blob: 24600c20f4a4c09a23204e5feaeac0ef6eb59889 [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}"},
Colin Crosse00c0e72020-09-17 11:54:30 -0700138 OutputFiles: []string{"${outUsage}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700139 ExecStrategy: "${config.RER8ExecStrategy}",
140 ToolchainInputs: []string{"${config.JavaCmd}"},
141 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
142 },
143 "$zipTemplate": &remoteexec.REParams{
144 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
145 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
146 OutputFiles: []string{"$outDir/classes.dex.jar"},
147 ExecStrategy: "${config.RER8ExecStrategy}",
148 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
149 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700150 "$zipUsageTemplate": &remoteexec.REParams{
151 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
152 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
153 OutputFiles: []string{"${outUsageZip}"},
154 ExecStrategy: "${config.RER8ExecStrategy}",
155 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
156 },
157 }, []string{"outDir", "outDict", "outUsage", "outUsageZip", "outUsageDir",
158 "r8Flags", "zipFlags"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800159
Liz Kammera7a64f32020-07-09 15:16:41 -0700160func (d *dexer) dexCommonFlags(ctx android.ModuleContext, minSdkVersion sdkSpec) []string {
161 flags := d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000162 // Translate all the DX flags to D8 ones until all the build files have been migrated
163 // to D8 flags. See: b/69377755
164 flags = android.RemoveListFromList(flags,
165 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800166
167 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000168 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800169 }
170
171 if ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
172 flags = append(flags,
173 "--debug",
174 "--verbose")
Colin Crossf0056cb2017-12-22 15:56:08 -0800175 }
176
Liz Kammera7a64f32020-07-09 15:16:41 -0700177 effectiveVersion, err := minSdkVersion.effectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700178 if err != nil {
179 ctx.PropertyErrorf("min_sdk_version", "%s", err)
180 }
181
Liz Kammera7a64f32020-07-09 15:16:41 -0700182 flags = append(flags, "--min-api "+effectiveVersion.asNumberString())
Colin Crossf0056cb2017-12-22 15:56:08 -0800183 return flags
184}
185
Liz Kammera7a64f32020-07-09 15:16:41 -0700186func d8Flags(flags javaBuilderFlags) (d8Flags []string, d8Deps android.Paths) {
Colin Crossc2557d12019-10-31 15:22:57 -0700187 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
188 d8Flags = append(d8Flags, flags.classpath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700189
Colin Cross6dab9bd2018-09-28 08:06:24 -0700190 d8Deps = append(d8Deps, flags.bootClasspath...)
191 d8Deps = append(d8Deps, flags.classpath...)
192
193 return d8Flags, d8Deps
Colin Crossffb657e2018-09-21 12:29:22 -0700194}
195
Liz Kammera7a64f32020-07-09 15:16:41 -0700196func (d *dexer) r8Flags(ctx android.ModuleContext, flags javaBuilderFlags) (r8Flags []string, r8Deps android.Paths) {
197 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800198
199 // When an app contains references to APIs that are not in the SDK specified by
200 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000201 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800202 // ProGuard, to
203 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
204 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
205 // See b/20667396
206 var proguardRaiseDeps classpath
207 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(dep android.Module) {
208 proguardRaiseDeps = append(proguardRaiseDeps, dep.(Dependency).HeaderJars()...)
209 })
210
211 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
212 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
213 r8Flags = append(r8Flags, flags.classpath.FormJavaClassPath("-libraryjars"))
Colin Cross66dbc0b2017-12-28 12:23:20 -0800214
Colin Cross6dab9bd2018-09-28 08:06:24 -0700215 r8Deps = append(r8Deps, proguardRaiseDeps...)
216 r8Deps = append(r8Deps, flags.bootClasspath...)
217 r8Deps = append(r8Deps, flags.classpath...)
218
Colin Cross66dbc0b2017-12-28 12:23:20 -0800219 flagFiles := android.Paths{
220 android.PathForSource(ctx, "build/make/core/proguard.flags"),
221 }
222
Liz Kammera7a64f32020-07-09 15:16:41 -0700223 flagFiles = append(flagFiles, d.extraProguardFlagFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800224 // TODO(ccross): static android library proguard files
225
Liz Kammera7a64f32020-07-09 15:16:41 -0700226 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700227
Colin Cross66dbc0b2017-12-28 12:23:20 -0800228 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
229 r8Deps = append(r8Deps, flagFiles...)
230
231 // TODO(b/70942988): This is included from build/make/core/proguard.flags
232 r8Deps = append(r8Deps, android.PathForSource(ctx,
233 "build/make/core/proguard_basic_keeps.flags"))
234
Liz Kammera7a64f32020-07-09 15:16:41 -0700235 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800236
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200237 if BoolDefault(opt.Proguard_compatibility, true) {
238 r8Flags = append(r8Flags, "--force-proguard-compatibility")
239 }
240
Colin Cross66dbc0b2017-12-28 12:23:20 -0800241 // TODO(ccross): Don't shrink app instrumentation tests by default.
242 if !Bool(opt.Shrink) {
243 r8Flags = append(r8Flags, "-dontshrink")
244 }
245
246 if !Bool(opt.Optimize) {
247 r8Flags = append(r8Flags, "-dontoptimize")
248 }
249
250 // TODO(ccross): error if obufscation + app instrumentation test.
251 if !Bool(opt.Obfuscate) {
252 r8Flags = append(r8Flags, "-dontobfuscate")
253 }
Colin Cross4b964c02018-10-15 16:18:06 -0700254 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
255 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800256
Jaewoong Jung1d6eb682018-11-29 15:08:44 -0800257 // Don't strip out debug information for eng builds.
258 if ctx.Config().Eng() {
259 r8Flags = append(r8Flags, "--debug")
260 }
261
Colin Cross66dbc0b2017-12-28 12:23:20 -0800262 return r8Flags, r8Deps
263}
264
Liz Kammera7a64f32020-07-09 15:16:41 -0700265func (d *dexer) compileDex(ctx android.ModuleContext, flags javaBuilderFlags, minSdkVersion sdkSpec,
Paul Duffin612e6102021-02-02 13:38:13 +0000266 classesJar android.Path, jarName string) android.OutputPath {
Colin Crossf0056cb2017-12-22 15:56:08 -0800267
Colin Crossf0056cb2017-12-22 15:56:08 -0800268 // Compile classes.jar into classes.dex and then javalib.jar
Paul Duffin612e6102021-02-02 13:38:13 +0000269 javalibJar := android.PathForModuleOut(ctx, "dex", jarName).OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800270 outDir := android.PathForModuleOut(ctx, "dex")
271
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800272 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700273 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800274 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700275 }
276
Liz Kammera7a64f32020-07-09 15:16:41 -0700277 commonFlags := d.dexCommonFlags(ctx, minSdkVersion)
278
279 useR8 := d.effectiveOptimizeEnabled()
Colin Cross66dbc0b2017-12-28 12:23:20 -0800280 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700281 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700282 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Colin Crosscb6143a2020-08-14 17:39:29 -0700283 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
284 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
285 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
286 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
287 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Liz Kammera7a64f32020-07-09 15:16:41 -0700288 r8Flags, r8Deps := d.r8Flags(ctx, flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400289 rule := r8
290 args := map[string]string{
Colin Crosscb6143a2020-08-14 17:39:29 -0700291 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
292 "zipFlags": zipFlags,
293 "outDict": proguardDictionary.String(),
294 "outUsageDir": proguardUsageDir.String(),
295 "outUsage": proguardUsage.String(),
296 "outUsageZip": proguardUsageZip.String(),
297 "outDir": outDir.String(),
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400298 }
Ramy Medhat16f23a42020-09-03 01:29:49 -0400299 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400300 rule = r8RE
301 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
302 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800303 ctx.Build(pctx, android.BuildParams{
Colin Crosscb6143a2020-08-14 17:39:29 -0700304 Rule: rule,
305 Description: "r8",
306 Output: javalibJar,
307 ImplicitOutputs: android.WritablePaths{proguardDictionary, proguardUsageZip},
308 Input: classesJar,
309 Implicits: r8Deps,
310 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800311 })
312 } else {
Liz Kammera7a64f32020-07-09 15:16:41 -0700313 d8Flags, d8Deps := d8Flags(flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400314 rule := d8
Ramy Medhat16f23a42020-09-03 01:29:49 -0400315 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400316 rule = d8RE
317 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800318 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400319 Rule: rule,
Colin Crossbafb8972018-06-06 21:46:32 +0000320 Description: "d8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800321 Output: javalibJar,
322 Input: classesJar,
Colin Cross6dab9bd2018-09-28 08:06:24 -0700323 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800324 Args: map[string]string{
Liz Kammera7a64f32020-07-09 15:16:41 -0700325 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
Colin Cross5a0dcd52018-10-05 14:20:06 -0700326 "zipFlags": zipFlags,
327 "outDir": outDir.String(),
Colin Cross66dbc0b2017-12-28 12:23:20 -0800328 },
329 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800330 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700331 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Paul Duffin612e6102021-02-02 13:38:13 +0000332 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", jarName).OutputPath
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000333 TransformZipAlign(ctx, alignedJavalibJar, javalibJar)
334 javalibJar = alignedJavalibJar
335 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800336
Colin Crossf0056cb2017-12-22 15:56:08 -0800337 return javalibJar
338}