blob: 983377ead7fae26550838c67c2d8ba6972da198d [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
Ulya Trafimovichc8160582024-07-10 08:32:45 +010094
95 // Disable dex container (also known as "multi-dex").
96 // This may be necessary as a temporary workaround to mask toolchain bugs (see b/341652226).
97 No_dex_container *bool
Liz Kammera7a64f32020-07-09 15:16:41 -070098}
99
100type dexer struct {
101 dexProperties DexProperties
102
103 // list of extra proguard flag files
Colin Cross312634e2023-11-21 15:13:56 -0800104 extraProguardFlagsFiles android.Paths
105 proguardDictionary android.OptionalPath
106 proguardConfiguration android.OptionalPath
107 proguardUsageZip android.OptionalPath
108 resourcesInput android.OptionalPath
109 resourcesOutput android.OptionalPath
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500110
Colin Cross9ffaf282024-08-12 13:50:09 -0700111 providesTransitiveHeaderJarsForR8
Liz Kammera7a64f32020-07-09 15:16:41 -0700112}
113
114func (d *dexer) effectiveOptimizeEnabled() bool {
115 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
116}
117
Rico Wind936754c2024-05-07 09:08:31 +0200118func (d *DexProperties) resourceShrinkingEnabled(ctx android.ModuleContext) bool {
119 return !ctx.Config().Eng() && BoolDefault(d.Optimize.Optimized_shrink_resources, Bool(d.Optimize.Shrink_resources))
120}
121
122func (d *DexProperties) optimizedResourceShrinkingEnabled(ctx android.ModuleContext) bool {
Rico Winda7b38592024-08-26 12:10:44 +0200123 return d.resourceShrinkingEnabled(ctx) && BoolDefault(d.Optimize.Optimized_shrink_resources, ctx.Config().UseOptimizedResourceShrinkingByDefault())
Rico Winda2fa2632024-03-13 13:09:17 +0100124}
125
Spandan Das15a67112024-05-30 00:07:40 +0000126func (d *dexer) optimizeOrObfuscateEnabled() bool {
127 return d.effectiveOptimizeEnabled() && (proptools.Bool(d.dexProperties.Optimize.Optimize) || proptools.Bool(d.dexProperties.Optimize.Obfuscate))
128}
129
Colin Cross77cdcfd2021-03-12 11:28:25 -0800130var d8, d8RE = pctx.MultiCommandRemoteStaticRules("d8",
Colin Crossf0056cb2017-12-22 15:56:08 -0800131 blueprint.RuleParams{
132 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000133 `$d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700134 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700135 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700136 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Crossf0056cb2017-12-22 15:56:08 -0800137 CommandDeps: []string{
138 "${config.D8Cmd}",
139 "${config.SoongZipCmd}",
140 "${config.MergeZipsCmd}",
141 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700142 }, map[string]*remoteexec.REParams{
143 "$d8Template": &remoteexec.REParams{
144 Labels: map[string]string{"type": "compile", "compiler": "d8"},
145 Inputs: []string{"${config.D8Jar}"},
146 ExecStrategy: "${config.RED8ExecStrategy}",
147 ToolchainInputs: []string{"${config.JavaCmd}"},
148 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
149 },
150 "$zipTemplate": &remoteexec.REParams{
151 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
152 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
153 OutputFiles: []string{"$outDir/classes.dex.jar"},
154 ExecStrategy: "${config.RED8ExecStrategy}",
155 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
156 },
Ian Zernydb2d35b2023-10-10 12:22:39 +0200157 }, []string{"outDir", "d8Flags", "zipFlags", "mergeZipsFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800158
Colin Cross77cdcfd2021-03-12 11:28:25 -0800159var r8, r8RE = pctx.MultiCommandRemoteStaticRules("r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800160 blueprint.RuleParams{
161 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100162 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700163 `mkdir -p $$(dirname ${outUsage}) && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000164 `$r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200165 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700166 `-printmapping ${outDict} ` +
Jared Duke34c6d7d2023-05-05 20:40:20 +0000167 `-printconfiguration ${outConfig} ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700168 `-printusage ${outUsage} ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000169 `--deps-file ${out}.d && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100170 `touch "${outDict}" "${outConfig}" "${outUsage}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700171 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
172 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700173 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700174 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700175 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Cross22e6a6f2022-03-21 12:19:44 -0700176 Depfile: "${out}.d",
177 Deps: blueprint.DepsGCC,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800178 CommandDeps: []string{
Colin Crossa832a042021-08-05 16:56:18 -0700179 "${config.R8Cmd}",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800180 "${config.SoongZipCmd}",
181 "${config.MergeZipsCmd}",
182 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700183 }, map[string]*remoteexec.REParams{
184 "$r8Template": &remoteexec.REParams{
185 Labels: map[string]string{"type": "compile", "compiler": "r8"},
186 Inputs: []string{"$implicits", "${config.R8Jar}"},
Spandan Dasd447bbb2024-06-24 17:13:30 +0000187 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700188 ExecStrategy: "${config.RER8ExecStrategy}",
189 ToolchainInputs: []string{"${config.JavaCmd}"},
190 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
191 },
192 "$zipTemplate": &remoteexec.REParams{
193 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
194 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
195 OutputFiles: []string{"$outDir/classes.dex.jar"},
196 ExecStrategy: "${config.RER8ExecStrategy}",
197 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
198 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700199 "$zipUsageTemplate": &remoteexec.REParams{
200 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
201 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
202 OutputFiles: []string{"${outUsageZip}"},
203 ExecStrategy: "${config.RER8ExecStrategy}",
204 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
205 },
Ian Zerny82044f12023-01-25 12:11:27 +0100206 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
Spandan Dasd447bbb2024-06-24 17:13:30 +0000207 "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800208
Colin Cross5ea963e2021-09-16 19:13:43 -0700209func (d *dexer) dexCommonFlags(ctx android.ModuleContext,
Spandan Dasc404cc72023-02-23 18:05:05 +0000210 dexParams *compileDexParams) (flags []string, deps android.Paths) {
Colin Cross5ea963e2021-09-16 19:13:43 -0700211
212 flags = d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000213 // Translate all the DX flags to D8 ones until all the build files have been migrated
214 // to D8 flags. See: b/69377755
215 flags = android.RemoveListFromList(flags,
216 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800217
Colin Cross5ea963e2021-09-16 19:13:43 -0700218 for _, f := range android.PathsForModuleSrc(ctx, d.dexProperties.Main_dex_rules) {
219 flags = append(flags, "--main-dex-rules", f.String())
220 deps = append(deps, f)
221 }
222
Jared Duked32e85f2024-09-25 23:54:30 +0000223 var requestReleaseMode bool
224 requestReleaseMode, flags = android.RemoveFromList("--release", flags)
225
Abdelrahman Daim1cde8fc2024-10-01 06:55:58 -0700226 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" || ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000227 flags = append(flags, "--debug")
Jared Duked32e85f2024-09-25 23:54:30 +0000228 requestReleaseMode = false
Colin Crossf0056cb2017-12-22 15:56:08 -0800229 }
230
Jared Duked32e85f2024-09-25 23:54:30 +0000231 // Don't strip out debug information for eng builds, unless the target
232 // explicitly provided the `--release` build flag. This allows certain
233 // test targets to remain optimized as part of eng test_suites builds.
234 if requestReleaseMode {
235 flags = append(flags, "--release")
236 } else if ctx.Config().Eng() {
237 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800238 }
239
Jared Duke40d731a2022-09-20 15:32:14 -0700240 // Supplying the platform build flag disables various features like API modeling and desugaring.
241 // For targets with a stable min SDK version (i.e., when the min SDK is both explicitly specified
242 // and managed+versioned), we suppress this flag to ensure portability.
243 // Note: Targets with a min SDK kind of core_platform (e.g., framework.jar) or unspecified (e.g.,
244 // services.jar), are not classified as stable, which is WAI.
245 // TODO(b/232073181): Expand to additional min SDK cases after validation.
Ian Zernyc26029b2023-08-25 13:43:44 +0200246 var addAndroidPlatformBuildFlag = false
Spandan Dasc404cc72023-02-23 18:05:05 +0000247 if !dexParams.sdkVersion.Stable() {
Ian Zernyc26029b2023-08-25 13:43:44 +0200248 addAndroidPlatformBuildFlag = true
Jared Duke40d731a2022-09-20 15:32:14 -0700249 }
250
Spandan Dasc404cc72023-02-23 18:05:05 +0000251 effectiveVersion, err := dexParams.minSdkVersion.EffectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700252 if err != nil {
253 ctx.PropertyErrorf("min_sdk_version", "%s", err)
254 }
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000255 if !Bool(d.dexProperties.No_dex_container) && effectiveVersion.FinalOrFutureInt() >= 36 {
256 // W is 36, but we have not bumped the SDK version yet, so check for both.
257 if ctx.Config().PlatformSdkVersion().FinalInt() >= 36 ||
258 ctx.Config().PlatformSdkCodename() == "Wear" {
259 // TODO(b/329465418): Skip this module since it causes issue with app DRM
260 if ctx.ModuleName() != "framework-minus-apex" {
261 flags = append([]string{"-JDcom.android.tools.r8.dexContainerExperiment"}, flags...)
262 }
263 }
264 }
Colin Cross83bb3162018-06-25 15:48:06 -0700265
Ian Zernyc26029b2023-08-25 13:43:44 +0200266 // If the specified SDK level is 10000, then configure the compiler to use the
267 // current platform SDK level and to compile the build as a platform build.
268 var minApiFlagValue = effectiveVersion.FinalOrFutureInt()
269 if minApiFlagValue == 10000 {
270 minApiFlagValue = ctx.Config().PlatformSdkVersion().FinalInt()
271 addAndroidPlatformBuildFlag = true
272 }
273 flags = append(flags, "--min-api "+strconv.Itoa(minApiFlagValue))
274
275 if addAndroidPlatformBuildFlag {
276 flags = append(flags, "--android-platform-build")
277 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700278 return flags, deps
Colin Crossf0056cb2017-12-22 15:56:08 -0800279}
280
Spandan Das3dbda182024-05-20 22:23:10 +0000281func (d *dexer) d8Flags(ctx android.ModuleContext, dexParams *compileDexParams) (d8Flags []string, d8Deps android.Paths, artProfileOutput *android.OutputPath) {
282 flags := dexParams.flags
Colin Crossc2557d12019-10-31 15:22:57 -0700283 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700284 d8Flags = append(d8Flags, flags.dexClasspath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700285
Colin Cross6dab9bd2018-09-28 08:06:24 -0700286 d8Deps = append(d8Deps, flags.bootClasspath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700287 d8Deps = append(d8Deps, flags.dexClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700288
Spandan Das3dbda182024-05-20 22:23:10 +0000289 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
290 d8Flags = append(d8Flags, flags...)
291 d8Deps = append(d8Deps, deps...)
292 artProfileOutput = profileOutput
293 }
294
295 return d8Flags, d8Deps, artProfileOutput
Colin Crossffb657e2018-09-21 12:29:22 -0700296}
297
Jared Duke91d0bee2024-11-14 23:10:09 +0000298func (d *dexer) r8Flags(ctx android.ModuleContext, dexParams *compileDexParams, debugMode bool) (r8Flags []string, r8Deps android.Paths, artProfileOutput *android.OutputPath) {
Spandan Das3dbda182024-05-20 22:23:10 +0000299 flags := dexParams.flags
Liz Kammera7a64f32020-07-09 15:16:41 -0700300 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800301
302 // When an app contains references to APIs that are not in the SDK specified by
303 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000304 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800305 // ProGuard, to
306 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
307 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
308 // See b/20667396
Jared Duke22468442024-08-20 20:45:35 +0000309 // TODO(b/360905238): Remove SdkSystemServer exception after resolving missing class references.
310 if !dexParams.sdkVersion.Stable() || dexParams.sdkVersion.Kind == android.SdkSystemServer {
311 var proguardRaiseDeps classpath
312 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(m android.Module) {
313 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
314 proguardRaiseDeps = append(proguardRaiseDeps, dep.RepackagedHeaderJars...)
315 }
316 })
317 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
318 r8Deps = append(r8Deps, proguardRaiseDeps...)
319 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800320
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500321 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700322 r8Deps = append(r8Deps, flags.bootClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500323 r8Flags = append(r8Flags, flags.dexClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700324 r8Deps = append(r8Deps, flags.dexClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500325
326 transitiveStaticLibsLookupMap := map[android.Path]bool{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700327 for _, jar := range d.transitiveStaticLibsHeaderJarsForR8.ToList() {
328 transitiveStaticLibsLookupMap[jar] = true
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500329 }
330 transitiveHeaderJars := android.Paths{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700331 for _, jar := range d.transitiveLibsHeaderJarsForR8.ToList() {
332 if _, ok := transitiveStaticLibsLookupMap[jar]; ok {
333 // don't include a lib if it is already packaged in the current JAR as a static lib
334 continue
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500335 }
Colin Crossa14fb6a2024-10-23 16:57:06 -0700336 transitiveHeaderJars = append(transitiveHeaderJars, jar)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500337 }
338 transitiveClasspath := classpath(transitiveHeaderJars)
339 r8Flags = append(r8Flags, transitiveClasspath.FormJavaClassPath("-libraryjars"))
340 r8Deps = append(r8Deps, transitiveClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700341
Colin Cross66dbc0b2017-12-28 12:23:20 -0800342 flagFiles := android.Paths{
343 android.PathForSource(ctx, "build/make/core/proguard.flags"),
344 }
345
Colin Cross312634e2023-11-21 15:13:56 -0800346 flagFiles = append(flagFiles, d.extraProguardFlagsFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800347 // TODO(ccross): static android library proguard files
348
Liz Kammera7a64f32020-07-09 15:16:41 -0700349 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700350
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000351 flagFiles = android.FirstUniquePaths(flagFiles)
352
Colin Cross66dbc0b2017-12-28 12:23:20 -0800353 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
354 r8Deps = append(r8Deps, flagFiles...)
355
356 // TODO(b/70942988): This is included from build/make/core/proguard.flags
357 r8Deps = append(r8Deps, android.PathForSource(ctx,
358 "build/make/core/proguard_basic_keeps.flags"))
359
Liz Kammera7a64f32020-07-09 15:16:41 -0700360 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800361
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200362 if BoolDefault(opt.Proguard_compatibility, true) {
363 r8Flags = append(r8Flags, "--force-proguard-compatibility")
Jared Dukeb832fbb2023-09-15 17:16:36 +0000364 }
365
Jared Duke91d0bee2024-11-14 23:10:09 +0000366 // Avoid unnecessary stack frame noise by only injecting source map ids for non-debug
367 // optimized or obfuscated targets.
368 if (Bool(opt.Optimize) || Bool(opt.Obfuscate)) && !debugMode {
Ian Zernyfc7df612021-11-02 15:37:06 +0100369 // TODO(b/213833843): Allow configuration of the prefix via a build variable.
370 var sourceFilePrefix = "go/retraceme "
371 var sourceFileTemplate = "\"" + sourceFilePrefix + "%MAP_ID\""
Jared Dukeb832fbb2023-09-15 17:16:36 +0000372 r8Flags = append(r8Flags, "--map-id-template", "%MAP_HASH")
373 r8Flags = append(r8Flags, "--source-file-template", sourceFileTemplate)
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200374 }
375
Colin Cross66dbc0b2017-12-28 12:23:20 -0800376 // TODO(ccross): Don't shrink app instrumentation tests by default.
377 if !Bool(opt.Shrink) {
378 r8Flags = append(r8Flags, "-dontshrink")
379 }
380
381 if !Bool(opt.Optimize) {
382 r8Flags = append(r8Flags, "-dontoptimize")
383 }
384
385 // TODO(ccross): error if obufscation + app instrumentation test.
386 if !Bool(opt.Obfuscate) {
387 r8Flags = append(r8Flags, "-dontobfuscate")
388 }
Colin Cross4b964c02018-10-15 16:18:06 -0700389 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
390 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800391
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100392 // TODO(b/180878971): missing classes should be added to the relevant builds.
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +0000393 // TODO(b/229727645): do not use true as default for Android platform builds.
394 if proptools.BoolDefault(opt.Ignore_warnings, true) {
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +0900395 r8Flags = append(r8Flags, "-ignorewarnings")
396 }
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100397
Rico Winda2fa2632024-03-13 13:09:17 +0100398 // resourcesInput is empty when we don't use resource shrinking, if on, pass these to R8
Rico Wind98e7fa82023-11-27 09:44:03 +0100399 if d.resourcesInput.Valid() {
400 r8Flags = append(r8Flags, "--resource-input", d.resourcesInput.Path().String())
401 r8Deps = append(r8Deps, d.resourcesInput.Path())
402 r8Flags = append(r8Flags, "--resource-output", d.resourcesOutput.Path().String())
Rico Winda7b38592024-08-26 12:10:44 +0200403 if d.dexProperties.optimizedResourceShrinkingEnabled(ctx) {
Rico Winda2fa2632024-03-13 13:09:17 +0100404 r8Flags = append(r8Flags, "--optimized-resource-shrinking")
Rico Wind619ed5c2024-10-22 14:00:23 +0200405 if Bool(d.dexProperties.Optimize.Optimized_shrink_resources) {
406 // Explicitly opted into optimized shrinking, no need for keeping R$id entries
407 r8Flags = append(r8Flags, "--force-optimized-resource-shrinking")
408 }
Rico Winda2fa2632024-03-13 13:09:17 +0100409 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100410 }
411
Spandan Das3dbda182024-05-20 22:23:10 +0000412 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
413 r8Flags = append(r8Flags, flags...)
414 r8Deps = append(r8Deps, deps...)
415 artProfileOutput = profileOutput
416 }
417
418 return r8Flags, r8Deps, artProfileOutput
Colin Cross66dbc0b2017-12-28 12:23:20 -0800419}
420
Spandan Dasc404cc72023-02-23 18:05:05 +0000421type compileDexParams struct {
Spandan Das3dbda182024-05-20 22:23:10 +0000422 flags javaBuilderFlags
423 sdkVersion android.SdkSpec
424 minSdkVersion android.ApiLevel
425 classesJar android.Path
426 jarName string
427 artProfileInput *string
Spandan Dasc404cc72023-02-23 18:05:05 +0000428}
429
Spandan Das3dbda182024-05-20 22:23:10 +0000430// Adds --art-profile to r8/d8 command.
431// r8/d8 will output a generated profile file to match the optimized dex code.
432func (d *dexer) addArtProfile(ctx android.ModuleContext, dexParams *compileDexParams) (flags []string, deps android.Paths, artProfileOutputPath *android.OutputPath) {
Cole Faust4e9f5922024-11-13 16:09:23 -0800433 if dexParams.artProfileInput == nil {
434 return nil, nil, nil
Spandan Das3dbda182024-05-20 22:23:10 +0000435 }
Cole Faust4e9f5922024-11-13 16:09:23 -0800436 artProfileInputPath := android.PathForModuleSrc(ctx, *dexParams.artProfileInput)
437 artProfileOutputPathValue := android.PathForModuleOut(ctx, "profile.prof.txt").OutputPath
438 artProfileOutputPath = &artProfileOutputPathValue
439 flags = []string{
440 "--art-profile",
441 artProfileInputPath.String(),
442 artProfileOutputPath.String(),
443 }
444 deps = append(deps, artProfileInputPath)
Spandan Das3dbda182024-05-20 22:23:10 +0000445 return flags, deps, artProfileOutputPath
446
447}
448
449// Return the compiled dex jar and (optional) profile _after_ r8 optimization
Colin Cross7707b242024-07-26 12:02:36 -0700450func (d *dexer) compileDex(ctx android.ModuleContext, dexParams *compileDexParams) (android.Path, android.Path) {
Colin Crossf0056cb2017-12-22 15:56:08 -0800451
Colin Crossf0056cb2017-12-22 15:56:08 -0800452 // Compile classes.jar into classes.dex and then javalib.jar
Spandan Dasc404cc72023-02-23 18:05:05 +0000453 javalibJar := android.PathForModuleOut(ctx, "dex", dexParams.jarName).OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800454 outDir := android.PathForModuleOut(ctx, "dex")
455
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800456 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700457 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800458 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700459 }
460
Spandan Dasc404cc72023-02-23 18:05:05 +0000461 commonFlags, commonDeps := d.dexCommonFlags(ctx, dexParams)
Liz Kammera7a64f32020-07-09 15:16:41 -0700462
Wei Li1e73c652021-12-06 13:35:11 -0800463 // Exclude kotlinc generated files when "exclude_kotlinc_generated_files" is set to true.
464 mergeZipsFlags := ""
465 if proptools.BoolDefault(d.dexProperties.Exclude_kotlinc_generated_files, false) {
466 mergeZipsFlags = "-stripFile META-INF/*.kotlin_module -stripFile **/*.kotlin_builtins"
467 }
468
Liz Kammera7a64f32020-07-09 15:16:41 -0700469 useR8 := d.effectiveOptimizeEnabled()
Spandan Das3dbda182024-05-20 22:23:10 +0000470 var artProfileOutputPath *android.OutputPath
Colin Cross66dbc0b2017-12-28 12:23:20 -0800471 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700472 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700473 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Ian Zerny82044f12023-01-25 12:11:27 +0100474 proguardConfiguration := android.PathForModuleOut(ctx, "proguard_configuration")
475 d.proguardConfiguration = android.OptionalPathForPath(proguardConfiguration)
Colin Crosscb6143a2020-08-14 17:39:29 -0700476 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
477 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
478 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
479 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
480 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Rico Wind98e7fa82023-11-27 09:44:03 +0100481 resourcesOutput := android.PathForModuleOut(ctx, "package-res-shrunken.apk")
482 d.resourcesOutput = android.OptionalPathForPath(resourcesOutput)
Spandan Das3dbda182024-05-20 22:23:10 +0000483 implicitOutputs := android.WritablePaths{
484 proguardDictionary,
485 proguardUsageZip,
486 proguardConfiguration,
487 }
Jared Duke91d0bee2024-11-14 23:10:09 +0000488 debugMode := android.InList("--debug", commonFlags)
489 r8Flags, r8Deps, r8ArtProfileOutputPath := d.r8Flags(ctx, dexParams, debugMode)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400490 rule := r8
491 args := map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800492 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
493 "zipFlags": zipFlags,
494 "outDict": proguardDictionary.String(),
Ian Zerny82044f12023-01-25 12:11:27 +0100495 "outConfig": proguardConfiguration.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800496 "outUsageDir": proguardUsageDir.String(),
497 "outUsage": proguardUsage.String(),
498 "outUsageZip": proguardUsageZip.String(),
499 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800500 "mergeZipsFlags": mergeZipsFlags,
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400501 }
Spandan Dasd447bbb2024-06-24 17:13:30 +0000502 if r8ArtProfileOutputPath != nil {
503 artProfileOutputPath = r8ArtProfileOutputPath
504 implicitOutputs = append(
505 implicitOutputs,
506 artProfileOutputPath,
507 )
508 // Add the implicit r8 Art profile output to args so that r8RE knows
509 // about this implicit output
510 args["outR8ArtProfile"] = artProfileOutputPath.String()
511 }
512
Ramy Medhat16f23a42020-09-03 01:29:49 -0400513 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400514 rule = r8RE
515 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
516 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100517 if d.resourcesInput.Valid() {
518 implicitOutputs = append(implicitOutputs, resourcesOutput)
519 args["resourcesOutput"] = resourcesOutput.String()
520 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800521 ctx.Build(pctx, android.BuildParams{
Rico Wind98e7fa82023-11-27 09:44:03 +0100522 Rule: rule,
523 Description: "r8",
524 Output: javalibJar,
525 ImplicitOutputs: implicitOutputs,
526 Input: dexParams.classesJar,
527 Implicits: r8Deps,
528 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800529 })
530 } else {
Spandan Das3dbda182024-05-20 22:23:10 +0000531 implicitOutputs := android.WritablePaths{}
532 d8Flags, d8Deps, d8ArtProfileOutputPath := d.d8Flags(ctx, dexParams)
533 if d8ArtProfileOutputPath != nil {
534 artProfileOutputPath = d8ArtProfileOutputPath
535 implicitOutputs = append(
536 implicitOutputs,
537 artProfileOutputPath,
538 )
539 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700540 d8Deps = append(d8Deps, commonDeps...)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400541 rule := d8
Ramy Medhat16f23a42020-09-03 01:29:49 -0400542 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400543 rule = d8RE
544 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800545 ctx.Build(pctx, android.BuildParams{
Spandan Das3dbda182024-05-20 22:23:10 +0000546 Rule: rule,
547 Description: "d8",
548 Output: javalibJar,
549 Input: dexParams.classesJar,
550 ImplicitOutputs: implicitOutputs,
551 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800552 Args: map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800553 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
554 "zipFlags": zipFlags,
555 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800556 "mergeZipsFlags": mergeZipsFlags,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800557 },
558 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800559 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700560 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Spandan Dasc404cc72023-02-23 18:05:05 +0000561 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", dexParams.jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +0000562 TransformZipAlign(ctx, alignedJavalibJar, javalibJar, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000563 javalibJar = alignedJavalibJar
564 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800565
Spandan Das3dbda182024-05-20 22:23:10 +0000566 return javalibJar, artProfileOutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800567}