blob: 15b4431dbe44d63e89964eacfc8a3c6ca69a17b8 [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
Colin Crosscb6143a2020-08-14 17:39:29 -070075 proguardUsageZip android.OptionalPath
Liz Kammera7a64f32020-07-09 15:16:41 -070076}
77
78func (d *dexer) effectiveOptimizeEnabled() bool {
79 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
80}
81
Kousik Kumar366afc52020-05-20 11:27:16 -070082var d8, d8RE = remoteexec.MultiCommandStaticRules(pctx, "d8",
Colin Crossf0056cb2017-12-22 15:56:08 -080083 blueprint.RuleParams{
84 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -070085 `$d8Template${config.D8Cmd} ${config.DexFlags} --output $outDir $d8Flags $in && ` +
86 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -070087 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Crossf0056cb2017-12-22 15:56:08 -080088 CommandDeps: []string{
89 "${config.D8Cmd}",
90 "${config.SoongZipCmd}",
91 "${config.MergeZipsCmd}",
92 },
Kousik Kumar366afc52020-05-20 11:27:16 -070093 }, map[string]*remoteexec.REParams{
94 "$d8Template": &remoteexec.REParams{
95 Labels: map[string]string{"type": "compile", "compiler": "d8"},
96 Inputs: []string{"${config.D8Jar}"},
97 ExecStrategy: "${config.RED8ExecStrategy}",
98 ToolchainInputs: []string{"${config.JavaCmd}"},
99 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
100 },
101 "$zipTemplate": &remoteexec.REParams{
102 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
103 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
104 OutputFiles: []string{"$outDir/classes.dex.jar"},
105 ExecStrategy: "${config.RED8ExecStrategy}",
106 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
107 },
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400108 }, []string{"outDir", "d8Flags", "zipFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800109
Kousik Kumar366afc52020-05-20 11:27:16 -0700110var r8, r8RE = remoteexec.MultiCommandStaticRules(pctx, "r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800111 blueprint.RuleParams{
112 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700113 `rm -f "$outDict" && rm -rf "${outUsageDir}" && ` +
114 `mkdir -p $$(dirname ${outUsage}) && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700115 `$r8Template${config.R8Cmd} ${config.DexFlags} -injars $in --output $outDir ` +
Colin Cross66dbc0b2017-12-28 12:23:20 -0800116 `--force-proguard-compatibility ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200117 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700118 `-printmapping ${outDict} ` +
119 `-printusage ${outUsage} ` +
Colin Crossffb657e2018-09-21 12:29:22 -0700120 `$r8Flags && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700121 `touch "${outDict}" "${outUsage}" && ` +
122 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
123 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700124 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross4c03f682018-07-15 08:16:31 -0700125 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $out $outDir/classes.dex.jar $in`,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800126 CommandDeps: []string{
127 "${config.R8Cmd}",
128 "${config.SoongZipCmd}",
129 "${config.MergeZipsCmd}",
130 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700131 }, map[string]*remoteexec.REParams{
132 "$r8Template": &remoteexec.REParams{
133 Labels: map[string]string{"type": "compile", "compiler": "r8"},
134 Inputs: []string{"$implicits", "${config.R8Jar}"},
135 ExecStrategy: "${config.RER8ExecStrategy}",
136 ToolchainInputs: []string{"${config.JavaCmd}"},
137 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
138 },
139 "$zipTemplate": &remoteexec.REParams{
140 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
141 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
142 OutputFiles: []string{"$outDir/classes.dex.jar"},
143 ExecStrategy: "${config.RER8ExecStrategy}",
144 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
145 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700146 "$zipUsageTemplate": &remoteexec.REParams{
147 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
148 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
149 OutputFiles: []string{"${outUsageZip}"},
150 ExecStrategy: "${config.RER8ExecStrategy}",
151 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
152 },
153 }, []string{"outDir", "outDict", "outUsage", "outUsageZip", "outUsageDir",
154 "r8Flags", "zipFlags"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800155
Liz Kammera7a64f32020-07-09 15:16:41 -0700156func (d *dexer) dexCommonFlags(ctx android.ModuleContext, minSdkVersion sdkSpec) []string {
157 flags := d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000158 // Translate all the DX flags to D8 ones until all the build files have been migrated
159 // to D8 flags. See: b/69377755
160 flags = android.RemoveListFromList(flags,
161 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800162
163 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000164 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800165 }
166
167 if ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
168 flags = append(flags,
169 "--debug",
170 "--verbose")
Colin Crossf0056cb2017-12-22 15:56:08 -0800171 }
172
Liz Kammera7a64f32020-07-09 15:16:41 -0700173 effectiveVersion, err := minSdkVersion.effectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700174 if err != nil {
175 ctx.PropertyErrorf("min_sdk_version", "%s", err)
176 }
177
Liz Kammera7a64f32020-07-09 15:16:41 -0700178 flags = append(flags, "--min-api "+effectiveVersion.asNumberString())
Colin Crossf0056cb2017-12-22 15:56:08 -0800179 return flags
180}
181
Liz Kammera7a64f32020-07-09 15:16:41 -0700182func d8Flags(flags javaBuilderFlags) (d8Flags []string, d8Deps android.Paths) {
Colin Crossc2557d12019-10-31 15:22:57 -0700183 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
184 d8Flags = append(d8Flags, flags.classpath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700185
Colin Cross6dab9bd2018-09-28 08:06:24 -0700186 d8Deps = append(d8Deps, flags.bootClasspath...)
187 d8Deps = append(d8Deps, flags.classpath...)
188
189 return d8Flags, d8Deps
Colin Crossffb657e2018-09-21 12:29:22 -0700190}
191
Liz Kammera7a64f32020-07-09 15:16:41 -0700192func (d *dexer) r8Flags(ctx android.ModuleContext, flags javaBuilderFlags) (r8Flags []string, r8Deps android.Paths) {
193 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800194
195 // When an app contains references to APIs that are not in the SDK specified by
196 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000197 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800198 // ProGuard, to
199 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
200 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
201 // See b/20667396
202 var proguardRaiseDeps classpath
203 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(dep android.Module) {
204 proguardRaiseDeps = append(proguardRaiseDeps, dep.(Dependency).HeaderJars()...)
205 })
206
207 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
208 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
209 r8Flags = append(r8Flags, flags.classpath.FormJavaClassPath("-libraryjars"))
Colin Cross66dbc0b2017-12-28 12:23:20 -0800210
Colin Cross6dab9bd2018-09-28 08:06:24 -0700211 r8Deps = append(r8Deps, proguardRaiseDeps...)
212 r8Deps = append(r8Deps, flags.bootClasspath...)
213 r8Deps = append(r8Deps, flags.classpath...)
214
Colin Cross66dbc0b2017-12-28 12:23:20 -0800215 flagFiles := android.Paths{
216 android.PathForSource(ctx, "build/make/core/proguard.flags"),
217 }
218
Liz Kammera7a64f32020-07-09 15:16:41 -0700219 flagFiles = append(flagFiles, d.extraProguardFlagFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800220 // TODO(ccross): static android library proguard files
221
Liz Kammera7a64f32020-07-09 15:16:41 -0700222 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700223
Colin Cross66dbc0b2017-12-28 12:23:20 -0800224 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
225 r8Deps = append(r8Deps, flagFiles...)
226
227 // TODO(b/70942988): This is included from build/make/core/proguard.flags
228 r8Deps = append(r8Deps, android.PathForSource(ctx,
229 "build/make/core/proguard_basic_keeps.flags"))
230
Liz Kammera7a64f32020-07-09 15:16:41 -0700231 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800232
233 // TODO(ccross): Don't shrink app instrumentation tests by default.
234 if !Bool(opt.Shrink) {
235 r8Flags = append(r8Flags, "-dontshrink")
236 }
237
238 if !Bool(opt.Optimize) {
239 r8Flags = append(r8Flags, "-dontoptimize")
240 }
241
242 // TODO(ccross): error if obufscation + app instrumentation test.
243 if !Bool(opt.Obfuscate) {
244 r8Flags = append(r8Flags, "-dontobfuscate")
245 }
Colin Cross4b964c02018-10-15 16:18:06 -0700246 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
247 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800248
Jaewoong Jung1d6eb682018-11-29 15:08:44 -0800249 // Don't strip out debug information for eng builds.
250 if ctx.Config().Eng() {
251 r8Flags = append(r8Flags, "--debug")
252 }
253
Colin Cross66dbc0b2017-12-28 12:23:20 -0800254 return r8Flags, r8Deps
255}
256
Liz Kammera7a64f32020-07-09 15:16:41 -0700257func (d *dexer) compileDex(ctx android.ModuleContext, flags javaBuilderFlags, minSdkVersion sdkSpec,
Colin Cross3063b782018-08-15 11:19:12 -0700258 classesJar android.Path, jarName string) android.ModuleOutPath {
Colin Crossf0056cb2017-12-22 15:56:08 -0800259
Colin Crossf0056cb2017-12-22 15:56:08 -0800260 // Compile classes.jar into classes.dex and then javalib.jar
261 javalibJar := android.PathForModuleOut(ctx, "dex", jarName)
262 outDir := android.PathForModuleOut(ctx, "dex")
263
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800264 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700265 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800266 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700267 }
268
Liz Kammera7a64f32020-07-09 15:16:41 -0700269 commonFlags := d.dexCommonFlags(ctx, minSdkVersion)
270
271 useR8 := d.effectiveOptimizeEnabled()
Colin Cross66dbc0b2017-12-28 12:23:20 -0800272 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700273 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700274 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Colin Crosscb6143a2020-08-14 17:39:29 -0700275 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
276 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
277 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
278 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
279 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Liz Kammera7a64f32020-07-09 15:16:41 -0700280 r8Flags, r8Deps := d.r8Flags(ctx, flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400281 rule := r8
282 args := map[string]string{
Colin Crosscb6143a2020-08-14 17:39:29 -0700283 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
284 "zipFlags": zipFlags,
285 "outDict": proguardDictionary.String(),
286 "outUsageDir": proguardUsageDir.String(),
287 "outUsage": proguardUsage.String(),
288 "outUsageZip": proguardUsageZip.String(),
289 "outDir": outDir.String(),
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400290 }
Ramy Medhat16f23a42020-09-03 01:29:49 -0400291 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400292 rule = r8RE
293 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
294 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800295 ctx.Build(pctx, android.BuildParams{
Colin Crosscb6143a2020-08-14 17:39:29 -0700296 Rule: rule,
297 Description: "r8",
298 Output: javalibJar,
299 ImplicitOutputs: android.WritablePaths{proguardDictionary, proguardUsageZip},
300 Input: classesJar,
301 Implicits: r8Deps,
302 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800303 })
304 } else {
Liz Kammera7a64f32020-07-09 15:16:41 -0700305 d8Flags, d8Deps := d8Flags(flags)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400306 rule := d8
Ramy Medhat16f23a42020-09-03 01:29:49 -0400307 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400308 rule = d8RE
309 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800310 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400311 Rule: rule,
Colin Crossbafb8972018-06-06 21:46:32 +0000312 Description: "d8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800313 Output: javalibJar,
314 Input: classesJar,
Colin Cross6dab9bd2018-09-28 08:06:24 -0700315 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800316 Args: map[string]string{
Liz Kammera7a64f32020-07-09 15:16:41 -0700317 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
Colin Cross5a0dcd52018-10-05 14:20:06 -0700318 "zipFlags": zipFlags,
319 "outDir": outDir.String(),
Colin Cross66dbc0b2017-12-28 12:23:20 -0800320 },
321 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800322 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700323 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000324 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", jarName)
325 TransformZipAlign(ctx, alignedJavalibJar, javalibJar)
326 javalibJar = alignedJavalibJar
327 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800328
Colin Crossf0056cb2017-12-22 15:56:08 -0800329 return javalibJar
330}