blob: cd45a931996127bb08c7e2183f9e520b40d430ac [file] [log] [blame]
Colin Crossf0056cb2017-12-22 15:56:08 -08001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "strings"
19
20 "github.com/google/blueprint"
David Srbeckye033cba2020-05-20 22:20:28 +010021 "github.com/google/blueprint/proptools"
Colin Crossf0056cb2017-12-22 15:56:08 -080022
23 "android/soong/android"
Ramy Medhat1dcc27e2020-04-21 21:36:23 -040024 "android/soong/remoteexec"
Colin Crossf0056cb2017-12-22 15:56:08 -080025)
26
Liz Kammera7a64f32020-07-09 15:16:41 -070027type DexProperties struct {
28 // If set to true, compile dex regardless of installable. Defaults to false.
29 Compile_dex *bool
30
31 // list of module-specific flags that will be used for dex compiles
32 Dxflags []string `android:"arch_variant"`
33
34 Optimize struct {
35 // If false, disable all optimization. Defaults to true for android_app and android_test
36 // modules, false for java_library and java_test modules.
37 Enabled *bool
38 // True if the module containing this has it set by default.
39 EnabledByDefault bool `blueprint:"mutated"`
40
41 // If true, optimize for size by removing unused code. Defaults to true for apps,
42 // false for libraries and tests.
43 Shrink *bool
44
45 // If true, optimize bytecode. Defaults to false.
46 Optimize *bool
47
48 // If true, obfuscate bytecode. Defaults to false.
49 Obfuscate *bool
50
51 // If true, do not use the flag files generated by aapt that automatically keep
52 // classes referenced by the app manifest. Defaults to false.
53 No_aapt_flags *bool
54
55 // Flags to pass to proguard.
56 Proguard_flags []string
57
58 // Specifies the locations of files containing proguard flags.
59 Proguard_flags_files []string `android:"path"`
60 }
61
62 // Keep the data uncompressed. We always need uncompressed dex for execution,
63 // so this might actually save space by avoiding storing the same data twice.
64 // This defaults to reasonable value based on module and should not be set.
65 // It exists only to support ART tests.
66 Uncompress_dex *bool
67}
68
69type dexer struct {
70 dexProperties DexProperties
71
72 // list of extra proguard flag files
73 extraProguardFlagFiles android.Paths
74 proguardDictionary android.OptionalPath
75}
76
77func (d *dexer) effectiveOptimizeEnabled() bool {
78 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
79}
80
Kousik Kumar366afc52020-05-20 11:27:16 -070081var d8, d8RE = remoteexec.MultiCommandStaticRules(pctx, "d8",
Colin Crossf0056cb2017-12-22 15:56:08 -080082 blueprint.RuleParams{
83 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -070084 `$d8Template${config.D8Cmd} ${config.DexFlags} --output $outDir $d8Flags $in && ` +
85 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -070086 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Crossf0056cb2017-12-22 15:56:08 -080087 CommandDeps: []string{
88 "${config.D8Cmd}",
89 "${config.SoongZipCmd}",
90 "${config.MergeZipsCmd}",
91 },
Kousik Kumar366afc52020-05-20 11:27:16 -070092 }, map[string]*remoteexec.REParams{
93 "$d8Template": &remoteexec.REParams{
94 Labels: map[string]string{"type": "compile", "compiler": "d8"},
95 Inputs: []string{"${config.D8Jar}"},
96 ExecStrategy: "${config.RED8ExecStrategy}",
97 ToolchainInputs: []string{"${config.JavaCmd}"},
98 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
99 },
100 "$zipTemplate": &remoteexec.REParams{
101 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
102 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
103 OutputFiles: []string{"$outDir/classes.dex.jar"},
104 ExecStrategy: "${config.RED8ExecStrategy}",
105 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
106 },
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400107 }, []string{"outDir", "d8Flags", "zipFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800108
Kousik Kumar366afc52020-05-20 11:27:16 -0700109var r8, r8RE = remoteexec.MultiCommandStaticRules(pctx, "r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800110 blueprint.RuleParams{
111 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Søren Gjesse0e849352018-08-22 16:16:23 +0200112 `rm -f "$outDict" && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700113 `$r8Template${config.R8Cmd} ${config.DexFlags} -injars $in --output $outDir ` +
Colin Cross66dbc0b2017-12-28 12:23:20 -0800114 `--force-proguard-compatibility ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200115 `--no-data-resources ` +
Colin Cross66dbc0b2017-12-28 12:23:20 -0800116 `-printmapping $outDict ` +
Colin Crossffb657e2018-09-21 12:29:22 -0700117 `$r8Flags && ` +
Søren Gjesse0e849352018-08-22 16:16:23 +0200118 `touch "$outDict" && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700119 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -0700120 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800121 CommandDeps: []string{
122 "${config.R8Cmd}",
123 "${config.SoongZipCmd}",
124 "${config.MergeZipsCmd}",
125 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700126 }, map[string]*remoteexec.REParams{
127 "$r8Template": &remoteexec.REParams{
128 Labels: map[string]string{"type": "compile", "compiler": "r8"},
129 Inputs: []string{"$implicits", "${config.R8Jar}"},
130 ExecStrategy: "${config.RER8ExecStrategy}",
131 ToolchainInputs: []string{"${config.JavaCmd}"},
132 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
133 },
134 "$zipTemplate": &remoteexec.REParams{
135 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
136 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
137 OutputFiles: []string{"$outDir/classes.dex.jar"},
138 ExecStrategy: "${config.RER8ExecStrategy}",
139 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
140 },
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400141 }, []string{"outDir", "outDict", "r8Flags", "zipFlags"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800142
Liz Kammera7a64f32020-07-09 15:16:41 -0700143func (d *dexer) dexCommonFlags(ctx android.ModuleContext, minSdkVersion sdkSpec) []string {
144 flags := d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000145 // Translate all the DX flags to D8 ones until all the build files have been migrated
146 // to D8 flags. See: b/69377755
147 flags = android.RemoveListFromList(flags,
148 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800149
150 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000151 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800152 }
153
154 if ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
155 flags = append(flags,
156 "--debug",
157 "--verbose")
Colin Crossf0056cb2017-12-22 15:56:08 -0800158 }
159
Liz Kammera7a64f32020-07-09 15:16:41 -0700160 effectiveVersion, err := minSdkVersion.effectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700161 if err != nil {
162 ctx.PropertyErrorf("min_sdk_version", "%s", err)
163 }
164
Liz Kammera7a64f32020-07-09 15:16:41 -0700165 flags = append(flags, "--min-api "+effectiveVersion.asNumberString())
Colin Crossf0056cb2017-12-22 15:56:08 -0800166 return flags
167}
168
Liz Kammera7a64f32020-07-09 15:16:41 -0700169func d8Flags(flags javaBuilderFlags) (d8Flags []string, d8Deps android.Paths) {
Colin Crossc2557d12019-10-31 15:22:57 -0700170 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
171 d8Flags = append(d8Flags, flags.classpath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700172
Colin Cross6dab9bd2018-09-28 08:06:24 -0700173 d8Deps = append(d8Deps, flags.bootClasspath...)
174 d8Deps = append(d8Deps, flags.classpath...)
175
176 return d8Flags, d8Deps
Colin Crossffb657e2018-09-21 12:29:22 -0700177}
178
Liz Kammera7a64f32020-07-09 15:16:41 -0700179func (d *dexer) r8Flags(ctx android.ModuleContext, flags javaBuilderFlags) (r8Flags []string, r8Deps android.Paths) {
180 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800181
182 // When an app contains references to APIs that are not in the SDK specified by
183 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000184 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800185 // ProGuard, to
186 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
187 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
188 // See b/20667396
189 var proguardRaiseDeps classpath
190 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(dep android.Module) {
191 proguardRaiseDeps = append(proguardRaiseDeps, dep.(Dependency).HeaderJars()...)
192 })
193
194 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
195 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
196 r8Flags = append(r8Flags, flags.classpath.FormJavaClassPath("-libraryjars"))
Colin Cross66dbc0b2017-12-28 12:23:20 -0800197
Colin Cross6dab9bd2018-09-28 08:06:24 -0700198 r8Deps = append(r8Deps, proguardRaiseDeps...)
199 r8Deps = append(r8Deps, flags.bootClasspath...)
200 r8Deps = append(r8Deps, flags.classpath...)
201
Colin Cross66dbc0b2017-12-28 12:23:20 -0800202 flagFiles := android.Paths{
203 android.PathForSource(ctx, "build/make/core/proguard.flags"),
204 }
205
Liz Kammera7a64f32020-07-09 15:16:41 -0700206 flagFiles = append(flagFiles, d.extraProguardFlagFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800207 // TODO(ccross): static android library proguard files
208
Liz Kammera7a64f32020-07-09 15:16:41 -0700209 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700210
Colin Cross66dbc0b2017-12-28 12:23:20 -0800211 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
212 r8Deps = append(r8Deps, flagFiles...)
213
214 // TODO(b/70942988): This is included from build/make/core/proguard.flags
215 r8Deps = append(r8Deps, android.PathForSource(ctx,
216 "build/make/core/proguard_basic_keeps.flags"))
217
Liz Kammera7a64f32020-07-09 15:16:41 -0700218 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800219
220 // TODO(ccross): Don't shrink app instrumentation tests by default.
221 if !Bool(opt.Shrink) {
222 r8Flags = append(r8Flags, "-dontshrink")
223 }
224
225 if !Bool(opt.Optimize) {
226 r8Flags = append(r8Flags, "-dontoptimize")
227 }
228
229 // TODO(ccross): error if obufscation + app instrumentation test.
230 if !Bool(opt.Obfuscate) {
231 r8Flags = append(r8Flags, "-dontobfuscate")
232 }
Colin Cross4b964c02018-10-15 16:18:06 -0700233 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
234 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800235
Jaewoong Jung1d6eb682018-11-29 15:08:44 -0800236 // Don't strip out debug information for eng builds.
237 if ctx.Config().Eng() {
238 r8Flags = append(r8Flags, "--debug")
239 }
240
Colin Cross66dbc0b2017-12-28 12:23:20 -0800241 return r8Flags, r8Deps
242}
243
Liz Kammera7a64f32020-07-09 15:16:41 -0700244func (d *dexer) compileDex(ctx android.ModuleContext, flags javaBuilderFlags, minSdkVersion sdkSpec,
Colin Cross3063b782018-08-15 11:19:12 -0700245 classesJar android.Path, jarName string) android.ModuleOutPath {
Colin Crossf0056cb2017-12-22 15:56:08 -0800246
Colin Crossf0056cb2017-12-22 15:56:08 -0800247 // Compile classes.jar into classes.dex and then javalib.jar
248 javalibJar := android.PathForModuleOut(ctx, "dex", jarName)
249 outDir := android.PathForModuleOut(ctx, "dex")
250
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800251 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700252 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800253 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700254 }
255
Liz Kammera7a64f32020-07-09 15:16:41 -0700256 commonFlags := d.dexCommonFlags(ctx, minSdkVersion)
257
258 useR8 := d.effectiveOptimizeEnabled()
Colin Cross66dbc0b2017-12-28 12:23:20 -0800259 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700260 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700261 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
262 r8Flags, r8Deps := d.r8Flags(ctx, flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400263 rule := r8
264 args := map[string]string{
Liz Kammera7a64f32020-07-09 15:16:41 -0700265 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400266 "zipFlags": zipFlags,
Liz Kammera7a64f32020-07-09 15:16:41 -0700267 "outDict": proguardDictionary.String(),
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400268 "outDir": outDir.String(),
269 }
270 if ctx.Config().IsEnvTrue("RBE_R8") {
271 rule = r8RE
272 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
273 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800274 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400275 Rule: rule,
Colin Crossc0c664c2018-05-16 16:47:21 -0700276 Description: "r8",
277 Output: javalibJar,
278 ImplicitOutput: proguardDictionary,
279 Input: classesJar,
280 Implicits: r8Deps,
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400281 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800282 })
283 } else {
Liz Kammera7a64f32020-07-09 15:16:41 -0700284 d8Flags, d8Deps := d8Flags(flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400285 rule := d8
286 if ctx.Config().IsEnvTrue("RBE_D8") {
287 rule = d8RE
288 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800289 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400290 Rule: rule,
Colin Crossbafb8972018-06-06 21:46:32 +0000291 Description: "d8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800292 Output: javalibJar,
293 Input: classesJar,
Colin Cross6dab9bd2018-09-28 08:06:24 -0700294 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800295 Args: map[string]string{
Liz Kammera7a64f32020-07-09 15:16:41 -0700296 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
Colin Cross5a0dcd52018-10-05 14:20:06 -0700297 "zipFlags": zipFlags,
298 "outDir": outDir.String(),
Colin Cross66dbc0b2017-12-28 12:23:20 -0800299 },
300 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800301 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700302 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000303 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", jarName)
304 TransformZipAlign(ctx, alignedJavalibJar, javalibJar)
305 javalibJar = alignedJavalibJar
306 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800307
Colin Crossf0056cb2017-12-22 15:56:08 -0800308 return javalibJar
309}