blob: 7b99549d4135aa72eab3dd092fe4587f4aafc511 [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
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +010045 // Whether to allow that library classes inherit from program classes.
46 // Defaults to false.
47 Ignore_library_extends_program *bool
48
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +000049 // Whether to continue building even if warnings are emitted. Defaults to true.
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +090050 Ignore_warnings *bool
51
Jared Dukeaa88b3d2023-08-29 17:07:20 +000052 // If true, runs R8 in Proguard compatibility mode, otherwise runs R8 in full mode.
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +010053 // Defaults to false for apps and tests, true for libraries.
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +020054 Proguard_compatibility *bool
55
Liz Kammera7a64f32020-07-09 15:16:41 -070056 // If true, optimize for size by removing unused code. Defaults to true for apps,
57 // false for libraries and tests.
58 Shrink *bool
59
60 // If true, optimize bytecode. Defaults to false.
61 Optimize *bool
62
63 // If true, obfuscate bytecode. Defaults to false.
64 Obfuscate *bool
65
66 // If true, do not use the flag files generated by aapt that automatically keep
67 // classes referenced by the app manifest. Defaults to false.
68 No_aapt_flags *bool
69
Jared Duke51b0a102022-09-27 16:53:11 -070070 // If true, optimize for size by removing unused resources. Defaults to false.
Rico Wind351bac92022-09-22 10:41:42 +020071 Shrink_resources *bool
72
Rico Winda2fa2632024-03-13 13:09:17 +010073 // If true, use optimized resource shrinking in R8, overriding the
74 // Shrink_resources setting. Defaults to false.
75 // Optimized shrinking means that R8 will trace and treeshake resources together with code
76 // and apply additional optimizations. This implies non final fields in the R classes.
77 Optimized_shrink_resources *bool
78
Liz Kammera7a64f32020-07-09 15:16:41 -070079 // Flags to pass to proguard.
80 Proguard_flags []string
81
82 // Specifies the locations of files containing proguard flags.
83 Proguard_flags_files []string `android:"path"`
Sam Delmerico95d70942023-08-02 18:00:35 -040084
85 // If true, transitive reverse dependencies of this module will have this
86 // module's proguard spec appended to their optimization action
87 Export_proguard_flags_files *bool
Liz Kammera7a64f32020-07-09 15:16:41 -070088 }
89
90 // Keep the data uncompressed. We always need uncompressed dex for execution,
91 // so this might actually save space by avoiding storing the same data twice.
92 // This defaults to reasonable value based on module and should not be set.
93 // It exists only to support ART tests.
94 Uncompress_dex *bool
Wei Li1e73c652021-12-06 13:35:11 -080095
Wei Li92cd54b2022-01-12 13:22:55 -080096 // Exclude kotlinc generate files: *.kotlin_module, *.kotlin_builtins. Defaults to false.
Wei Li1e73c652021-12-06 13:35:11 -080097 Exclude_kotlinc_generated_files *bool
Ulya Trafimovichc8160582024-07-10 08:32:45 +010098
99 // Disable dex container (also known as "multi-dex").
100 // This may be necessary as a temporary workaround to mask toolchain bugs (see b/341652226).
101 No_dex_container *bool
Liz Kammera7a64f32020-07-09 15:16:41 -0700102}
103
104type dexer struct {
105 dexProperties DexProperties
106
107 // list of extra proguard flag files
Colin Cross312634e2023-11-21 15:13:56 -0800108 extraProguardFlagsFiles android.Paths
109 proguardDictionary android.OptionalPath
110 proguardConfiguration android.OptionalPath
111 proguardUsageZip android.OptionalPath
112 resourcesInput android.OptionalPath
113 resourcesOutput android.OptionalPath
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500114
Colin Cross9ffaf282024-08-12 13:50:09 -0700115 providesTransitiveHeaderJarsForR8
Liz Kammera7a64f32020-07-09 15:16:41 -0700116}
117
118func (d *dexer) effectiveOptimizeEnabled() bool {
119 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
120}
121
Rico Wind936754c2024-05-07 09:08:31 +0200122func (d *DexProperties) resourceShrinkingEnabled(ctx android.ModuleContext) bool {
123 return !ctx.Config().Eng() && BoolDefault(d.Optimize.Optimized_shrink_resources, Bool(d.Optimize.Shrink_resources))
124}
125
126func (d *DexProperties) optimizedResourceShrinkingEnabled(ctx android.ModuleContext) bool {
Rico Winda7b38592024-08-26 12:10:44 +0200127 return d.resourceShrinkingEnabled(ctx) && BoolDefault(d.Optimize.Optimized_shrink_resources, ctx.Config().UseOptimizedResourceShrinkingByDefault())
Rico Winda2fa2632024-03-13 13:09:17 +0100128}
129
Spandan Das15a67112024-05-30 00:07:40 +0000130func (d *dexer) optimizeOrObfuscateEnabled() bool {
131 return d.effectiveOptimizeEnabled() && (proptools.Bool(d.dexProperties.Optimize.Optimize) || proptools.Bool(d.dexProperties.Optimize.Obfuscate))
132}
133
Colin Cross77cdcfd2021-03-12 11:28:25 -0800134var d8, d8RE = pctx.MultiCommandRemoteStaticRules("d8",
Colin Crossf0056cb2017-12-22 15:56:08 -0800135 blueprint.RuleParams{
136 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000137 `$d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700138 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700139 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700140 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Crossf0056cb2017-12-22 15:56:08 -0800141 CommandDeps: []string{
142 "${config.D8Cmd}",
143 "${config.SoongZipCmd}",
144 "${config.MergeZipsCmd}",
145 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700146 }, map[string]*remoteexec.REParams{
147 "$d8Template": &remoteexec.REParams{
148 Labels: map[string]string{"type": "compile", "compiler": "d8"},
149 Inputs: []string{"${config.D8Jar}"},
150 ExecStrategy: "${config.RED8ExecStrategy}",
151 ToolchainInputs: []string{"${config.JavaCmd}"},
152 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
153 },
154 "$zipTemplate": &remoteexec.REParams{
155 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
156 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
157 OutputFiles: []string{"$outDir/classes.dex.jar"},
158 ExecStrategy: "${config.RED8ExecStrategy}",
159 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
160 },
Ian Zernydb2d35b2023-10-10 12:22:39 +0200161 }, []string{"outDir", "d8Flags", "zipFlags", "mergeZipsFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800162
Colin Cross77cdcfd2021-03-12 11:28:25 -0800163var r8, r8RE = pctx.MultiCommandRemoteStaticRules("r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800164 blueprint.RuleParams{
165 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100166 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700167 `mkdir -p $$(dirname ${outUsage}) && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000168 `$r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200169 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700170 `-printmapping ${outDict} ` +
Jared Duke34c6d7d2023-05-05 20:40:20 +0000171 `-printconfiguration ${outConfig} ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700172 `-printusage ${outUsage} ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000173 `--deps-file ${out}.d && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100174 `touch "${outDict}" "${outConfig}" "${outUsage}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700175 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
176 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700177 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700178 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700179 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Cross22e6a6f2022-03-21 12:19:44 -0700180 Depfile: "${out}.d",
181 Deps: blueprint.DepsGCC,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800182 CommandDeps: []string{
Colin Crossa832a042021-08-05 16:56:18 -0700183 "${config.R8Cmd}",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800184 "${config.SoongZipCmd}",
185 "${config.MergeZipsCmd}",
186 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700187 }, map[string]*remoteexec.REParams{
188 "$r8Template": &remoteexec.REParams{
189 Labels: map[string]string{"type": "compile", "compiler": "r8"},
190 Inputs: []string{"$implicits", "${config.R8Jar}"},
Spandan Dasd447bbb2024-06-24 17:13:30 +0000191 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700192 ExecStrategy: "${config.RER8ExecStrategy}",
193 ToolchainInputs: []string{"${config.JavaCmd}"},
194 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
195 },
196 "$zipTemplate": &remoteexec.REParams{
197 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
198 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
199 OutputFiles: []string{"$outDir/classes.dex.jar"},
200 ExecStrategy: "${config.RER8ExecStrategy}",
201 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
202 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700203 "$zipUsageTemplate": &remoteexec.REParams{
204 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
205 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
206 OutputFiles: []string{"${outUsageZip}"},
207 ExecStrategy: "${config.RER8ExecStrategy}",
208 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
209 },
Ian Zerny82044f12023-01-25 12:11:27 +0100210 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
Spandan Dasd447bbb2024-06-24 17:13:30 +0000211 "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800212
Colin Cross5ea963e2021-09-16 19:13:43 -0700213func (d *dexer) dexCommonFlags(ctx android.ModuleContext,
Spandan Dasc404cc72023-02-23 18:05:05 +0000214 dexParams *compileDexParams) (flags []string, deps android.Paths) {
Colin Cross5ea963e2021-09-16 19:13:43 -0700215
216 flags = d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000217 // Translate all the DX flags to D8 ones until all the build files have been migrated
218 // to D8 flags. See: b/69377755
219 flags = android.RemoveListFromList(flags,
220 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800221
Colin Cross5ea963e2021-09-16 19:13:43 -0700222 for _, f := range android.PathsForModuleSrc(ctx, d.dexProperties.Main_dex_rules) {
223 flags = append(flags, "--main-dex-rules", f.String())
224 deps = append(deps, f)
225 }
226
Jared Duked32e85f2024-09-25 23:54:30 +0000227 var requestReleaseMode bool
228 requestReleaseMode, flags = android.RemoveFromList("--release", flags)
229
Abdelrahman Daim1cde8fc2024-10-01 06:55:58 -0700230 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" || ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
Colin Crossbafb8972018-06-06 21:46:32 +0000231 flags = append(flags, "--debug")
Jared Duked32e85f2024-09-25 23:54:30 +0000232 requestReleaseMode = false
Colin Crossf0056cb2017-12-22 15:56:08 -0800233 }
234
Jared Duked32e85f2024-09-25 23:54:30 +0000235 // Don't strip out debug information for eng builds, unless the target
236 // explicitly provided the `--release` build flag. This allows certain
237 // test targets to remain optimized as part of eng test_suites builds.
238 if requestReleaseMode {
239 flags = append(flags, "--release")
240 } else if ctx.Config().Eng() {
241 flags = append(flags, "--debug")
Colin Crossf0056cb2017-12-22 15:56:08 -0800242 }
243
Jared Duke40d731a2022-09-20 15:32:14 -0700244 // Supplying the platform build flag disables various features like API modeling and desugaring.
245 // For targets with a stable min SDK version (i.e., when the min SDK is both explicitly specified
246 // and managed+versioned), we suppress this flag to ensure portability.
247 // Note: Targets with a min SDK kind of core_platform (e.g., framework.jar) or unspecified (e.g.,
248 // services.jar), are not classified as stable, which is WAI.
249 // TODO(b/232073181): Expand to additional min SDK cases after validation.
Ian Zernyc26029b2023-08-25 13:43:44 +0200250 var addAndroidPlatformBuildFlag = false
Spandan Dasc404cc72023-02-23 18:05:05 +0000251 if !dexParams.sdkVersion.Stable() {
Ian Zernyc26029b2023-08-25 13:43:44 +0200252 addAndroidPlatformBuildFlag = true
Jared Duke40d731a2022-09-20 15:32:14 -0700253 }
254
Spandan Dasc404cc72023-02-23 18:05:05 +0000255 effectiveVersion, err := dexParams.minSdkVersion.EffectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700256 if err != nil {
257 ctx.PropertyErrorf("min_sdk_version", "%s", err)
258 }
David Srbecky55b46b02024-11-26 17:16:16 +0000259 if !Bool(d.dexProperties.No_dex_container) && effectiveVersion.FinalOrFutureInt() >= 36 && ctx.Config().UseDexV41() {
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000260 // W is 36, but we have not bumped the SDK version yet, so check for both.
261 if ctx.Config().PlatformSdkVersion().FinalInt() >= 36 ||
David Srbecky55b46b02024-11-26 17:16:16 +0000262 ctx.Config().PlatformSdkCodename() == "Baklava" {
263 flags = append([]string{"-JDcom.android.tools.r8.dexContainerExperiment"}, flags...)
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000264 }
265 }
Colin Cross83bb3162018-06-25 15:48:06 -0700266
Ian Zernyc26029b2023-08-25 13:43:44 +0200267 // If the specified SDK level is 10000, then configure the compiler to use the
268 // current platform SDK level and to compile the build as a platform build.
269 var minApiFlagValue = effectiveVersion.FinalOrFutureInt()
270 if minApiFlagValue == 10000 {
271 minApiFlagValue = ctx.Config().PlatformSdkVersion().FinalInt()
272 addAndroidPlatformBuildFlag = true
273 }
274 flags = append(flags, "--min-api "+strconv.Itoa(minApiFlagValue))
275
276 if addAndroidPlatformBuildFlag {
277 flags = append(flags, "--android-platform-build")
278 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700279 return flags, deps
Colin Crossf0056cb2017-12-22 15:56:08 -0800280}
281
Spandan Das3dbda182024-05-20 22:23:10 +0000282func (d *dexer) d8Flags(ctx android.ModuleContext, dexParams *compileDexParams) (d8Flags []string, d8Deps android.Paths, artProfileOutput *android.OutputPath) {
283 flags := dexParams.flags
Colin Crossc2557d12019-10-31 15:22:57 -0700284 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700285 d8Flags = append(d8Flags, flags.dexClasspath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700286
Colin Cross6dab9bd2018-09-28 08:06:24 -0700287 d8Deps = append(d8Deps, flags.bootClasspath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700288 d8Deps = append(d8Deps, flags.dexClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700289
Spandan Das3dbda182024-05-20 22:23:10 +0000290 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
291 d8Flags = append(d8Flags, flags...)
292 d8Deps = append(d8Deps, deps...)
293 artProfileOutput = profileOutput
294 }
295
296 return d8Flags, d8Deps, artProfileOutput
Colin Crossffb657e2018-09-21 12:29:22 -0700297}
298
Jared Duke91d0bee2024-11-14 23:10:09 +0000299func (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 +0000300 flags := dexParams.flags
Liz Kammera7a64f32020-07-09 15:16:41 -0700301 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800302
303 // When an app contains references to APIs that are not in the SDK specified by
304 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000305 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800306 // ProGuard, to
307 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
308 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
309 // See b/20667396
Jared Duke22468442024-08-20 20:45:35 +0000310 // TODO(b/360905238): Remove SdkSystemServer exception after resolving missing class references.
311 if !dexParams.sdkVersion.Stable() || dexParams.sdkVersion.Kind == android.SdkSystemServer {
312 var proguardRaiseDeps classpath
313 ctx.VisitDirectDepsWithTag(proguardRaiseTag, func(m android.Module) {
314 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
315 proguardRaiseDeps = append(proguardRaiseDeps, dep.RepackagedHeaderJars...)
316 }
317 })
318 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
319 r8Deps = append(r8Deps, proguardRaiseDeps...)
320 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800321
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500322 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700323 r8Deps = append(r8Deps, flags.bootClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500324 r8Flags = append(r8Flags, flags.dexClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700325 r8Deps = append(r8Deps, flags.dexClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500326
327 transitiveStaticLibsLookupMap := map[android.Path]bool{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700328 for _, jar := range d.transitiveStaticLibsHeaderJarsForR8.ToList() {
329 transitiveStaticLibsLookupMap[jar] = true
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500330 }
331 transitiveHeaderJars := android.Paths{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700332 for _, jar := range d.transitiveLibsHeaderJarsForR8.ToList() {
333 if _, ok := transitiveStaticLibsLookupMap[jar]; ok {
334 // don't include a lib if it is already packaged in the current JAR as a static lib
335 continue
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500336 }
Colin Crossa14fb6a2024-10-23 16:57:06 -0700337 transitiveHeaderJars = append(transitiveHeaderJars, jar)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500338 }
339 transitiveClasspath := classpath(transitiveHeaderJars)
340 r8Flags = append(r8Flags, transitiveClasspath.FormJavaClassPath("-libraryjars"))
341 r8Deps = append(r8Deps, transitiveClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700342
Colin Cross66dbc0b2017-12-28 12:23:20 -0800343 flagFiles := android.Paths{
344 android.PathForSource(ctx, "build/make/core/proguard.flags"),
345 }
346
Colin Cross312634e2023-11-21 15:13:56 -0800347 flagFiles = append(flagFiles, d.extraProguardFlagsFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800348 // TODO(ccross): static android library proguard files
349
Liz Kammera7a64f32020-07-09 15:16:41 -0700350 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700351
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000352 flagFiles = android.FirstUniquePaths(flagFiles)
353
Colin Cross66dbc0b2017-12-28 12:23:20 -0800354 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
355 r8Deps = append(r8Deps, flagFiles...)
356
357 // TODO(b/70942988): This is included from build/make/core/proguard.flags
358 r8Deps = append(r8Deps, android.PathForSource(ctx,
359 "build/make/core/proguard_basic_keeps.flags"))
360
Liz Kammera7a64f32020-07-09 15:16:41 -0700361 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800362
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +0100363 if BoolDefault(opt.Ignore_library_extends_program, false) {
364 r8Flags = append(r8Flags, "--ignore-library-extends-program")
365 }
366
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200367 if BoolDefault(opt.Proguard_compatibility, true) {
368 r8Flags = append(r8Flags, "--force-proguard-compatibility")
Jared Dukeb832fbb2023-09-15 17:16:36 +0000369 }
370
Jared Duke91d0bee2024-11-14 23:10:09 +0000371 // Avoid unnecessary stack frame noise by only injecting source map ids for non-debug
372 // optimized or obfuscated targets.
373 if (Bool(opt.Optimize) || Bool(opt.Obfuscate)) && !debugMode {
Ian Zernyfc7df612021-11-02 15:37:06 +0100374 // TODO(b/213833843): Allow configuration of the prefix via a build variable.
375 var sourceFilePrefix = "go/retraceme "
376 var sourceFileTemplate = "\"" + sourceFilePrefix + "%MAP_ID\""
Jared Dukeb832fbb2023-09-15 17:16:36 +0000377 r8Flags = append(r8Flags, "--map-id-template", "%MAP_HASH")
378 r8Flags = append(r8Flags, "--source-file-template", sourceFileTemplate)
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200379 }
380
Colin Cross66dbc0b2017-12-28 12:23:20 -0800381 // TODO(ccross): Don't shrink app instrumentation tests by default.
382 if !Bool(opt.Shrink) {
383 r8Flags = append(r8Flags, "-dontshrink")
384 }
385
386 if !Bool(opt.Optimize) {
387 r8Flags = append(r8Flags, "-dontoptimize")
388 }
389
390 // TODO(ccross): error if obufscation + app instrumentation test.
391 if !Bool(opt.Obfuscate) {
392 r8Flags = append(r8Flags, "-dontobfuscate")
393 }
Colin Cross4b964c02018-10-15 16:18:06 -0700394 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
395 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800396
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100397 // TODO(b/180878971): missing classes should be added to the relevant builds.
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +0000398 // TODO(b/229727645): do not use true as default for Android platform builds.
399 if proptools.BoolDefault(opt.Ignore_warnings, true) {
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +0900400 r8Flags = append(r8Flags, "-ignorewarnings")
401 }
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100402
Rico Winda2fa2632024-03-13 13:09:17 +0100403 // resourcesInput is empty when we don't use resource shrinking, if on, pass these to R8
Rico Wind98e7fa82023-11-27 09:44:03 +0100404 if d.resourcesInput.Valid() {
405 r8Flags = append(r8Flags, "--resource-input", d.resourcesInput.Path().String())
406 r8Deps = append(r8Deps, d.resourcesInput.Path())
407 r8Flags = append(r8Flags, "--resource-output", d.resourcesOutput.Path().String())
Rico Winda7b38592024-08-26 12:10:44 +0200408 if d.dexProperties.optimizedResourceShrinkingEnabled(ctx) {
Rico Winda2fa2632024-03-13 13:09:17 +0100409 r8Flags = append(r8Flags, "--optimized-resource-shrinking")
Rico Wind619ed5c2024-10-22 14:00:23 +0200410 if Bool(d.dexProperties.Optimize.Optimized_shrink_resources) {
411 // Explicitly opted into optimized shrinking, no need for keeping R$id entries
412 r8Flags = append(r8Flags, "--force-optimized-resource-shrinking")
413 }
Rico Winda2fa2632024-03-13 13:09:17 +0100414 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100415 }
416
Spandan Das3dbda182024-05-20 22:23:10 +0000417 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
418 r8Flags = append(r8Flags, flags...)
419 r8Deps = append(r8Deps, deps...)
420 artProfileOutput = profileOutput
421 }
422
Christoffer Adamsenb81fc912024-12-17 14:30:47 +0100423 if ctx.Config().UseR8StoreStoreFenceConstructorInlining() {
424 r8Flags = append(r8Flags, "--store-store-fence-constructor-inlining")
425 }
426
Spandan Das3dbda182024-05-20 22:23:10 +0000427 return r8Flags, r8Deps, artProfileOutput
Colin Cross66dbc0b2017-12-28 12:23:20 -0800428}
429
Spandan Dasc404cc72023-02-23 18:05:05 +0000430type compileDexParams struct {
Spandan Das3dbda182024-05-20 22:23:10 +0000431 flags javaBuilderFlags
432 sdkVersion android.SdkSpec
433 minSdkVersion android.ApiLevel
434 classesJar android.Path
435 jarName string
436 artProfileInput *string
Spandan Dasc404cc72023-02-23 18:05:05 +0000437}
438
Spandan Das3dbda182024-05-20 22:23:10 +0000439// Adds --art-profile to r8/d8 command.
440// r8/d8 will output a generated profile file to match the optimized dex code.
441func (d *dexer) addArtProfile(ctx android.ModuleContext, dexParams *compileDexParams) (flags []string, deps android.Paths, artProfileOutputPath *android.OutputPath) {
Cole Faust4e9f5922024-11-13 16:09:23 -0800442 if dexParams.artProfileInput == nil {
443 return nil, nil, nil
Spandan Das3dbda182024-05-20 22:23:10 +0000444 }
Cole Faust4e9f5922024-11-13 16:09:23 -0800445 artProfileInputPath := android.PathForModuleSrc(ctx, *dexParams.artProfileInput)
446 artProfileOutputPathValue := android.PathForModuleOut(ctx, "profile.prof.txt").OutputPath
447 artProfileOutputPath = &artProfileOutputPathValue
448 flags = []string{
449 "--art-profile",
450 artProfileInputPath.String(),
451 artProfileOutputPath.String(),
452 }
453 deps = append(deps, artProfileInputPath)
Spandan Das3dbda182024-05-20 22:23:10 +0000454 return flags, deps, artProfileOutputPath
455
456}
457
458// Return the compiled dex jar and (optional) profile _after_ r8 optimization
Colin Cross7707b242024-07-26 12:02:36 -0700459func (d *dexer) compileDex(ctx android.ModuleContext, dexParams *compileDexParams) (android.Path, android.Path) {
Colin Crossf0056cb2017-12-22 15:56:08 -0800460
Colin Crossf0056cb2017-12-22 15:56:08 -0800461 // Compile classes.jar into classes.dex and then javalib.jar
Spandan Dasc404cc72023-02-23 18:05:05 +0000462 javalibJar := android.PathForModuleOut(ctx, "dex", dexParams.jarName).OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800463 outDir := android.PathForModuleOut(ctx, "dex")
464
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800465 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700466 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800467 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700468 }
469
Spandan Dasc404cc72023-02-23 18:05:05 +0000470 commonFlags, commonDeps := d.dexCommonFlags(ctx, dexParams)
Liz Kammera7a64f32020-07-09 15:16:41 -0700471
Wei Li1e73c652021-12-06 13:35:11 -0800472 // Exclude kotlinc generated files when "exclude_kotlinc_generated_files" is set to true.
473 mergeZipsFlags := ""
474 if proptools.BoolDefault(d.dexProperties.Exclude_kotlinc_generated_files, false) {
475 mergeZipsFlags = "-stripFile META-INF/*.kotlin_module -stripFile **/*.kotlin_builtins"
476 }
477
Liz Kammera7a64f32020-07-09 15:16:41 -0700478 useR8 := d.effectiveOptimizeEnabled()
Spandan Das3dbda182024-05-20 22:23:10 +0000479 var artProfileOutputPath *android.OutputPath
Colin Cross66dbc0b2017-12-28 12:23:20 -0800480 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700481 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700482 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Ian Zerny82044f12023-01-25 12:11:27 +0100483 proguardConfiguration := android.PathForModuleOut(ctx, "proguard_configuration")
484 d.proguardConfiguration = android.OptionalPathForPath(proguardConfiguration)
Colin Crosscb6143a2020-08-14 17:39:29 -0700485 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
486 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
487 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
488 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
489 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Rico Wind98e7fa82023-11-27 09:44:03 +0100490 resourcesOutput := android.PathForModuleOut(ctx, "package-res-shrunken.apk")
491 d.resourcesOutput = android.OptionalPathForPath(resourcesOutput)
Spandan Das3dbda182024-05-20 22:23:10 +0000492 implicitOutputs := android.WritablePaths{
493 proguardDictionary,
494 proguardUsageZip,
495 proguardConfiguration,
496 }
Jared Duke91d0bee2024-11-14 23:10:09 +0000497 debugMode := android.InList("--debug", commonFlags)
498 r8Flags, r8Deps, r8ArtProfileOutputPath := d.r8Flags(ctx, dexParams, debugMode)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400499 rule := r8
500 args := map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800501 "r8Flags": strings.Join(append(commonFlags, r8Flags...), " "),
502 "zipFlags": zipFlags,
503 "outDict": proguardDictionary.String(),
Ian Zerny82044f12023-01-25 12:11:27 +0100504 "outConfig": proguardConfiguration.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800505 "outUsageDir": proguardUsageDir.String(),
506 "outUsage": proguardUsage.String(),
507 "outUsageZip": proguardUsageZip.String(),
508 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800509 "mergeZipsFlags": mergeZipsFlags,
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400510 }
Spandan Dasd447bbb2024-06-24 17:13:30 +0000511 if r8ArtProfileOutputPath != nil {
512 artProfileOutputPath = r8ArtProfileOutputPath
513 implicitOutputs = append(
514 implicitOutputs,
515 artProfileOutputPath,
516 )
517 // Add the implicit r8 Art profile output to args so that r8RE knows
518 // about this implicit output
519 args["outR8ArtProfile"] = artProfileOutputPath.String()
520 }
521
Ramy Medhat16f23a42020-09-03 01:29:49 -0400522 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400523 rule = r8RE
524 args["implicits"] = strings.Join(r8Deps.Strings(), ",")
525 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100526 if d.resourcesInput.Valid() {
527 implicitOutputs = append(implicitOutputs, resourcesOutput)
528 args["resourcesOutput"] = resourcesOutput.String()
529 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800530 ctx.Build(pctx, android.BuildParams{
Rico Wind98e7fa82023-11-27 09:44:03 +0100531 Rule: rule,
532 Description: "r8",
533 Output: javalibJar,
534 ImplicitOutputs: implicitOutputs,
535 Input: dexParams.classesJar,
536 Implicits: r8Deps,
537 Args: args,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800538 })
539 } else {
Spandan Das3dbda182024-05-20 22:23:10 +0000540 implicitOutputs := android.WritablePaths{}
541 d8Flags, d8Deps, d8ArtProfileOutputPath := d.d8Flags(ctx, dexParams)
542 if d8ArtProfileOutputPath != nil {
543 artProfileOutputPath = d8ArtProfileOutputPath
544 implicitOutputs = append(
545 implicitOutputs,
546 artProfileOutputPath,
547 )
548 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700549 d8Deps = append(d8Deps, commonDeps...)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400550 rule := d8
Ramy Medhat16f23a42020-09-03 01:29:49 -0400551 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400552 rule = d8RE
553 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800554 ctx.Build(pctx, android.BuildParams{
Spandan Das3dbda182024-05-20 22:23:10 +0000555 Rule: rule,
556 Description: "d8",
557 Output: javalibJar,
558 Input: dexParams.classesJar,
559 ImplicitOutputs: implicitOutputs,
560 Implicits: d8Deps,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800561 Args: map[string]string{
Wei Li1e73c652021-12-06 13:35:11 -0800562 "d8Flags": strings.Join(append(commonFlags, d8Flags...), " "),
563 "zipFlags": zipFlags,
564 "outDir": outDir.String(),
Wei Li1e73c652021-12-06 13:35:11 -0800565 "mergeZipsFlags": mergeZipsFlags,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800566 },
567 })
Colin Crossf0056cb2017-12-22 15:56:08 -0800568 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700569 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Spandan Dasc404cc72023-02-23 18:05:05 +0000570 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", dexParams.jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +0000571 TransformZipAlign(ctx, alignedJavalibJar, javalibJar, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000572 javalibJar = alignedJavalibJar
573 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800574
Spandan Das3dbda182024-05-20 22:23:10 +0000575 return javalibJar, artProfileOutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800576}