blob: dd64675461c6c36e6924648e3369f4fa6a5ffc33 [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
Christoffer Adamsen8ec5f612025-01-09 11:05:11 +010052 // Whether runtime invisible annotations should be kept by R8. Defaults to false.
53 // This is equivalent to:
54 // -keepattributes RuntimeInvisibleAnnotations,
55 // RuntimeInvisibleParameterAnnotations,
56 // RuntimeInvisibleTypeAnnotations
57 // This is only applicable when RELEASE_R8_ONLY_RUNTIME_VISIBLE_ANNOTATIONS is
58 // enabled and will be used to migrate away from keeping runtime invisible
59 // annotations (b/387958004).
60 Keep_runtime_invisible_annotations *bool
61
Jared Dukeaa88b3d2023-08-29 17:07:20 +000062 // If true, runs R8 in Proguard compatibility mode, otherwise runs R8 in full mode.
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +010063 // Defaults to false for apps and tests, true for libraries.
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +020064 Proguard_compatibility *bool
65
Christoffer Adamsen18c1da52025-02-07 03:36:47 -080066 // If true, R8 will not add public or protected members (fields or methods) to
67 // the API surface of the compilation unit, i.e., classes that are kept or
68 // have kept subclasses will not expose any members added by R8 for internal
69 // use. That includes renamed members if obfuscation is enabled.
70 // This should only be used for building targets that go on the bootclasspath.
71 // Defaults to false.
72 Protect_api_surface *bool
73
Liz Kammera7a64f32020-07-09 15:16:41 -070074 // If true, optimize for size by removing unused code. Defaults to true for apps,
75 // false for libraries and tests.
76 Shrink *bool
77
78 // If true, optimize bytecode. Defaults to false.
79 Optimize *bool
80
81 // If true, obfuscate bytecode. Defaults to false.
82 Obfuscate *bool
83
84 // If true, do not use the flag files generated by aapt that automatically keep
85 // classes referenced by the app manifest. Defaults to false.
86 No_aapt_flags *bool
87
Jared Duke51b0a102022-09-27 16:53:11 -070088 // If true, optimize for size by removing unused resources. Defaults to false.
Rico Wind351bac92022-09-22 10:41:42 +020089 Shrink_resources *bool
90
Rico Winda2fa2632024-03-13 13:09:17 +010091 // If true, use optimized resource shrinking in R8, overriding the
92 // Shrink_resources setting. Defaults to false.
93 // Optimized shrinking means that R8 will trace and treeshake resources together with code
94 // and apply additional optimizations. This implies non final fields in the R classes.
95 Optimized_shrink_resources *bool
96
Liz Kammera7a64f32020-07-09 15:16:41 -070097 // Flags to pass to proguard.
98 Proguard_flags []string
99
100 // Specifies the locations of files containing proguard flags.
101 Proguard_flags_files []string `android:"path"`
Sam Delmerico95d70942023-08-02 18:00:35 -0400102
103 // If true, transitive reverse dependencies of this module will have this
104 // module's proguard spec appended to their optimization action
105 Export_proguard_flags_files *bool
Christoffer Adamsen914fe682025-02-27 08:23:49 +0100106
107 // Path to a file containing a list of class names that should not be compiled using R8.
108 // These classes will be compiled by D8 similar to when Optimize.Enabled is false.
109 //
110 // Example:
111 //
112 // r8.exclude:
113 // com.example.Foo
114 // com.example.Bar
115 // com.example.Bar$Baz
116 //
117 // By default all classes are compiled using R8 when Optimize.Enabled is set.
118 Exclude *string `android:"path"`
Jared Duke0ac6ae72025-03-10 23:03:00 +0000119
120 // Optional list of downstream (Java) libraries from which to trace and preserve references
121 // when optimizing. Note that this requires that the source reference does *not* have
122 // a strict lib dependency on this target; dependencies should be on intermediate targets
123 // statically linked into this target, e.g., if A references B, and we want to trace and
124 // keep references from A when optimizing B, you would create an intermediate B.impl (
125 // containing all static code), have A depend on `B.impl` via libs, and set
126 // `trace_references_from: ["A"]` on B.
127 //
128 // Also note that these are *not* inherited across targets, they must be specified at the
129 // top-level target that is optimized.
130 //
131 // TODO(b/212737576): Handle this implicitly using bottom-up deps mutation and implicit
132 // creation of a proxy `.impl` library.
133 Trace_references_from proptools.Configurable[[]string] `android:"arch_variant"`
Liz Kammera7a64f32020-07-09 15:16:41 -0700134 }
135
136 // Keep the data uncompressed. We always need uncompressed dex for execution,
137 // so this might actually save space by avoiding storing the same data twice.
138 // This defaults to reasonable value based on module and should not be set.
139 // It exists only to support ART tests.
140 Uncompress_dex *bool
Wei Li1e73c652021-12-06 13:35:11 -0800141
Wei Li92cd54b2022-01-12 13:22:55 -0800142 // Exclude kotlinc generate files: *.kotlin_module, *.kotlin_builtins. Defaults to false.
Wei Li1e73c652021-12-06 13:35:11 -0800143 Exclude_kotlinc_generated_files *bool
Ulya Trafimovichc8160582024-07-10 08:32:45 +0100144
145 // Disable dex container (also known as "multi-dex").
146 // This may be necessary as a temporary workaround to mask toolchain bugs (see b/341652226).
147 No_dex_container *bool
Liz Kammera7a64f32020-07-09 15:16:41 -0700148}
149
150type dexer struct {
151 dexProperties DexProperties
152
153 // list of extra proguard flag files
Colin Cross312634e2023-11-21 15:13:56 -0800154 extraProguardFlagsFiles android.Paths
155 proguardDictionary android.OptionalPath
156 proguardConfiguration android.OptionalPath
157 proguardUsageZip android.OptionalPath
158 resourcesInput android.OptionalPath
159 resourcesOutput android.OptionalPath
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500160
Colin Cross9ffaf282024-08-12 13:50:09 -0700161 providesTransitiveHeaderJarsForR8
Liz Kammera7a64f32020-07-09 15:16:41 -0700162}
163
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700164func (d *dexer) effectiveOptimizeEnabled(ctx android.EarlyModuleContext) bool {
Satish Yalla51484872025-03-20 21:57:26 -0700165 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault && !ctx.Config().Eng())
Liz Kammera7a64f32020-07-09 15:16:41 -0700166}
167
Rico Wind936754c2024-05-07 09:08:31 +0200168func (d *DexProperties) resourceShrinkingEnabled(ctx android.ModuleContext) bool {
169 return !ctx.Config().Eng() && BoolDefault(d.Optimize.Optimized_shrink_resources, Bool(d.Optimize.Shrink_resources))
170}
171
172func (d *DexProperties) optimizedResourceShrinkingEnabled(ctx android.ModuleContext) bool {
Rico Winda7b38592024-08-26 12:10:44 +0200173 return d.resourceShrinkingEnabled(ctx) && BoolDefault(d.Optimize.Optimized_shrink_resources, ctx.Config().UseOptimizedResourceShrinkingByDefault())
Rico Winda2fa2632024-03-13 13:09:17 +0100174}
175
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700176func (d *dexer) optimizeOrObfuscateEnabled(ctx android.EarlyModuleContext) bool {
177 return d.effectiveOptimizeEnabled(ctx) && (proptools.Bool(d.dexProperties.Optimize.Optimize) || proptools.Bool(d.dexProperties.Optimize.Obfuscate))
Spandan Das15a67112024-05-30 00:07:40 +0000178}
179
Colin Cross77cdcfd2021-03-12 11:28:25 -0800180var d8, d8RE = pctx.MultiCommandRemoteStaticRules("d8",
Colin Crossf0056cb2017-12-22 15:56:08 -0800181 blueprint.RuleParams{
182 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000183 `$d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700184 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700185 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700186 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Crossf0056cb2017-12-22 15:56:08 -0800187 CommandDeps: []string{
188 "${config.D8Cmd}",
189 "${config.SoongZipCmd}",
190 "${config.MergeZipsCmd}",
191 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700192 }, map[string]*remoteexec.REParams{
193 "$d8Template": &remoteexec.REParams{
194 Labels: map[string]string{"type": "compile", "compiler": "d8"},
195 Inputs: []string{"${config.D8Jar}"},
196 ExecStrategy: "${config.RED8ExecStrategy}",
197 ToolchainInputs: []string{"${config.JavaCmd}"},
198 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
199 },
200 "$zipTemplate": &remoteexec.REParams{
201 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
202 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
203 OutputFiles: []string{"$outDir/classes.dex.jar"},
204 ExecStrategy: "${config.RED8ExecStrategy}",
205 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
206 },
Ian Zernydb2d35b2023-10-10 12:22:39 +0200207 }, []string{"outDir", "d8Flags", "zipFlags", "mergeZipsFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800208
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800209// Include all of the args for d8r8, so that we can generate the partialcompileclean target's build using the same list.
210var d8r8Clean = pctx.AndroidStaticRule("d8r8-partialcompileclean",
211 blueprint.RuleParams{
212 Command: `rm -rf "${outDir}" "${outDict}" "${outConfig}" "${outUsage}" "${outUsageZip}" "${outUsageDir}" ` +
213 `"${resourcesOutput}" "${outR8ArtProfile}" ${builtOut}`,
214 }, "outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir", "builtOut",
215 "d8Flags", "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile", "implicits",
216)
217
218var d8r8, d8r8RE = pctx.MultiCommandRemoteStaticRules("d8r8",
219 blueprint.RuleParams{
220 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
221 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
222 `mkdir -p $$(dirname ${outUsage}) && ` +
223 `if [ -n "$${SOONG_USE_PARTIAL_COMPILE}" ]; then ` +
224 ` for f in "${outConfig}" "${outDict}" "${outUsage}" "${resourcesOutput}"; do ` +
225 ` test -n "$${f}" && test ! -f "$${f}" && mkdir -p "$$(dirname "$${f}")" && touch "$${f}" || true; ` +
226 ` done && ` +
227 ` $d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in; ` +
228 `else ` +
229 ` $r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
230 ` --no-data-resources ` +
231 ` -printmapping ${outDict} ` +
232 ` -printconfiguration ${outConfig} ` +
233 ` -printusage ${outUsage} ` +
234 ` --deps-file ${out}.d && ` +
235 ` touch "${outDict}" "${outConfig}" "${outUsage}"; ` +
236 `fi && ` +
237 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
238 `rm -rf ${outUsageDir} && ` +
239 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
240 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
241 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar" `,
242 CommandDeps: []string{
243 "${config.D8Cmd}",
244 "${config.R8Cmd}",
245 "${config.SoongZipCmd}",
246 "${config.MergeZipsCmd}",
247 },
248 }, map[string]*remoteexec.REParams{
249 "$d8Template": &remoteexec.REParams{
250 Labels: map[string]string{"type": "compile", "compiler": "d8"},
251 Inputs: []string{"${config.D8Jar}"},
252 ExecStrategy: "${config.RED8ExecStrategy}",
253 ToolchainInputs: []string{"${config.JavaCmd}"},
254 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
255 },
256 "$r8Template": &remoteexec.REParams{
257 Labels: map[string]string{"type": "compile", "compiler": "r8"},
258 Inputs: []string{"$implicits", "${config.R8Jar}"},
259 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
260 ExecStrategy: "${config.RER8ExecStrategy}",
261 ToolchainInputs: []string{"${config.JavaCmd}"},
262 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
263 },
264 "$zipTemplate": &remoteexec.REParams{
265 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
266 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
267 OutputFiles: []string{"$outDir/classes.dex.jar"},
268 ExecStrategy: "${config.RED8ExecStrategy}",
269 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
270 },
271 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
272 "d8Flags", "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
273
Colin Cross77cdcfd2021-03-12 11:28:25 -0800274var r8, r8RE = pctx.MultiCommandRemoteStaticRules("r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800275 blueprint.RuleParams{
276 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100277 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700278 `mkdir -p $$(dirname ${outUsage}) && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000279 `$r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200280 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700281 `-printmapping ${outDict} ` +
Jared Duke34c6d7d2023-05-05 20:40:20 +0000282 `-printconfiguration ${outConfig} ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700283 `-printusage ${outUsage} ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000284 `--deps-file ${out}.d && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100285 `touch "${outDict}" "${outConfig}" "${outUsage}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700286 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
287 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700288 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700289 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700290 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Cross22e6a6f2022-03-21 12:19:44 -0700291 Depfile: "${out}.d",
292 Deps: blueprint.DepsGCC,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800293 CommandDeps: []string{
Colin Crossa832a042021-08-05 16:56:18 -0700294 "${config.R8Cmd}",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800295 "${config.SoongZipCmd}",
296 "${config.MergeZipsCmd}",
297 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700298 }, map[string]*remoteexec.REParams{
299 "$r8Template": &remoteexec.REParams{
300 Labels: map[string]string{"type": "compile", "compiler": "r8"},
301 Inputs: []string{"$implicits", "${config.R8Jar}"},
Spandan Dasd447bbb2024-06-24 17:13:30 +0000302 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700303 ExecStrategy: "${config.RER8ExecStrategy}",
304 ToolchainInputs: []string{"${config.JavaCmd}"},
305 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
306 },
307 "$zipTemplate": &remoteexec.REParams{
308 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
309 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
310 OutputFiles: []string{"$outDir/classes.dex.jar"},
311 ExecStrategy: "${config.RER8ExecStrategy}",
312 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
313 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700314 "$zipUsageTemplate": &remoteexec.REParams{
315 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
316 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
317 OutputFiles: []string{"${outUsageZip}"},
318 ExecStrategy: "${config.RER8ExecStrategy}",
319 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
320 },
Ian Zerny82044f12023-01-25 12:11:27 +0100321 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
Spandan Dasd447bbb2024-06-24 17:13:30 +0000322 "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800323
Colin Cross5ea963e2021-09-16 19:13:43 -0700324func (d *dexer) dexCommonFlags(ctx android.ModuleContext,
Spandan Dasc404cc72023-02-23 18:05:05 +0000325 dexParams *compileDexParams) (flags []string, deps android.Paths) {
Colin Cross5ea963e2021-09-16 19:13:43 -0700326
327 flags = d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000328 // Translate all the DX flags to D8 ones until all the build files have been migrated
329 // to D8 flags. See: b/69377755
330 flags = android.RemoveListFromList(flags,
331 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800332
Colin Cross5ea963e2021-09-16 19:13:43 -0700333 for _, f := range android.PathsForModuleSrc(ctx, d.dexProperties.Main_dex_rules) {
334 flags = append(flags, "--main-dex-rules", f.String())
335 deps = append(deps, f)
336 }
337
Jared Duke70b85422025-01-28 19:13:39 +0000338 var requestReleaseMode, requestDebugMode bool
Jared Duked32e85f2024-09-25 23:54:30 +0000339 requestReleaseMode, flags = android.RemoveFromList("--release", flags)
Jared Duke70b85422025-01-28 19:13:39 +0000340 requestDebugMode, flags = android.RemoveFromList("--debug", flags)
Jared Duked32e85f2024-09-25 23:54:30 +0000341
Abdelrahman Daim1cde8fc2024-10-01 06:55:58 -0700342 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" || ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
Jared Duke70b85422025-01-28 19:13:39 +0000343 requestDebugMode = true
Jared Duked32e85f2024-09-25 23:54:30 +0000344 requestReleaseMode = false
Colin Crossf0056cb2017-12-22 15:56:08 -0800345 }
346
Jared Duked32e85f2024-09-25 23:54:30 +0000347 // Don't strip out debug information for eng builds, unless the target
348 // explicitly provided the `--release` build flag. This allows certain
349 // test targets to remain optimized as part of eng test_suites builds.
Jared Duke70b85422025-01-28 19:13:39 +0000350 if requestDebugMode {
351 flags = append(flags, "--debug")
352 } else if requestReleaseMode {
Jared Duked32e85f2024-09-25 23:54:30 +0000353 flags = append(flags, "--release")
354 } else if ctx.Config().Eng() {
355 flags = append(flags, "--debug")
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700356 } else if !d.effectiveOptimizeEnabled(ctx) && d.dexProperties.Optimize.EnabledByDefault {
Jared Duke70b85422025-01-28 19:13:39 +0000357 // D8 uses --debug by default, whereas R8 uses --release by default.
358 // For targets that default to R8 usage (e.g., apps), but override this default, we still
359 // want D8 to run in release mode, preserving semantics as much as possible between the two.
360 flags = append(flags, "--release")
Colin Crossf0056cb2017-12-22 15:56:08 -0800361 }
362
Jared Duke40d731a2022-09-20 15:32:14 -0700363 // Supplying the platform build flag disables various features like API modeling and desugaring.
364 // For targets with a stable min SDK version (i.e., when the min SDK is both explicitly specified
365 // and managed+versioned), we suppress this flag to ensure portability.
366 // Note: Targets with a min SDK kind of core_platform (e.g., framework.jar) or unspecified (e.g.,
367 // services.jar), are not classified as stable, which is WAI.
368 // TODO(b/232073181): Expand to additional min SDK cases after validation.
Ian Zernyc26029b2023-08-25 13:43:44 +0200369 var addAndroidPlatformBuildFlag = false
Spandan Dasc404cc72023-02-23 18:05:05 +0000370 if !dexParams.sdkVersion.Stable() {
Ian Zernyc26029b2023-08-25 13:43:44 +0200371 addAndroidPlatformBuildFlag = true
Jared Duke40d731a2022-09-20 15:32:14 -0700372 }
373
Spandan Dasc404cc72023-02-23 18:05:05 +0000374 effectiveVersion, err := dexParams.minSdkVersion.EffectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700375 if err != nil {
376 ctx.PropertyErrorf("min_sdk_version", "%s", err)
377 }
David Srbecky55b46b02024-11-26 17:16:16 +0000378 if !Bool(d.dexProperties.No_dex_container) && effectiveVersion.FinalOrFutureInt() >= 36 && ctx.Config().UseDexV41() {
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000379 // W is 36, but we have not bumped the SDK version yet, so check for both.
380 if ctx.Config().PlatformSdkVersion().FinalInt() >= 36 ||
David Srbecky55b46b02024-11-26 17:16:16 +0000381 ctx.Config().PlatformSdkCodename() == "Baklava" {
382 flags = append([]string{"-JDcom.android.tools.r8.dexContainerExperiment"}, flags...)
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000383 }
384 }
Colin Cross83bb3162018-06-25 15:48:06 -0700385
Ian Zernyc26029b2023-08-25 13:43:44 +0200386 // If the specified SDK level is 10000, then configure the compiler to use the
387 // current platform SDK level and to compile the build as a platform build.
388 var minApiFlagValue = effectiveVersion.FinalOrFutureInt()
389 if minApiFlagValue == 10000 {
390 minApiFlagValue = ctx.Config().PlatformSdkVersion().FinalInt()
391 addAndroidPlatformBuildFlag = true
392 }
393 flags = append(flags, "--min-api "+strconv.Itoa(minApiFlagValue))
394
395 if addAndroidPlatformBuildFlag {
396 flags = append(flags, "--android-platform-build")
397 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700398 return flags, deps
Colin Crossf0056cb2017-12-22 15:56:08 -0800399}
400
Spandan Das3dbda182024-05-20 22:23:10 +0000401func (d *dexer) d8Flags(ctx android.ModuleContext, dexParams *compileDexParams) (d8Flags []string, d8Deps android.Paths, artProfileOutput *android.OutputPath) {
402 flags := dexParams.flags
Colin Crossc2557d12019-10-31 15:22:57 -0700403 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700404 d8Flags = append(d8Flags, flags.dexClasspath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700405
Colin Cross6dab9bd2018-09-28 08:06:24 -0700406 d8Deps = append(d8Deps, flags.bootClasspath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700407 d8Deps = append(d8Deps, flags.dexClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700408
Spandan Das3dbda182024-05-20 22:23:10 +0000409 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
410 d8Flags = append(d8Flags, flags...)
411 d8Deps = append(d8Deps, deps...)
412 artProfileOutput = profileOutput
413 }
414
415 return d8Flags, d8Deps, artProfileOutput
Colin Crossffb657e2018-09-21 12:29:22 -0700416}
417
Jared Duke91d0bee2024-11-14 23:10:09 +0000418func (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 +0000419 flags := dexParams.flags
Liz Kammera7a64f32020-07-09 15:16:41 -0700420 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800421
422 // When an app contains references to APIs that are not in the SDK specified by
423 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000424 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800425 // ProGuard, to
426 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
427 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
428 // See b/20667396
Jared Duke22468442024-08-20 20:45:35 +0000429 // TODO(b/360905238): Remove SdkSystemServer exception after resolving missing class references.
430 if !dexParams.sdkVersion.Stable() || dexParams.sdkVersion.Kind == android.SdkSystemServer {
431 var proguardRaiseDeps classpath
Yu Liuc41eae52025-01-14 01:03:08 +0000432 ctx.VisitDirectDepsProxyWithTag(proguardRaiseTag, func(m android.ModuleProxy) {
Jared Duke22468442024-08-20 20:45:35 +0000433 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
434 proguardRaiseDeps = append(proguardRaiseDeps, dep.RepackagedHeaderJars...)
435 }
436 })
437 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
438 r8Deps = append(r8Deps, proguardRaiseDeps...)
439 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800440
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500441 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700442 r8Deps = append(r8Deps, flags.bootClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500443 r8Flags = append(r8Flags, flags.dexClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700444 r8Deps = append(r8Deps, flags.dexClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500445
446 transitiveStaticLibsLookupMap := map[android.Path]bool{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700447 for _, jar := range d.transitiveStaticLibsHeaderJarsForR8.ToList() {
448 transitiveStaticLibsLookupMap[jar] = true
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500449 }
450 transitiveHeaderJars := android.Paths{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700451 for _, jar := range d.transitiveLibsHeaderJarsForR8.ToList() {
452 if _, ok := transitiveStaticLibsLookupMap[jar]; ok {
453 // don't include a lib if it is already packaged in the current JAR as a static lib
454 continue
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500455 }
Colin Crossa14fb6a2024-10-23 16:57:06 -0700456 transitiveHeaderJars = append(transitiveHeaderJars, jar)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500457 }
458 transitiveClasspath := classpath(transitiveHeaderJars)
459 r8Flags = append(r8Flags, transitiveClasspath.FormJavaClassPath("-libraryjars"))
460 r8Deps = append(r8Deps, transitiveClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700461
Colin Cross66dbc0b2017-12-28 12:23:20 -0800462 flagFiles := android.Paths{
463 android.PathForSource(ctx, "build/make/core/proguard.flags"),
464 }
465
Jared Dukeb6f8f4f2025-02-18 22:35:45 +0000466 if ctx.Config().UseR8GlobalCheckNotNullFlags() {
467 flagFiles = append(flagFiles, android.PathForSource(ctx,
468 "build/make/core/proguard/checknotnull.flags"))
469 }
470
Colin Cross312634e2023-11-21 15:13:56 -0800471 flagFiles = append(flagFiles, d.extraProguardFlagsFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800472 // TODO(ccross): static android library proguard files
473
Liz Kammera7a64f32020-07-09 15:16:41 -0700474 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700475
Jared Duke0ac6ae72025-03-10 23:03:00 +0000476 traceReferencesSources := android.Paths{}
477 ctx.VisitDirectDepsProxyWithTag(traceReferencesTag, func(m android.ModuleProxy) {
478 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
479 traceReferencesSources = append(traceReferencesSources, dep.ImplementationJars...)
480 }
481 })
482 if len(traceReferencesSources) > 0 {
483 traceTarget := dexParams.classesJar
484 traceLibs := android.FirstUniquePaths(append(flags.bootClasspath.Paths(), flags.dexClasspath.Paths()...))
485 traceReferencesFlags := android.PathForModuleOut(ctx, "proguard", "trace_references.flags")
486 TraceReferences(ctx, traceReferencesSources, traceTarget, traceLibs, traceReferencesFlags)
487 flagFiles = append(flagFiles, traceReferencesFlags)
488 }
489
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000490 flagFiles = android.FirstUniquePaths(flagFiles)
491
Colin Cross66dbc0b2017-12-28 12:23:20 -0800492 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
493 r8Deps = append(r8Deps, flagFiles...)
494
495 // TODO(b/70942988): This is included from build/make/core/proguard.flags
496 r8Deps = append(r8Deps, android.PathForSource(ctx,
497 "build/make/core/proguard_basic_keeps.flags"))
498
Liz Kammera7a64f32020-07-09 15:16:41 -0700499 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800500
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +0100501 if BoolDefault(opt.Ignore_library_extends_program, false) {
502 r8Flags = append(r8Flags, "--ignore-library-extends-program")
503 }
504
Christoffer Adamsen8ec5f612025-01-09 11:05:11 +0100505 if BoolDefault(opt.Keep_runtime_invisible_annotations, false) {
506 r8Flags = append(r8Flags, "--keep-runtime-invisible-annotations")
507 }
508
Christoffer Adamsenf4f4aa62025-01-14 09:15:11 +0100509 if BoolDefault(opt.Proguard_compatibility, !ctx.Config().UseR8FullModeByDefault()) {
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200510 r8Flags = append(r8Flags, "--force-proguard-compatibility")
Jared Dukeb832fbb2023-09-15 17:16:36 +0000511 }
512
Christoffer Adamsen18c1da52025-02-07 03:36:47 -0800513 if BoolDefault(opt.Protect_api_surface, false) {
514 r8Flags = append(r8Flags, "--protect-api-surface")
515 }
516
Jared Duke91d0bee2024-11-14 23:10:09 +0000517 // Avoid unnecessary stack frame noise by only injecting source map ids for non-debug
518 // optimized or obfuscated targets.
519 if (Bool(opt.Optimize) || Bool(opt.Obfuscate)) && !debugMode {
Ian Zernyfc7df612021-11-02 15:37:06 +0100520 // TODO(b/213833843): Allow configuration of the prefix via a build variable.
521 var sourceFilePrefix = "go/retraceme "
522 var sourceFileTemplate = "\"" + sourceFilePrefix + "%MAP_ID\""
Jared Dukeb832fbb2023-09-15 17:16:36 +0000523 r8Flags = append(r8Flags, "--map-id-template", "%MAP_HASH")
524 r8Flags = append(r8Flags, "--source-file-template", sourceFileTemplate)
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200525 }
526
Colin Cross66dbc0b2017-12-28 12:23:20 -0800527 // TODO(ccross): Don't shrink app instrumentation tests by default.
528 if !Bool(opt.Shrink) {
529 r8Flags = append(r8Flags, "-dontshrink")
530 }
531
532 if !Bool(opt.Optimize) {
533 r8Flags = append(r8Flags, "-dontoptimize")
534 }
535
536 // TODO(ccross): error if obufscation + app instrumentation test.
537 if !Bool(opt.Obfuscate) {
538 r8Flags = append(r8Flags, "-dontobfuscate")
539 }
Colin Cross4b964c02018-10-15 16:18:06 -0700540 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
541 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800542
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100543 // TODO(b/180878971): missing classes should be added to the relevant builds.
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +0000544 // TODO(b/229727645): do not use true as default for Android platform builds.
545 if proptools.BoolDefault(opt.Ignore_warnings, true) {
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +0900546 r8Flags = append(r8Flags, "-ignorewarnings")
547 }
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100548
Rico Winda2fa2632024-03-13 13:09:17 +0100549 // resourcesInput is empty when we don't use resource shrinking, if on, pass these to R8
Rico Wind98e7fa82023-11-27 09:44:03 +0100550 if d.resourcesInput.Valid() {
551 r8Flags = append(r8Flags, "--resource-input", d.resourcesInput.Path().String())
552 r8Deps = append(r8Deps, d.resourcesInput.Path())
553 r8Flags = append(r8Flags, "--resource-output", d.resourcesOutput.Path().String())
Rico Winda7b38592024-08-26 12:10:44 +0200554 if d.dexProperties.optimizedResourceShrinkingEnabled(ctx) {
Rico Winda2fa2632024-03-13 13:09:17 +0100555 r8Flags = append(r8Flags, "--optimized-resource-shrinking")
Rico Wind619ed5c2024-10-22 14:00:23 +0200556 if Bool(d.dexProperties.Optimize.Optimized_shrink_resources) {
557 // Explicitly opted into optimized shrinking, no need for keeping R$id entries
558 r8Flags = append(r8Flags, "--force-optimized-resource-shrinking")
559 }
Rico Winda2fa2632024-03-13 13:09:17 +0100560 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100561 }
562
Spandan Das3dbda182024-05-20 22:23:10 +0000563 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
564 r8Flags = append(r8Flags, flags...)
565 r8Deps = append(r8Deps, deps...)
566 artProfileOutput = profileOutput
567 }
568
Christoffer Adamsenb81fc912024-12-17 14:30:47 +0100569 if ctx.Config().UseR8StoreStoreFenceConstructorInlining() {
570 r8Flags = append(r8Flags, "--store-store-fence-constructor-inlining")
571 }
572
Christoffer Adamsen914fe682025-02-27 08:23:49 +0100573 if opt.Exclude != nil {
574 r8Flags = append(r8Flags, "--exclude", *opt.Exclude)
575 r8Deps = append(r8Deps, android.PathForModuleSrc(ctx, *opt.Exclude))
576 }
577
Spandan Das3dbda182024-05-20 22:23:10 +0000578 return r8Flags, r8Deps, artProfileOutput
Colin Cross66dbc0b2017-12-28 12:23:20 -0800579}
580
Spandan Dasc404cc72023-02-23 18:05:05 +0000581type compileDexParams struct {
Spandan Das3dbda182024-05-20 22:23:10 +0000582 flags javaBuilderFlags
583 sdkVersion android.SdkSpec
584 minSdkVersion android.ApiLevel
585 classesJar android.Path
586 jarName string
587 artProfileInput *string
Spandan Dasc404cc72023-02-23 18:05:05 +0000588}
589
Spandan Das3dbda182024-05-20 22:23:10 +0000590// Adds --art-profile to r8/d8 command.
591// r8/d8 will output a generated profile file to match the optimized dex code.
592func (d *dexer) addArtProfile(ctx android.ModuleContext, dexParams *compileDexParams) (flags []string, deps android.Paths, artProfileOutputPath *android.OutputPath) {
Cole Faust4e9f5922024-11-13 16:09:23 -0800593 if dexParams.artProfileInput == nil {
594 return nil, nil, nil
Spandan Das3dbda182024-05-20 22:23:10 +0000595 }
Cole Faust4e9f5922024-11-13 16:09:23 -0800596 artProfileInputPath := android.PathForModuleSrc(ctx, *dexParams.artProfileInput)
597 artProfileOutputPathValue := android.PathForModuleOut(ctx, "profile.prof.txt").OutputPath
598 artProfileOutputPath = &artProfileOutputPathValue
599 flags = []string{
600 "--art-profile",
601 artProfileInputPath.String(),
602 artProfileOutputPath.String(),
603 }
604 deps = append(deps, artProfileInputPath)
Spandan Das3dbda182024-05-20 22:23:10 +0000605 return flags, deps, artProfileOutputPath
606
607}
608
609// Return the compiled dex jar and (optional) profile _after_ r8 optimization
Colin Cross7707b242024-07-26 12:02:36 -0700610func (d *dexer) compileDex(ctx android.ModuleContext, dexParams *compileDexParams) (android.Path, android.Path) {
Colin Crossf0056cb2017-12-22 15:56:08 -0800611
Colin Crossf0056cb2017-12-22 15:56:08 -0800612 // Compile classes.jar into classes.dex and then javalib.jar
Spandan Dasc404cc72023-02-23 18:05:05 +0000613 javalibJar := android.PathForModuleOut(ctx, "dex", dexParams.jarName).OutputPath
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800614 cleanPhonyPath := android.PathForModuleOut(ctx, "dex", dexParams.jarName+"-partialcompileclean").OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800615 outDir := android.PathForModuleOut(ctx, "dex")
616
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800617 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700618 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800619 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700620 }
621
Spandan Dasc404cc72023-02-23 18:05:05 +0000622 commonFlags, commonDeps := d.dexCommonFlags(ctx, dexParams)
Liz Kammera7a64f32020-07-09 15:16:41 -0700623
Wei Li1e73c652021-12-06 13:35:11 -0800624 // Exclude kotlinc generated files when "exclude_kotlinc_generated_files" is set to true.
625 mergeZipsFlags := ""
626 if proptools.BoolDefault(d.dexProperties.Exclude_kotlinc_generated_files, false) {
627 mergeZipsFlags = "-stripFile META-INF/*.kotlin_module -stripFile **/*.kotlin_builtins"
628 }
629
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700630 useR8 := d.effectiveOptimizeEnabled(ctx)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800631 useD8 := !useR8 || ctx.Config().PartialCompileFlags().Use_d8
632 rbeR8 := ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8")
633 rbeD8 := ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8")
634 var rule blueprint.Rule
635 var description string
Spandan Das3dbda182024-05-20 22:23:10 +0000636 var artProfileOutputPath *android.OutputPath
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800637 var implicitOutputs android.WritablePaths
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800638 var deps android.Paths
639 args := map[string]string{
640 "zipFlags": zipFlags,
641 "outDir": outDir.String(),
642 "mergeZipsFlags": mergeZipsFlags,
643 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800644 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700645 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700646 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Ian Zerny82044f12023-01-25 12:11:27 +0100647 proguardConfiguration := android.PathForModuleOut(ctx, "proguard_configuration")
648 d.proguardConfiguration = android.OptionalPathForPath(proguardConfiguration)
Colin Crosscb6143a2020-08-14 17:39:29 -0700649 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
650 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
651 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
652 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
653 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Rico Wind98e7fa82023-11-27 09:44:03 +0100654 resourcesOutput := android.PathForModuleOut(ctx, "package-res-shrunken.apk")
655 d.resourcesOutput = android.OptionalPathForPath(resourcesOutput)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800656 implicitOutputs = append(implicitOutputs, android.WritablePaths{
Spandan Das3dbda182024-05-20 22:23:10 +0000657 proguardDictionary,
658 proguardUsageZip,
659 proguardConfiguration,
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800660 }...)
661 description = "r8"
Jared Duke91d0bee2024-11-14 23:10:09 +0000662 debugMode := android.InList("--debug", commonFlags)
663 r8Flags, r8Deps, r8ArtProfileOutputPath := d.r8Flags(ctx, dexParams, debugMode)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800664 deps = append(deps, r8Deps...)
665 args["r8Flags"] = strings.Join(append(commonFlags, r8Flags...), " ")
Spandan Dasd447bbb2024-06-24 17:13:30 +0000666 if r8ArtProfileOutputPath != nil {
667 artProfileOutputPath = r8ArtProfileOutputPath
Spandan Dasd447bbb2024-06-24 17:13:30 +0000668 // Add the implicit r8 Art profile output to args so that r8RE knows
669 // about this implicit output
LaMont Jones61d14fa2025-02-20 13:49:07 -0800670 args["outR8ArtProfile"] = r8ArtProfileOutputPath.String()
Spandan Dasd447bbb2024-06-24 17:13:30 +0000671 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800672 args["outDict"] = proguardDictionary.String()
673 args["outConfig"] = proguardConfiguration.String()
674 args["outUsageDir"] = proguardUsageDir.String()
675 args["outUsage"] = proguardUsage.String()
676 args["outUsageZip"] = proguardUsageZip.String()
Rico Wind98e7fa82023-11-27 09:44:03 +0100677 if d.resourcesInput.Valid() {
678 implicitOutputs = append(implicitOutputs, resourcesOutput)
679 args["resourcesOutput"] = resourcesOutput.String()
680 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800681
682 rule = r8
683 if rbeR8 {
684 rule = r8RE
685 args["implicits"] = strings.Join(deps.Strings(), ",")
686 }
687 }
688 if useD8 {
689 description = "d8"
Spandan Das3dbda182024-05-20 22:23:10 +0000690 d8Flags, d8Deps, d8ArtProfileOutputPath := d.d8Flags(ctx, dexParams)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800691 deps = append(deps, d8Deps...)
692 deps = append(deps, commonDeps...)
693 args["d8Flags"] = strings.Join(append(commonFlags, d8Flags...), " ")
Spandan Das3dbda182024-05-20 22:23:10 +0000694 if d8ArtProfileOutputPath != nil {
695 artProfileOutputPath = d8ArtProfileOutputPath
Spandan Das3dbda182024-05-20 22:23:10 +0000696 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800697 // If we are generating both d8 and r8, only use RBE when both are enabled.
698 switch {
699 case useR8 && rule == r8:
700 rule = d8r8
701 description = "d8r8"
702 case useR8 && rule == r8RE && rbeD8:
703 rule = d8r8RE
704 description = "d8r8"
705 case rbeD8:
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400706 rule = d8RE
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800707 default:
708 rule = d8
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400709 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800710 }
LaMont Jones61d14fa2025-02-20 13:49:07 -0800711 if artProfileOutputPath != nil {
712 implicitOutputs = append(
713 implicitOutputs,
714 artProfileOutputPath,
715 )
716 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800717 ctx.Build(pctx, android.BuildParams{
718 Rule: rule,
719 Description: description,
720 Output: javalibJar,
721 ImplicitOutputs: implicitOutputs,
722 Input: dexParams.classesJar,
723 Implicits: deps,
724 Args: args,
725 })
726 if useR8 && useD8 {
727 // Generate the rule for partial compile clean.
728 args["builtOut"] = javalibJar.String()
729 ctx.Build(pctx, android.BuildParams{
730 Rule: d8r8Clean,
731 Description: "d8r8Clean",
732 Output: cleanPhonyPath,
733 Args: args,
734 PhonyOutput: true,
735 })
736 ctx.Phony("partialcompileclean", cleanPhonyPath)
737 }
738
Liz Kammera7a64f32020-07-09 15:16:41 -0700739 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Spandan Dasc404cc72023-02-23 18:05:05 +0000740 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", dexParams.jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +0000741 TransformZipAlign(ctx, alignedJavalibJar, javalibJar, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000742 javalibJar = alignedJavalibJar
743 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800744
Spandan Das3dbda182024-05-20 22:23:10 +0000745 return javalibJar, artProfileOutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800746}
Cole Faust1dcf9e42025-02-19 17:23:34 -0800747
748type ProguardInfo struct {
749 ModuleName string
750 Class string
751 ProguardDictionary android.Path
752 ProguardUsageZip android.Path
753 ClassesJar android.Path
754}
755
756var ProguardProvider = blueprint.NewProvider[ProguardInfo]()