blob: 9c77db57ed9276e6342f12e5a4a38a24a14559fe [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
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +020041 // If true, runs R8 in Proguard compatibility mode (default).
42 // Otherwise, runs R8 in full mode.
43 Proguard_compatibility *bool
44
Liz Kammera7a64f32020-07-09 15:16:41 -070045 // If true, optimize for size by removing unused code. Defaults to true for apps,
46 // false for libraries and tests.
47 Shrink *bool
48
49 // If true, optimize bytecode. Defaults to false.
50 Optimize *bool
51
52 // If true, obfuscate bytecode. Defaults to false.
53 Obfuscate *bool
54
55 // If true, do not use the flag files generated by aapt that automatically keep
56 // classes referenced by the app manifest. Defaults to false.
57 No_aapt_flags *bool
58
59 // Flags to pass to proguard.
60 Proguard_flags []string
61
62 // Specifies the locations of files containing proguard flags.
63 Proguard_flags_files []string `android:"path"`
64 }
65
66 // Keep the data uncompressed. We always need uncompressed dex for execution,
67 // so this might actually save space by avoiding storing the same data twice.
68 // This defaults to reasonable value based on module and should not be set.
69 // It exists only to support ART tests.
70 Uncompress_dex *bool
71}
72
73type dexer struct {
74 dexProperties DexProperties
75
76 // list of extra proguard flag files
77 extraProguardFlagFiles android.Paths
78 proguardDictionary android.OptionalPath
Colin Crosscb6143a2020-08-14 17:39:29 -070079 proguardUsageZip android.OptionalPath
Liz Kammera7a64f32020-07-09 15:16:41 -070080}
81
82func (d *dexer) effectiveOptimizeEnabled() bool {
83 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
84}
85
Kousik Kumar366afc52020-05-20 11:27:16 -070086var d8, d8RE = remoteexec.MultiCommandStaticRules(pctx, "d8",
Colin Crossf0056cb2017-12-22 15:56:08 -080087 blueprint.RuleParams{
88 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -070089 `$d8Template${config.D8Cmd} ${config.DexFlags} --output $outDir $d8Flags $in && ` +
90 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -070091 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Crossf0056cb2017-12-22 15:56:08 -080092 CommandDeps: []string{
93 "${config.D8Cmd}",
94 "${config.SoongZipCmd}",
95 "${config.MergeZipsCmd}",
96 },
Kousik Kumar366afc52020-05-20 11:27:16 -070097 }, map[string]*remoteexec.REParams{
98 "$d8Template": &remoteexec.REParams{
99 Labels: map[string]string{"type": "compile", "compiler": "d8"},
100 Inputs: []string{"${config.D8Jar}"},
101 ExecStrategy: "${config.RED8ExecStrategy}",
102 ToolchainInputs: []string{"${config.JavaCmd}"},
103 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
104 },
105 "$zipTemplate": &remoteexec.REParams{
106 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
107 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
108 OutputFiles: []string{"$outDir/classes.dex.jar"},
109 ExecStrategy: "${config.RED8ExecStrategy}",
110 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
111 },
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400112 }, []string{"outDir", "d8Flags", "zipFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800113
Kousik Kumar366afc52020-05-20 11:27:16 -0700114var r8, r8RE = remoteexec.MultiCommandStaticRules(pctx, "r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800115 blueprint.RuleParams{
116 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700117 `rm -f "$outDict" && rm -rf "${outUsageDir}" && ` +
118 `mkdir -p $$(dirname ${outUsage}) && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700119 `$r8Template${config.R8Cmd} ${config.DexFlags} -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200120 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700121 `-printmapping ${outDict} ` +
122 `-printusage ${outUsage} ` +
Colin Crossffb657e2018-09-21 12:29:22 -0700123 `$r8Flags && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700124 `touch "${outDict}" "${outUsage}" && ` +
125 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
126 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700127 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -0700128 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800129 CommandDeps: []string{
130 "${config.R8Cmd}",
131 "${config.SoongZipCmd}",
132 "${config.MergeZipsCmd}",
133 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700134 }, map[string]*remoteexec.REParams{
135 "$r8Template": &remoteexec.REParams{
136 Labels: map[string]string{"type": "compile", "compiler": "r8"},
137 Inputs: []string{"$implicits", "${config.R8Jar}"},
138 ExecStrategy: "${config.RER8ExecStrategy}",
139 ToolchainInputs: []string{"${config.JavaCmd}"},
140 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
141 },
142 "$zipTemplate": &remoteexec.REParams{
143 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
144 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
145 OutputFiles: []string{"$outDir/classes.dex.jar"},
146 ExecStrategy: "${config.RER8ExecStrategy}",
147 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
148 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700149 "$zipUsageTemplate": &remoteexec.REParams{
150 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
151 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
152 OutputFiles: []string{"${outUsageZip}"},
153 ExecStrategy: "${config.RER8ExecStrategy}",
154 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
155 },
156 }, []string{"outDir", "outDict", "outUsage", "outUsageZip", "outUsageDir",
157 "r8Flags", "zipFlags"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800158
Liz Kammera7a64f32020-07-09 15:16:41 -0700159func (d *dexer) dexCommonFlags(ctx android.ModuleContext, minSdkVersion sdkSpec) []string {
160 flags := d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000161 // Translate all the DX flags to D8 ones until all the build files have been migrated
162 // to D8 flags. See: b/69377755
163 flags = android.RemoveListFromList(flags,
164 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800165
166 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000167 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800168 }
169
170 if ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
171 flags = append(flags,
172 "--debug",
173 "--verbose")
Colin Crossf0056cb2017-12-22 15:56:08 -0800174 }
175
Liz Kammera7a64f32020-07-09 15:16:41 -0700176 effectiveVersion, err := minSdkVersion.effectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700177 if err != nil {
178 ctx.PropertyErrorf("min_sdk_version", "%s", err)
179 }
180
Liz Kammera7a64f32020-07-09 15:16:41 -0700181 flags = append(flags, "--min-api "+effectiveVersion.asNumberString())
Colin Crossf0056cb2017-12-22 15:56:08 -0800182 return flags
183}
184
Liz Kammera7a64f32020-07-09 15:16:41 -0700185func d8Flags(flags javaBuilderFlags) (d8Flags []string, d8Deps android.Paths) {
Colin Crossc2557d12019-10-31 15:22:57 -0700186 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
187 d8Flags = append(d8Flags, flags.classpath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700188
Colin Cross6dab9bd2018-09-28 08:06:24 -0700189 d8Deps = append(d8Deps, flags.bootClasspath...)
190 d8Deps = append(d8Deps, flags.classpath...)
191
192 return d8Flags, d8Deps
Colin Crossffb657e2018-09-21 12:29:22 -0700193}
194
Liz Kammera7a64f32020-07-09 15:16:41 -0700195func (d *dexer) r8Flags(ctx android.ModuleContext, flags javaBuilderFlags) (r8Flags []string, r8Deps android.Paths) {
196 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800197
198 // When an app contains references to APIs that are not in the SDK specified by
199 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000200 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800201 // ProGuard, to
202 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
203 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
204 // See b/20667396
205 var proguardRaiseDeps classpath
206 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(dep android.Module) {
207 proguardRaiseDeps = append(proguardRaiseDeps, dep.(Dependency).HeaderJars()...)
208 })
209
210 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
211 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
212 r8Flags = append(r8Flags, flags.classpath.FormJavaClassPath("-libraryjars"))
Colin Cross66dbc0b2017-12-28 12:23:20 -0800213
Colin Cross6dab9bd2018-09-28 08:06:24 -0700214 r8Deps = append(r8Deps, proguardRaiseDeps...)
215 r8Deps = append(r8Deps, flags.bootClasspath...)
216 r8Deps = append(r8Deps, flags.classpath...)
217
Colin Cross66dbc0b2017-12-28 12:23:20 -0800218 flagFiles := android.Paths{
219 android.PathForSource(ctx, "build/make/core/proguard.flags"),
220 }
221
Liz Kammera7a64f32020-07-09 15:16:41 -0700222 flagFiles = append(flagFiles, d.extraProguardFlagFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800223 // TODO(ccross): static android library proguard files
224
Liz Kammera7a64f32020-07-09 15:16:41 -0700225 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700226
Colin Cross66dbc0b2017-12-28 12:23:20 -0800227 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
228 r8Deps = append(r8Deps, flagFiles...)
229
230 // TODO(b/70942988): This is included from build/make/core/proguard.flags
231 r8Deps = append(r8Deps, android.PathForSource(ctx,
232 "build/make/core/proguard_basic_keeps.flags"))
233
Liz Kammera7a64f32020-07-09 15:16:41 -0700234 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800235
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200236 if BoolDefault(opt.Proguard_compatibility, true) {
237 r8Flags = append(r8Flags, "--force-proguard-compatibility")
238 }
239
Colin Cross66dbc0b2017-12-28 12:23:20 -0800240 // TODO(ccross): Don't shrink app instrumentation tests by default.
241 if !Bool(opt.Shrink) {
242 r8Flags = append(r8Flags, "-dontshrink")
243 }
244
245 if !Bool(opt.Optimize) {
246 r8Flags = append(r8Flags, "-dontoptimize")
247 }
248
249 // TODO(ccross): error if obufscation + app instrumentation test.
250 if !Bool(opt.Obfuscate) {
251 r8Flags = append(r8Flags, "-dontobfuscate")
252 }
Colin Cross4b964c02018-10-15 16:18:06 -0700253 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
254 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800255
Jaewoong Jung1d6eb682018-11-29 15:08:44 -0800256 // Don't strip out debug information for eng builds.
257 if ctx.Config().Eng() {
258 r8Flags = append(r8Flags, "--debug")
259 }
260
Colin Cross66dbc0b2017-12-28 12:23:20 -0800261 return r8Flags, r8Deps
262}
263
Liz Kammera7a64f32020-07-09 15:16:41 -0700264func (d *dexer) compileDex(ctx android.ModuleContext, flags javaBuilderFlags, minSdkVersion sdkSpec,
Colin Cross3063b782018-08-15 11:19:12 -0700265 classesJar android.Path, jarName string) android.ModuleOutPath {
Colin Crossf0056cb2017-12-22 15:56:08 -0800266
Colin Crossf0056cb2017-12-22 15:56:08 -0800267 // Compile classes.jar into classes.dex and then javalib.jar
268 javalibJar := android.PathForModuleOut(ctx, "dex", jarName)
269 outDir := android.PathForModuleOut(ctx, "dex")
270
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800271 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700272 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800273 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700274 }
275
Liz Kammera7a64f32020-07-09 15:16:41 -0700276 commonFlags := d.dexCommonFlags(ctx, minSdkVersion)
277
278 useR8 := d.effectiveOptimizeEnabled()
Colin Cross66dbc0b2017-12-28 12:23:20 -0800279 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700280 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700281 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Colin Crosscb6143a2020-08-14 17:39:29 -0700282 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
283 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
284 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
285 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
286 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Liz Kammera7a64f32020-07-09 15:16:41 -0700287 r8Flags, r8Deps := d.r8Flags(ctx, flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400288 rule := r8
289 args := map[string]string{
Colin Crosscb6143a2020-08-14 17:39:29 -0700290 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
291 "zipFlags": zipFlags,
292 "outDict": proguardDictionary.String(),
293 "outUsageDir": proguardUsageDir.String(),
294 "outUsage": proguardUsage.String(),
295 "outUsageZip": proguardUsageZip.String(),
296 "outDir": outDir.String(),
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400297 }
298 if ctx.Config().IsEnvTrue("RBE_R8") {
299 rule = r8RE
300 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
301 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800302 ctx.Build(pctx, android.BuildParams{
Colin Crosscb6143a2020-08-14 17:39:29 -0700303 Rule: rule,
304 Description: "r8",
305 Output: javalibJar,
306 ImplicitOutputs: android.WritablePaths{proguardDictionary, proguardUsageZip},
307 Input: classesJar,
308 Implicits: r8Deps,
309 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800310 })
311 } else {
Liz Kammera7a64f32020-07-09 15:16:41 -0700312 d8Flags, d8Deps := d8Flags(flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400313 rule := d8
314 if ctx.Config().IsEnvTrue("RBE_D8") {
315 rule = d8RE
316 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800317 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400318 Rule: rule,
Colin Crossbafb8972018-06-06 21:46:32 +0000319 Description: "d8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800320 Output: javalibJar,
321 Input: classesJar,
Colin Cross6dab9bd2018-09-28 08:06:24 -0700322 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800323 Args: map[string]string{
Liz Kammera7a64f32020-07-09 15:16:41 -0700324 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
Colin Cross5a0dcd52018-10-05 14:20:06 -0700325 "zipFlags": zipFlags,
326 "outDir": outDir.String(),
Colin Cross66dbc0b2017-12-28 12:23:20 -0800327 },
328 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800329 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700330 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000331 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", jarName)
332 TransformZipAlign(ctx, alignedJavalibJar, javalibJar)
333 javalibJar = alignedJavalibJar
334 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800335
Colin Crossf0056cb2017-12-22 15:56:08 -0800336 return javalibJar
337}