blob: 6caaa7f4892175041fef2868b25299f24c0036c3 [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 (
Jiyong Park54105c42021-03-31 18:17:53 +090018 "strconv"
Colin Crossf0056cb2017-12-22 15:56:08 -080019 "strings"
20
21 "github.com/google/blueprint"
David Srbeckye033cba2020-05-20 22:20:28 +010022 "github.com/google/blueprint/proptools"
Colin Crossf0056cb2017-12-22 15:56:08 -080023
24 "android/soong/android"
Ramy Medhat1dcc27e2020-04-21 21:36:23 -040025 "android/soong/remoteexec"
Colin Crossf0056cb2017-12-22 15:56:08 -080026)
27
Liz Kammera7a64f32020-07-09 15:16:41 -070028type DexProperties struct {
29 // If set to true, compile dex regardless of installable. Defaults to false.
30 Compile_dex *bool
31
32 // list of module-specific flags that will be used for dex compiles
33 Dxflags []string `android:"arch_variant"`
34
Colin Cross5ea963e2021-09-16 19:13:43 -070035 // A list of files containing rules that specify the classes to keep in the main dex file.
36 Main_dex_rules []string `android:"path"`
37
Liz Kammera7a64f32020-07-09 15:16:41 -070038 Optimize struct {
Jared Duke63a3da92022-06-02 19:11:14 +000039 // If false, disable all optimization. Defaults to true for android_app and
40 // android_test_helper_app modules, false for android_test, java_library, and java_test modules.
Liz Kammera7a64f32020-07-09 15:16:41 -070041 Enabled *bool
42 // True if the module containing this has it set by default.
43 EnabledByDefault bool `blueprint:"mutated"`
44
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +000045 // Whether to continue building even if warnings are emitted. Defaults to true.
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +090046 Ignore_warnings *bool
47
Jared Dukeaa88b3d2023-08-29 17:07:20 +000048 // If true, runs R8 in Proguard compatibility mode, otherwise runs R8 in full mode.
49 // Defaults to false for apps, true for libraries and tests.
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +020050 Proguard_compatibility *bool
51
Liz Kammera7a64f32020-07-09 15:16:41 -070052 // If true, optimize for size by removing unused code. Defaults to true for apps,
53 // false for libraries and tests.
54 Shrink *bool
55
56 // If true, optimize bytecode. Defaults to false.
57 Optimize *bool
58
59 // If true, obfuscate bytecode. Defaults to false.
60 Obfuscate *bool
61
62 // If true, do not use the flag files generated by aapt that automatically keep
63 // classes referenced by the app manifest. Defaults to false.
64 No_aapt_flags *bool
65
Jared Duke51b0a102022-09-27 16:53:11 -070066 // If true, optimize for size by removing unused resources. Defaults to false.
Rico Wind351bac92022-09-22 10:41:42 +020067 Shrink_resources *bool
68
Rico Winda2fa2632024-03-13 13:09:17 +010069 // If true, use optimized resource shrinking in R8, overriding the
70 // Shrink_resources setting. Defaults to false.
71 // Optimized shrinking means that R8 will trace and treeshake resources together with code
72 // and apply additional optimizations. This implies non final fields in the R classes.
73 Optimized_shrink_resources *bool
74
Liz Kammera7a64f32020-07-09 15:16:41 -070075 // Flags to pass to proguard.
76 Proguard_flags []string
77
78 // Specifies the locations of files containing proguard flags.
79 Proguard_flags_files []string `android:"path"`
Sam Delmerico95d70942023-08-02 18:00:35 -040080
81 // If true, transitive reverse dependencies of this module will have this
82 // module's proguard spec appended to their optimization action
83 Export_proguard_flags_files *bool
Liz Kammera7a64f32020-07-09 15:16:41 -070084 }
85
86 // Keep the data uncompressed. We always need uncompressed dex for execution,
87 // so this might actually save space by avoiding storing the same data twice.
88 // This defaults to reasonable value based on module and should not be set.
89 // It exists only to support ART tests.
90 Uncompress_dex *bool
Wei Li1e73c652021-12-06 13:35:11 -080091
Wei Li92cd54b2022-01-12 13:22:55 -080092 // Exclude kotlinc generate files: *.kotlin_module, *.kotlin_builtins. Defaults to false.
Wei Li1e73c652021-12-06 13:35:11 -080093 Exclude_kotlinc_generated_files *bool
Liz Kammera7a64f32020-07-09 15:16:41 -070094}
95
96type dexer struct {
97 dexProperties DexProperties
98
99 // list of extra proguard flag files
Colin Cross312634e2023-11-21 15:13:56 -0800100 extraProguardFlagsFiles android.Paths
101 proguardDictionary android.OptionalPath
102 proguardConfiguration android.OptionalPath
103 proguardUsageZip android.OptionalPath
104 resourcesInput android.OptionalPath
105 resourcesOutput android.OptionalPath
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500106
107 providesTransitiveHeaderJars
Liz Kammera7a64f32020-07-09 15:16:41 -0700108}
109
110func (d *dexer) effectiveOptimizeEnabled() bool {
111 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
112}
113
Rico Winda2fa2632024-03-13 13:09:17 +0100114func (d *DexProperties) resourceShrinkingEnabled() bool {
115 return BoolDefault(d.Optimize.Optimized_shrink_resources, Bool(d.Optimize.Shrink_resources))
116}
117
Colin Cross77cdcfd2021-03-12 11:28:25 -0800118var d8, d8RE = pctx.MultiCommandRemoteStaticRules("d8",
Colin Crossf0056cb2017-12-22 15:56:08 -0800119 blueprint.RuleParams{
120 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000121 `$d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700122 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700123 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Ian Zernydb2d35b2023-10-10 12:22:39 +0200124 `rm -f "$outDir/classes*.dex" "$outDir/classes.dex.jar"`,
Colin Crossf0056cb2017-12-22 15:56:08 -0800125 CommandDeps: []string{
126 "${config.D8Cmd}",
127 "${config.SoongZipCmd}",
128 "${config.MergeZipsCmd}",
129 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700130 }, map[string]*remoteexec.REParams{
131 "$d8Template": &remoteexec.REParams{
132 Labels: map[string]string{"type": "compile", "compiler": "d8"},
133 Inputs: []string{"${config.D8Jar}"},
134 ExecStrategy: "${config.RED8ExecStrategy}",
135 ToolchainInputs: []string{"${config.JavaCmd}"},
136 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
137 },
138 "$zipTemplate": &remoteexec.REParams{
139 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
140 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
141 OutputFiles: []string{"$outDir/classes.dex.jar"},
142 ExecStrategy: "${config.RED8ExecStrategy}",
143 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
144 },
Ian Zernydb2d35b2023-10-10 12:22:39 +0200145 }, []string{"outDir", "d8Flags", "zipFlags", "mergeZipsFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800146
Colin Cross77cdcfd2021-03-12 11:28:25 -0800147var r8, r8RE = pctx.MultiCommandRemoteStaticRules("r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800148 blueprint.RuleParams{
149 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100150 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700151 `mkdir -p $$(dirname ${outUsage}) && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000152 `$r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200153 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700154 `-printmapping ${outDict} ` +
Jared Duke34c6d7d2023-05-05 20:40:20 +0000155 `-printconfiguration ${outConfig} ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700156 `-printusage ${outUsage} ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000157 `--deps-file ${out}.d && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100158 `touch "${outDict}" "${outConfig}" "${outUsage}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700159 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
160 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700161 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700162 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Colin Crossb716ceb2023-10-03 09:40:06 -0700163 `rm -f "$outDir/classes*.dex" "$outDir/classes.dex.jar"`,
Colin Cross22e6a6f2022-03-21 12:19:44 -0700164 Depfile: "${out}.d",
165 Deps: blueprint.DepsGCC,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800166 CommandDeps: []string{
Colin Crossa832a042021-08-05 16:56:18 -0700167 "${config.R8Cmd}",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800168 "${config.SoongZipCmd}",
169 "${config.MergeZipsCmd}",
170 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700171 }, map[string]*remoteexec.REParams{
172 "$r8Template": &remoteexec.REParams{
173 Labels: map[string]string{"type": "compile", "compiler": "r8"},
174 Inputs: []string{"$implicits", "${config.R8Jar}"},
Rico Wind98e7fa82023-11-27 09:44:03 +0100175 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700176 ExecStrategy: "${config.RER8ExecStrategy}",
177 ToolchainInputs: []string{"${config.JavaCmd}"},
178 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
179 },
180 "$zipTemplate": &remoteexec.REParams{
181 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
182 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
183 OutputFiles: []string{"$outDir/classes.dex.jar"},
184 ExecStrategy: "${config.RER8ExecStrategy}",
185 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
186 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700187 "$zipUsageTemplate": &remoteexec.REParams{
188 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
189 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
190 OutputFiles: []string{"${outUsageZip}"},
191 ExecStrategy: "${config.RER8ExecStrategy}",
192 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
193 },
Ian Zerny82044f12023-01-25 12:11:27 +0100194 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
Rico Wind98e7fa82023-11-27 09:44:03 +0100195 "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800196
Colin Cross5ea963e2021-09-16 19:13:43 -0700197func (d *dexer) dexCommonFlags(ctx android.ModuleContext,
Spandan Dasc404cc72023-02-23 18:05:05 +0000198 dexParams *compileDexParams) (flags []string, deps android.Paths) {
Colin Cross5ea963e2021-09-16 19:13:43 -0700199
200 flags = d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000201 // Translate all the DX flags to D8 ones until all the build files have been migrated
202 // to D8 flags. See: b/69377755
203 flags = android.RemoveListFromList(flags,
204 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800205
Colin Cross5ea963e2021-09-16 19:13:43 -0700206 for _, f := range android.PathsForModuleSrc(ctx, d.dexProperties.Main_dex_rules) {
207 flags = append(flags, "--main-dex-rules", f.String())
208 deps = append(deps, f)
209 }
210
Colin Crossf0056cb2017-12-22 15:56:08 -0800211 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000212 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800213 }
214
215 if ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
216 flags = append(flags,
217 "--debug",
218 "--verbose")
Colin Crossf0056cb2017-12-22 15:56:08 -0800219 }
220
Jared Duke40d731a2022-09-20 15:32:14 -0700221 // Supplying the platform build flag disables various features like API modeling and desugaring.
222 // For targets with a stable min SDK version (i.e., when the min SDK is both explicitly specified
223 // and managed+versioned), we suppress this flag to ensure portability.
224 // Note: Targets with a min SDK kind of core_platform (e.g., framework.jar) or unspecified (e.g.,
225 // services.jar), are not classified as stable, which is WAI.
226 // TODO(b/232073181): Expand to additional min SDK cases after validation.
Ian Zernyc26029b2023-08-25 13:43:44 +0200227 var addAndroidPlatformBuildFlag = false
Spandan Dasc404cc72023-02-23 18:05:05 +0000228 if !dexParams.sdkVersion.Stable() {
Ian Zernyc26029b2023-08-25 13:43:44 +0200229 addAndroidPlatformBuildFlag = true
Jared Duke40d731a2022-09-20 15:32:14 -0700230 }
231
Spandan Dasc404cc72023-02-23 18:05:05 +0000232 effectiveVersion, err := dexParams.minSdkVersion.EffectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700233 if err != nil {
234 ctx.PropertyErrorf("min_sdk_version", "%s", err)
235 }
236
Ian Zernyc26029b2023-08-25 13:43:44 +0200237 // If the specified SDK level is 10000, then configure the compiler to use the
238 // current platform SDK level and to compile the build as a platform build.
239 var minApiFlagValue = effectiveVersion.FinalOrFutureInt()
240 if minApiFlagValue == 10000 {
241 minApiFlagValue = ctx.Config().PlatformSdkVersion().FinalInt()
242 addAndroidPlatformBuildFlag = true
243 }
244 flags = append(flags, "--min-api "+strconv.Itoa(minApiFlagValue))
245
246 if addAndroidPlatformBuildFlag {
247 flags = append(flags, "--android-platform-build")
248 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700249 return flags, deps
Colin Crossf0056cb2017-12-22 15:56:08 -0800250}
251
Liz Kammera7a64f32020-07-09 15:16:41 -0700252func d8Flags(flags javaBuilderFlags) (d8Flags []string, d8Deps android.Paths) {
Colin Crossc2557d12019-10-31 15:22:57 -0700253 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700254 d8Flags = append(d8Flags, flags.dexClasspath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700255
Colin Cross6dab9bd2018-09-28 08:06:24 -0700256 d8Deps = append(d8Deps, flags.bootClasspath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700257 d8Deps = append(d8Deps, flags.dexClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700258
259 return d8Flags, d8Deps
Colin Crossffb657e2018-09-21 12:29:22 -0700260}
261
Liz Kammera7a64f32020-07-09 15:16:41 -0700262func (d *dexer) r8Flags(ctx android.ModuleContext, flags javaBuilderFlags) (r8Flags []string, r8Deps android.Paths) {
263 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800264
265 // When an app contains references to APIs that are not in the SDK specified by
266 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000267 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800268 // ProGuard, to
269 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
270 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
271 // See b/20667396
272 var proguardRaiseDeps classpath
Colin Crossdcf71b22021-02-01 13:59:03 -0800273 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -0800274 dep, _ := android.OtherModuleProvider(ctx, m, JavaInfoProvider)
Joe Onorato349ae8d2024-02-05 22:46:00 +0000275 proguardRaiseDeps = append(proguardRaiseDeps, dep.RepackagedHeaderJars...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800276 })
277
278 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700279 r8Deps = append(r8Deps, proguardRaiseDeps...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500280 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700281 r8Deps = append(r8Deps, flags.bootClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500282 r8Flags = append(r8Flags, flags.dexClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700283 r8Deps = append(r8Deps, flags.dexClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500284
285 transitiveStaticLibsLookupMap := map[android.Path]bool{}
286 if d.transitiveStaticLibsHeaderJars != nil {
287 for _, jar := range d.transitiveStaticLibsHeaderJars.ToList() {
288 transitiveStaticLibsLookupMap[jar] = true
289 }
290 }
291 transitiveHeaderJars := android.Paths{}
292 if d.transitiveLibsHeaderJars != nil {
293 for _, jar := range d.transitiveLibsHeaderJars.ToList() {
294 if _, ok := transitiveStaticLibsLookupMap[jar]; ok {
295 // don't include a lib if it is already packaged in the current JAR as a static lib
296 continue
297 }
298 transitiveHeaderJars = append(transitiveHeaderJars, jar)
299 }
300 }
301 transitiveClasspath := classpath(transitiveHeaderJars)
302 r8Flags = append(r8Flags, transitiveClasspath.FormJavaClassPath("-libraryjars"))
303 r8Deps = append(r8Deps, transitiveClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700304
Colin Cross66dbc0b2017-12-28 12:23:20 -0800305 flagFiles := android.Paths{
306 android.PathForSource(ctx, "build/make/core/proguard.flags"),
307 }
308
Colin Cross312634e2023-11-21 15:13:56 -0800309 flagFiles = append(flagFiles, d.extraProguardFlagsFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800310 // TODO(ccross): static android library proguard files
311
Liz Kammera7a64f32020-07-09 15:16:41 -0700312 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700313
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000314 flagFiles = android.FirstUniquePaths(flagFiles)
315
Colin Cross66dbc0b2017-12-28 12:23:20 -0800316 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
317 r8Deps = append(r8Deps, flagFiles...)
318
319 // TODO(b/70942988): This is included from build/make/core/proguard.flags
320 r8Deps = append(r8Deps, android.PathForSource(ctx,
321 "build/make/core/proguard_basic_keeps.flags"))
322
Liz Kammera7a64f32020-07-09 15:16:41 -0700323 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800324
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200325 if BoolDefault(opt.Proguard_compatibility, true) {
326 r8Flags = append(r8Flags, "--force-proguard-compatibility")
Jared Dukeb832fbb2023-09-15 17:16:36 +0000327 }
328
329 if Bool(opt.Optimize) || Bool(opt.Obfuscate) {
Ian Zernyfc7df612021-11-02 15:37:06 +0100330 // TODO(b/213833843): Allow configuration of the prefix via a build variable.
331 var sourceFilePrefix = "go/retraceme "
332 var sourceFileTemplate = "\"" + sourceFilePrefix + "%MAP_ID\""
Jared Dukeb832fbb2023-09-15 17:16:36 +0000333 r8Flags = append(r8Flags, "--map-id-template", "%MAP_HASH")
334 r8Flags = append(r8Flags, "--source-file-template", sourceFileTemplate)
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200335 }
336
Colin Cross66dbc0b2017-12-28 12:23:20 -0800337 // TODO(ccross): Don't shrink app instrumentation tests by default.
338 if !Bool(opt.Shrink) {
339 r8Flags = append(r8Flags, "-dontshrink")
340 }
341
342 if !Bool(opt.Optimize) {
343 r8Flags = append(r8Flags, "-dontoptimize")
344 }
345
346 // TODO(ccross): error if obufscation + app instrumentation test.
347 if !Bool(opt.Obfuscate) {
348 r8Flags = append(r8Flags, "-dontobfuscate")
349 }
Colin Cross4b964c02018-10-15 16:18:06 -0700350 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
351 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800352
Jaewoong Jung1d6eb682018-11-29 15:08:44 -0800353 // Don't strip out debug information for eng builds.
354 if ctx.Config().Eng() {
355 r8Flags = append(r8Flags, "--debug")
356 }
357
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100358 // TODO(b/180878971): missing classes should be added to the relevant builds.
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +0000359 // TODO(b/229727645): do not use true as default for Android platform builds.
360 if proptools.BoolDefault(opt.Ignore_warnings, true) {
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +0900361 r8Flags = append(r8Flags, "-ignorewarnings")
362 }
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100363
Rico Winda2fa2632024-03-13 13:09:17 +0100364 // resourcesInput is empty when we don't use resource shrinking, if on, pass these to R8
Rico Wind98e7fa82023-11-27 09:44:03 +0100365 if d.resourcesInput.Valid() {
366 r8Flags = append(r8Flags, "--resource-input", d.resourcesInput.Path().String())
367 r8Deps = append(r8Deps, d.resourcesInput.Path())
368 r8Flags = append(r8Flags, "--resource-output", d.resourcesOutput.Path().String())
Rico Winda2fa2632024-03-13 13:09:17 +0100369 if Bool(opt.Optimized_shrink_resources) {
370 r8Flags = append(r8Flags, "--optimized-resource-shrinking")
371 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100372 }
373
Colin Cross66dbc0b2017-12-28 12:23:20 -0800374 return r8Flags, r8Deps
375}
376
Spandan Dasc404cc72023-02-23 18:05:05 +0000377type compileDexParams struct {
378 flags javaBuilderFlags
379 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000380 minSdkVersion android.ApiLevel
Spandan Dasc404cc72023-02-23 18:05:05 +0000381 classesJar android.Path
382 jarName string
383}
384
385func (d *dexer) compileDex(ctx android.ModuleContext, dexParams *compileDexParams) android.OutputPath {
Colin Crossf0056cb2017-12-22 15:56:08 -0800386
Colin Crossf0056cb2017-12-22 15:56:08 -0800387 // Compile classes.jar into classes.dex and then javalib.jar
Spandan Dasc404cc72023-02-23 18:05:05 +0000388 javalibJar := android.PathForModuleOut(ctx, "dex", dexParams.jarName).OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800389 outDir := android.PathForModuleOut(ctx, "dex")
390
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800391 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700392 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800393 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700394 }
395
Spandan Dasc404cc72023-02-23 18:05:05 +0000396 commonFlags, commonDeps := d.dexCommonFlags(ctx, dexParams)
Liz Kammera7a64f32020-07-09 15:16:41 -0700397
Wei Li1e73c652021-12-06 13:35:11 -0800398 // Exclude kotlinc generated files when "exclude_kotlinc_generated_files" is set to true.
399 mergeZipsFlags := ""
400 if proptools.BoolDefault(d.dexProperties.Exclude_kotlinc_generated_files, false) {
401 mergeZipsFlags = "-stripFile META-INF/*.kotlin_module -stripFile **/*.kotlin_builtins"
402 }
403
Liz Kammera7a64f32020-07-09 15:16:41 -0700404 useR8 := d.effectiveOptimizeEnabled()
Colin Cross66dbc0b2017-12-28 12:23:20 -0800405 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700406 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700407 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Ian Zerny82044f12023-01-25 12:11:27 +0100408 proguardConfiguration := android.PathForModuleOut(ctx, "proguard_configuration")
409 d.proguardConfiguration = android.OptionalPathForPath(proguardConfiguration)
Colin Crosscb6143a2020-08-14 17:39:29 -0700410 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
411 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
412 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
413 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
414 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Rico Wind98e7fa82023-11-27 09:44:03 +0100415 resourcesOutput := android.PathForModuleOut(ctx, "package-res-shrunken.apk")
416 d.resourcesOutput = android.OptionalPathForPath(resourcesOutput)
Spandan Dasc404cc72023-02-23 18:05:05 +0000417 r8Flags, r8Deps := d.r8Flags(ctx, dexParams.flags)
Colin Cross5ea963e2021-09-16 19:13:43 -0700418 r8Deps = append(r8Deps, commonDeps...)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400419 rule := r8
420 args := map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800421 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
422 "zipFlags": zipFlags,
423 "outDict": proguardDictionary.String(),
Ian Zerny82044f12023-01-25 12:11:27 +0100424 "outConfig": proguardConfiguration.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800425 "outUsageDir": proguardUsageDir.String(),
426 "outUsage": proguardUsage.String(),
427 "outUsageZip": proguardUsageZip.String(),
428 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800429 "mergeZipsFlags": mergeZipsFlags,
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400430 }
Ramy Medhat16f23a42020-09-03 01:29:49 -0400431 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400432 rule = r8RE
433 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
434 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100435 implicitOutputs := android.WritablePaths{
436 proguardDictionary,
437 proguardUsageZip,
438 proguardConfiguration}
439 if d.resourcesInput.Valid() {
440 implicitOutputs = append(implicitOutputs, resourcesOutput)
441 args["resourcesOutput"] = resourcesOutput.String()
442 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800443 ctx.Build(pctx, android.BuildParams{
Rico Wind98e7fa82023-11-27 09:44:03 +0100444 Rule: rule,
445 Description: "r8",
446 Output: javalibJar,
447 ImplicitOutputs: implicitOutputs,
448 Input: dexParams.classesJar,
449 Implicits: r8Deps,
450 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800451 })
452 } else {
Spandan Dasc404cc72023-02-23 18:05:05 +0000453 d8Flags, d8Deps := d8Flags(dexParams.flags)
Colin Cross5ea963e2021-09-16 19:13:43 -0700454 d8Deps = append(d8Deps, commonDeps...)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400455 rule := d8
Ramy Medhat16f23a42020-09-03 01:29:49 -0400456 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400457 rule = d8RE
458 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800459 ctx.Build(pctx, android.BuildParams{
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400460 Rule: rule,
Colin Crossbafb8972018-06-06 21:46:32 +0000461 Description: "d8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800462 Output: javalibJar,
Spandan Dasc404cc72023-02-23 18:05:05 +0000463 Input: dexParams.classesJar,
Colin Cross6dab9bd2018-09-28 08:06:24 -0700464 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800465 Args: map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800466 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
467 "zipFlags": zipFlags,
468 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800469 "mergeZipsFlags": mergeZipsFlags,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800470 },
471 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800472 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700473 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Spandan Dasc404cc72023-02-23 18:05:05 +0000474 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", dexParams.jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +0000475 TransformZipAlign(ctx, alignedJavalibJar, javalibJar, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000476 javalibJar = alignedJavalibJar
477 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800478
Colin Crossf0056cb2017-12-22 15:56:08 -0800479 return javalibJar
480}