blob: f2406fb3c5ff6897f9da28e86ee8d2ed2e3540ff [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
LaMont Jones91e05ea2025-03-20 15:09:04 -070045 // If true, then this module will be optimized on eng builds.
46 Enabled_on_eng *bool
47
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +010048 // Whether to allow that library classes inherit from program classes.
49 // Defaults to false.
50 Ignore_library_extends_program *bool
51
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +000052 // Whether to continue building even if warnings are emitted. Defaults to true.
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +090053 Ignore_warnings *bool
54
Christoffer Adamsen8ec5f612025-01-09 11:05:11 +010055 // Whether runtime invisible annotations should be kept by R8. Defaults to false.
56 // This is equivalent to:
57 // -keepattributes RuntimeInvisibleAnnotations,
58 // RuntimeInvisibleParameterAnnotations,
59 // RuntimeInvisibleTypeAnnotations
60 // This is only applicable when RELEASE_R8_ONLY_RUNTIME_VISIBLE_ANNOTATIONS is
61 // enabled and will be used to migrate away from keeping runtime invisible
62 // annotations (b/387958004).
63 Keep_runtime_invisible_annotations *bool
64
Jared Dukeaa88b3d2023-08-29 17:07:20 +000065 // If true, runs R8 in Proguard compatibility mode, otherwise runs R8 in full mode.
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +010066 // Defaults to false for apps and tests, true for libraries.
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +020067 Proguard_compatibility *bool
68
Christoffer Adamsen18c1da52025-02-07 03:36:47 -080069 // If true, R8 will not add public or protected members (fields or methods) to
70 // the API surface of the compilation unit, i.e., classes that are kept or
71 // have kept subclasses will not expose any members added by R8 for internal
72 // use. That includes renamed members if obfuscation is enabled.
73 // This should only be used for building targets that go on the bootclasspath.
74 // Defaults to false.
75 Protect_api_surface *bool
76
Liz Kammera7a64f32020-07-09 15:16:41 -070077 // If true, optimize for size by removing unused code. Defaults to true for apps,
78 // false for libraries and tests.
79 Shrink *bool
80
81 // If true, optimize bytecode. Defaults to false.
82 Optimize *bool
83
84 // If true, obfuscate bytecode. Defaults to false.
85 Obfuscate *bool
86
87 // If true, do not use the flag files generated by aapt that automatically keep
88 // classes referenced by the app manifest. Defaults to false.
89 No_aapt_flags *bool
90
Jared Duke51b0a102022-09-27 16:53:11 -070091 // If true, optimize for size by removing unused resources. Defaults to false.
Rico Wind351bac92022-09-22 10:41:42 +020092 Shrink_resources *bool
93
Rico Winda2fa2632024-03-13 13:09:17 +010094 // If true, use optimized resource shrinking in R8, overriding the
95 // Shrink_resources setting. Defaults to false.
96 // Optimized shrinking means that R8 will trace and treeshake resources together with code
97 // and apply additional optimizations. This implies non final fields in the R classes.
98 Optimized_shrink_resources *bool
99
Liz Kammera7a64f32020-07-09 15:16:41 -0700100 // Flags to pass to proguard.
101 Proguard_flags []string
102
103 // Specifies the locations of files containing proguard flags.
104 Proguard_flags_files []string `android:"path"`
Sam Delmerico95d70942023-08-02 18:00:35 -0400105
106 // If true, transitive reverse dependencies of this module will have this
107 // module's proguard spec appended to their optimization action
108 Export_proguard_flags_files *bool
Christoffer Adamsen914fe682025-02-27 08:23:49 +0100109
110 // Path to a file containing a list of class names that should not be compiled using R8.
111 // These classes will be compiled by D8 similar to when Optimize.Enabled is false.
112 //
113 // Example:
114 //
115 // r8.exclude:
116 // com.example.Foo
117 // com.example.Bar
118 // com.example.Bar$Baz
119 //
120 // By default all classes are compiled using R8 when Optimize.Enabled is set.
121 Exclude *string `android:"path"`
Jared Duke0ac6ae72025-03-10 23:03:00 +0000122
123 // Optional list of downstream (Java) libraries from which to trace and preserve references
124 // when optimizing. Note that this requires that the source reference does *not* have
125 // a strict lib dependency on this target; dependencies should be on intermediate targets
126 // statically linked into this target, e.g., if A references B, and we want to trace and
127 // keep references from A when optimizing B, you would create an intermediate B.impl (
128 // containing all static code), have A depend on `B.impl` via libs, and set
129 // `trace_references_from: ["A"]` on B.
130 //
131 // Also note that these are *not* inherited across targets, they must be specified at the
132 // top-level target that is optimized.
133 //
134 // TODO(b/212737576): Handle this implicitly using bottom-up deps mutation and implicit
135 // creation of a proxy `.impl` library.
136 Trace_references_from proptools.Configurable[[]string] `android:"arch_variant"`
Liz Kammera7a64f32020-07-09 15:16:41 -0700137 }
138
139 // Keep the data uncompressed. We always need uncompressed dex for execution,
140 // so this might actually save space by avoiding storing the same data twice.
141 // This defaults to reasonable value based on module and should not be set.
142 // It exists only to support ART tests.
143 Uncompress_dex *bool
Wei Li1e73c652021-12-06 13:35:11 -0800144
Wei Li92cd54b2022-01-12 13:22:55 -0800145 // Exclude kotlinc generate files: *.kotlin_module, *.kotlin_builtins. Defaults to false.
Wei Li1e73c652021-12-06 13:35:11 -0800146 Exclude_kotlinc_generated_files *bool
Ulya Trafimovichc8160582024-07-10 08:32:45 +0100147
148 // Disable dex container (also known as "multi-dex").
149 // This may be necessary as a temporary workaround to mask toolchain bugs (see b/341652226).
150 No_dex_container *bool
Liz Kammera7a64f32020-07-09 15:16:41 -0700151}
152
153type dexer struct {
154 dexProperties DexProperties
155
156 // list of extra proguard flag files
Colin Cross312634e2023-11-21 15:13:56 -0800157 extraProguardFlagsFiles android.Paths
158 proguardDictionary android.OptionalPath
159 proguardConfiguration android.OptionalPath
160 proguardUsageZip android.OptionalPath
161 resourcesInput android.OptionalPath
162 resourcesOutput android.OptionalPath
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500163
Colin Cross9ffaf282024-08-12 13:50:09 -0700164 providesTransitiveHeaderJarsForR8
Liz Kammera7a64f32020-07-09 15:16:41 -0700165}
166
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700167func (d *dexer) effectiveOptimizeEnabled(ctx android.EarlyModuleContext) bool {
LaMont Jones91e05ea2025-03-20 15:09:04 -0700168 if ctx.Config().Eng() {
169 return proptools.Bool(d.dexProperties.Optimize.Enabled_on_eng)
170 }
171 return BoolDefault(d.dexProperties.Optimize.Enabled, d.dexProperties.Optimize.EnabledByDefault)
Liz Kammera7a64f32020-07-09 15:16:41 -0700172}
173
Rico Wind936754c2024-05-07 09:08:31 +0200174func (d *DexProperties) resourceShrinkingEnabled(ctx android.ModuleContext) bool {
175 return !ctx.Config().Eng() && BoolDefault(d.Optimize.Optimized_shrink_resources, Bool(d.Optimize.Shrink_resources))
176}
177
178func (d *DexProperties) optimizedResourceShrinkingEnabled(ctx android.ModuleContext) bool {
Rico Winda7b38592024-08-26 12:10:44 +0200179 return d.resourceShrinkingEnabled(ctx) && BoolDefault(d.Optimize.Optimized_shrink_resources, ctx.Config().UseOptimizedResourceShrinkingByDefault())
Rico Winda2fa2632024-03-13 13:09:17 +0100180}
181
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700182func (d *dexer) optimizeOrObfuscateEnabled(ctx android.EarlyModuleContext) bool {
183 return d.effectiveOptimizeEnabled(ctx) && (proptools.Bool(d.dexProperties.Optimize.Optimize) || proptools.Bool(d.dexProperties.Optimize.Obfuscate))
Spandan Das15a67112024-05-30 00:07:40 +0000184}
185
Colin Cross77cdcfd2021-03-12 11:28:25 -0800186var d8, d8RE = pctx.MultiCommandRemoteStaticRules("d8",
Colin Crossf0056cb2017-12-22 15:56:08 -0800187 blueprint.RuleParams{
188 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000189 `$d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700190 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700191 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700192 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Crossf0056cb2017-12-22 15:56:08 -0800193 CommandDeps: []string{
194 "${config.D8Cmd}",
195 "${config.SoongZipCmd}",
196 "${config.MergeZipsCmd}",
197 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700198 }, map[string]*remoteexec.REParams{
199 "$d8Template": &remoteexec.REParams{
200 Labels: map[string]string{"type": "compile", "compiler": "d8"},
201 Inputs: []string{"${config.D8Jar}"},
202 ExecStrategy: "${config.RED8ExecStrategy}",
203 ToolchainInputs: []string{"${config.JavaCmd}"},
204 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
205 },
206 "$zipTemplate": &remoteexec.REParams{
207 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
208 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
209 OutputFiles: []string{"$outDir/classes.dex.jar"},
210 ExecStrategy: "${config.RED8ExecStrategy}",
211 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
212 },
Ian Zernydb2d35b2023-10-10 12:22:39 +0200213 }, []string{"outDir", "d8Flags", "zipFlags", "mergeZipsFlags"}, nil)
Colin Crossf0056cb2017-12-22 15:56:08 -0800214
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800215// Include all of the args for d8r8, so that we can generate the partialcompileclean target's build using the same list.
216var d8r8Clean = pctx.AndroidStaticRule("d8r8-partialcompileclean",
217 blueprint.RuleParams{
218 Command: `rm -rf "${outDir}" "${outDict}" "${outConfig}" "${outUsage}" "${outUsageZip}" "${outUsageDir}" ` +
219 `"${resourcesOutput}" "${outR8ArtProfile}" ${builtOut}`,
220 }, "outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir", "builtOut",
221 "d8Flags", "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile", "implicits",
222)
223
224var d8r8, d8r8RE = pctx.MultiCommandRemoteStaticRules("d8r8",
225 blueprint.RuleParams{
226 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
227 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
228 `mkdir -p $$(dirname ${outUsage}) && ` +
229 `if [ -n "$${SOONG_USE_PARTIAL_COMPILE}" ]; then ` +
230 ` for f in "${outConfig}" "${outDict}" "${outUsage}" "${resourcesOutput}"; do ` +
231 ` test -n "$${f}" && test ! -f "$${f}" && mkdir -p "$$(dirname "$${f}")" && touch "$${f}" || true; ` +
232 ` done && ` +
233 ` $d8Template${config.D8Cmd} ${config.D8Flags} $d8Flags --output $outDir --no-dex-input-jar $in; ` +
234 `else ` +
235 ` $r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
236 ` --no-data-resources ` +
237 ` -printmapping ${outDict} ` +
238 ` -printconfiguration ${outConfig} ` +
239 ` -printusage ${outUsage} ` +
240 ` --deps-file ${out}.d && ` +
241 ` touch "${outDict}" "${outConfig}" "${outUsage}"; ` +
242 `fi && ` +
243 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
244 `rm -rf ${outUsageDir} && ` +
245 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
246 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
247 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar" `,
248 CommandDeps: []string{
249 "${config.D8Cmd}",
250 "${config.R8Cmd}",
251 "${config.SoongZipCmd}",
252 "${config.MergeZipsCmd}",
253 },
254 }, map[string]*remoteexec.REParams{
255 "$d8Template": &remoteexec.REParams{
256 Labels: map[string]string{"type": "compile", "compiler": "d8"},
257 Inputs: []string{"${config.D8Jar}"},
258 ExecStrategy: "${config.RED8ExecStrategy}",
259 ToolchainInputs: []string{"${config.JavaCmd}"},
260 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
261 },
262 "$r8Template": &remoteexec.REParams{
263 Labels: map[string]string{"type": "compile", "compiler": "r8"},
264 Inputs: []string{"$implicits", "${config.R8Jar}"},
265 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
266 ExecStrategy: "${config.RER8ExecStrategy}",
267 ToolchainInputs: []string{"${config.JavaCmd}"},
268 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
269 },
270 "$zipTemplate": &remoteexec.REParams{
271 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
272 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
273 OutputFiles: []string{"$outDir/classes.dex.jar"},
274 ExecStrategy: "${config.RED8ExecStrategy}",
275 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
276 },
277 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
278 "d8Flags", "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
279
Colin Cross77cdcfd2021-03-12 11:28:25 -0800280var r8, r8RE = pctx.MultiCommandRemoteStaticRules("r8",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800281 blueprint.RuleParams{
282 Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100283 `rm -f "$outDict" && rm -f "$outConfig" && rm -rf "${outUsageDir}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700284 `mkdir -p $$(dirname ${outUsage}) && ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000285 `$r8Template${config.R8Cmd} ${config.R8Flags} $r8Flags -injars $in --output $outDir ` +
Søren Gjesse24f17022018-09-14 15:20:42 +0200286 `--no-data-resources ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700287 `-printmapping ${outDict} ` +
Jared Duke34c6d7d2023-05-05 20:40:20 +0000288 `-printconfiguration ${outConfig} ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700289 `-printusage ${outUsage} ` +
David Srbeckybda964c2023-11-24 15:57:54 +0000290 `--deps-file ${out}.d && ` +
Ian Zerny82044f12023-01-25 12:11:27 +0100291 `touch "${outDict}" "${outConfig}" "${outUsage}" && ` +
Colin Crosscb6143a2020-08-14 17:39:29 -0700292 `${config.SoongZipCmd} -o ${outUsageZip} -C ${outUsageDir} -f ${outUsage} && ` +
293 `rm -rf ${outUsageDir} && ` +
Kousik Kumar366afc52020-05-20 11:27:16 -0700294 `$zipTemplate${config.SoongZipCmd} $zipFlags -o $outDir/classes.dex.jar -C $outDir -f "$outDir/classes*.dex" && ` +
Colin Cross56e28402023-09-28 14:38:06 -0700295 `${config.MergeZipsCmd} -D -stripFile "**/*.class" $mergeZipsFlags $out $outDir/classes.dex.jar $in && ` +
Haamed Gheibie90a6712024-10-04 12:37:21 -0700296 `rm -f "$outDir"/classes*.dex "$outDir/classes.dex.jar"`,
Colin Cross22e6a6f2022-03-21 12:19:44 -0700297 Depfile: "${out}.d",
298 Deps: blueprint.DepsGCC,
Colin Cross66dbc0b2017-12-28 12:23:20 -0800299 CommandDeps: []string{
Colin Crossa832a042021-08-05 16:56:18 -0700300 "${config.R8Cmd}",
Colin Cross66dbc0b2017-12-28 12:23:20 -0800301 "${config.SoongZipCmd}",
302 "${config.MergeZipsCmd}",
303 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700304 }, map[string]*remoteexec.REParams{
305 "$r8Template": &remoteexec.REParams{
306 Labels: map[string]string{"type": "compile", "compiler": "r8"},
307 Inputs: []string{"$implicits", "${config.R8Jar}"},
Spandan Dasd447bbb2024-06-24 17:13:30 +0000308 OutputFiles: []string{"${outUsage}", "${outConfig}", "${outDict}", "${resourcesOutput}", "${outR8ArtProfile}"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700309 ExecStrategy: "${config.RER8ExecStrategy}",
310 ToolchainInputs: []string{"${config.JavaCmd}"},
311 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
312 },
313 "$zipTemplate": &remoteexec.REParams{
314 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
315 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
316 OutputFiles: []string{"$outDir/classes.dex.jar"},
317 ExecStrategy: "${config.RER8ExecStrategy}",
318 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
319 },
Colin Crosscb6143a2020-08-14 17:39:29 -0700320 "$zipUsageTemplate": &remoteexec.REParams{
321 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
322 Inputs: []string{"${config.SoongZipCmd}", "${outUsage}"},
323 OutputFiles: []string{"${outUsageZip}"},
324 ExecStrategy: "${config.RER8ExecStrategy}",
325 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
326 },
Ian Zerny82044f12023-01-25 12:11:27 +0100327 }, []string{"outDir", "outDict", "outConfig", "outUsage", "outUsageZip", "outUsageDir",
Spandan Dasd447bbb2024-06-24 17:13:30 +0000328 "r8Flags", "zipFlags", "mergeZipsFlags", "resourcesOutput", "outR8ArtProfile"}, []string{"implicits"})
Colin Cross66dbc0b2017-12-28 12:23:20 -0800329
Colin Cross5ea963e2021-09-16 19:13:43 -0700330func (d *dexer) dexCommonFlags(ctx android.ModuleContext,
Spandan Dasc404cc72023-02-23 18:05:05 +0000331 dexParams *compileDexParams) (flags []string, deps android.Paths) {
Colin Cross5ea963e2021-09-16 19:13:43 -0700332
333 flags = d.dexProperties.Dxflags
Colin Crossbafb8972018-06-06 21:46:32 +0000334 // Translate all the DX flags to D8 ones until all the build files have been migrated
335 // to D8 flags. See: b/69377755
336 flags = android.RemoveListFromList(flags,
337 []string{"--core-library", "--dex", "--multi-dex"})
Colin Crossf0056cb2017-12-22 15:56:08 -0800338
Colin Cross5ea963e2021-09-16 19:13:43 -0700339 for _, f := range android.PathsForModuleSrc(ctx, d.dexProperties.Main_dex_rules) {
340 flags = append(flags, "--main-dex-rules", f.String())
341 deps = append(deps, f)
342 }
343
Jared Duke70b85422025-01-28 19:13:39 +0000344 var requestReleaseMode, requestDebugMode bool
Jared Duked32e85f2024-09-25 23:54:30 +0000345 requestReleaseMode, flags = android.RemoveFromList("--release", flags)
Jared Duke70b85422025-01-28 19:13:39 +0000346 requestDebugMode, flags = android.RemoveFromList("--debug", flags)
Jared Duked32e85f2024-09-25 23:54:30 +0000347
Abdelrahman Daim1cde8fc2024-10-01 06:55:58 -0700348 if ctx.Config().Getenv("NO_OPTIMIZE_DX") != "" || ctx.Config().Getenv("GENERATE_DEX_DEBUG") != "" {
Jared Duke70b85422025-01-28 19:13:39 +0000349 requestDebugMode = true
Jared Duked32e85f2024-09-25 23:54:30 +0000350 requestReleaseMode = false
Colin Crossf0056cb2017-12-22 15:56:08 -0800351 }
352
Jared Duked32e85f2024-09-25 23:54:30 +0000353 // Don't strip out debug information for eng builds, unless the target
354 // explicitly provided the `--release` build flag. This allows certain
355 // test targets to remain optimized as part of eng test_suites builds.
Jared Duke70b85422025-01-28 19:13:39 +0000356 if requestDebugMode {
357 flags = append(flags, "--debug")
358 } else if requestReleaseMode {
Jared Duked32e85f2024-09-25 23:54:30 +0000359 flags = append(flags, "--release")
360 } else if ctx.Config().Eng() {
361 flags = append(flags, "--debug")
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700362 } else if !d.effectiveOptimizeEnabled(ctx) && d.dexProperties.Optimize.EnabledByDefault {
Jared Duke70b85422025-01-28 19:13:39 +0000363 // D8 uses --debug by default, whereas R8 uses --release by default.
364 // For targets that default to R8 usage (e.g., apps), but override this default, we still
365 // want D8 to run in release mode, preserving semantics as much as possible between the two.
366 flags = append(flags, "--release")
Colin Crossf0056cb2017-12-22 15:56:08 -0800367 }
368
Jared Duke40d731a2022-09-20 15:32:14 -0700369 // Supplying the platform build flag disables various features like API modeling and desugaring.
370 // For targets with a stable min SDK version (i.e., when the min SDK is both explicitly specified
371 // and managed+versioned), we suppress this flag to ensure portability.
372 // Note: Targets with a min SDK kind of core_platform (e.g., framework.jar) or unspecified (e.g.,
373 // services.jar), are not classified as stable, which is WAI.
374 // TODO(b/232073181): Expand to additional min SDK cases after validation.
Ian Zernyc26029b2023-08-25 13:43:44 +0200375 var addAndroidPlatformBuildFlag = false
Spandan Dasc404cc72023-02-23 18:05:05 +0000376 if !dexParams.sdkVersion.Stable() {
Ian Zernyc26029b2023-08-25 13:43:44 +0200377 addAndroidPlatformBuildFlag = true
Jared Duke40d731a2022-09-20 15:32:14 -0700378 }
379
Spandan Dasc404cc72023-02-23 18:05:05 +0000380 effectiveVersion, err := dexParams.minSdkVersion.EffectiveVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700381 if err != nil {
382 ctx.PropertyErrorf("min_sdk_version", "%s", err)
383 }
David Srbecky55b46b02024-11-26 17:16:16 +0000384 if !Bool(d.dexProperties.No_dex_container) && effectiveVersion.FinalOrFutureInt() >= 36 && ctx.Config().UseDexV41() {
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000385 // W is 36, but we have not bumped the SDK version yet, so check for both.
386 if ctx.Config().PlatformSdkVersion().FinalInt() >= 36 ||
David Srbecky55b46b02024-11-26 17:16:16 +0000387 ctx.Config().PlatformSdkCodename() == "Baklava" {
388 flags = append([]string{"-JDcom.android.tools.r8.dexContainerExperiment"}, flags...)
Ulya Trofimovich5bb46812024-08-07 19:25:58 +0000389 }
390 }
Colin Cross83bb3162018-06-25 15:48:06 -0700391
Ian Zernyc26029b2023-08-25 13:43:44 +0200392 // If the specified SDK level is 10000, then configure the compiler to use the
393 // current platform SDK level and to compile the build as a platform build.
394 var minApiFlagValue = effectiveVersion.FinalOrFutureInt()
395 if minApiFlagValue == 10000 {
396 minApiFlagValue = ctx.Config().PlatformSdkVersion().FinalInt()
397 addAndroidPlatformBuildFlag = true
398 }
399 flags = append(flags, "--min-api "+strconv.Itoa(minApiFlagValue))
400
401 if addAndroidPlatformBuildFlag {
402 flags = append(flags, "--android-platform-build")
403 }
Colin Cross5ea963e2021-09-16 19:13:43 -0700404 return flags, deps
Colin Crossf0056cb2017-12-22 15:56:08 -0800405}
406
Spandan Das3dbda182024-05-20 22:23:10 +0000407func (d *dexer) d8Flags(ctx android.ModuleContext, dexParams *compileDexParams) (d8Flags []string, d8Deps android.Paths, artProfileOutput *android.OutputPath) {
408 flags := dexParams.flags
Colin Crossc2557d12019-10-31 15:22:57 -0700409 d8Flags = append(d8Flags, flags.bootClasspath.FormRepeatedClassPath("--lib ")...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700410 d8Flags = append(d8Flags, flags.dexClasspath.FormRepeatedClassPath("--lib ")...)
Colin Crossffb657e2018-09-21 12:29:22 -0700411
Colin Cross6dab9bd2018-09-28 08:06:24 -0700412 d8Deps = append(d8Deps, flags.bootClasspath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700413 d8Deps = append(d8Deps, flags.dexClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700414
Spandan Das3dbda182024-05-20 22:23:10 +0000415 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
416 d8Flags = append(d8Flags, flags...)
417 d8Deps = append(d8Deps, deps...)
418 artProfileOutput = profileOutput
419 }
420
421 return d8Flags, d8Deps, artProfileOutput
Colin Crossffb657e2018-09-21 12:29:22 -0700422}
423
Jared Duke91d0bee2024-11-14 23:10:09 +0000424func (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 +0000425 flags := dexParams.flags
Liz Kammera7a64f32020-07-09 15:16:41 -0700426 opt := d.dexProperties.Optimize
Colin Cross66dbc0b2017-12-28 12:23:20 -0800427
428 // When an app contains references to APIs that are not in the SDK specified by
429 // its LOCAL_SDK_VERSION for example added by support library or by runtime
Colin Crossbafb8972018-06-06 21:46:32 +0000430 // classes added by desugaring, we artifically raise the "SDK version" "linked" by
Colin Cross66dbc0b2017-12-28 12:23:20 -0800431 // ProGuard, to
432 // - suppress ProGuard warnings of referencing symbols unknown to the lower SDK version.
433 // - prevent ProGuard stripping subclass in the support library that extends class added in the higher SDK version.
434 // See b/20667396
Jared Duke22468442024-08-20 20:45:35 +0000435 // TODO(b/360905238): Remove SdkSystemServer exception after resolving missing class references.
436 if !dexParams.sdkVersion.Stable() || dexParams.sdkVersion.Kind == android.SdkSystemServer {
437 var proguardRaiseDeps classpath
Yu Liuc41eae52025-01-14 01:03:08 +0000438 ctx.VisitDirectDepsProxyWithTag(proguardRaiseTag, func(m android.ModuleProxy) {
Jared Duke22468442024-08-20 20:45:35 +0000439 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
440 proguardRaiseDeps = append(proguardRaiseDeps, dep.RepackagedHeaderJars...)
441 }
442 })
443 r8Flags = append(r8Flags, proguardRaiseDeps.FormJavaClassPath("-libraryjars"))
444 r8Deps = append(r8Deps, proguardRaiseDeps...)
445 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800446
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500447 r8Flags = append(r8Flags, flags.bootClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross6dab9bd2018-09-28 08:06:24 -0700448 r8Deps = append(r8Deps, flags.bootClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500449 r8Flags = append(r8Flags, flags.dexClasspath.FormJavaClassPath("-libraryjars"))
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700450 r8Deps = append(r8Deps, flags.dexClasspath...)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500451
452 transitiveStaticLibsLookupMap := map[android.Path]bool{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700453 for _, jar := range d.transitiveStaticLibsHeaderJarsForR8.ToList() {
454 transitiveStaticLibsLookupMap[jar] = true
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500455 }
456 transitiveHeaderJars := android.Paths{}
Colin Crossa14fb6a2024-10-23 16:57:06 -0700457 for _, jar := range d.transitiveLibsHeaderJarsForR8.ToList() {
458 if _, ok := transitiveStaticLibsLookupMap[jar]; ok {
459 // don't include a lib if it is already packaged in the current JAR as a static lib
460 continue
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500461 }
Colin Crossa14fb6a2024-10-23 16:57:06 -0700462 transitiveHeaderJars = append(transitiveHeaderJars, jar)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500463 }
464 transitiveClasspath := classpath(transitiveHeaderJars)
465 r8Flags = append(r8Flags, transitiveClasspath.FormJavaClassPath("-libraryjars"))
466 r8Deps = append(r8Deps, transitiveClasspath...)
Colin Cross6dab9bd2018-09-28 08:06:24 -0700467
Colin Cross66dbc0b2017-12-28 12:23:20 -0800468 flagFiles := android.Paths{
469 android.PathForSource(ctx, "build/make/core/proguard.flags"),
470 }
471
Jared Dukeb6f8f4f2025-02-18 22:35:45 +0000472 if ctx.Config().UseR8GlobalCheckNotNullFlags() {
473 flagFiles = append(flagFiles, android.PathForSource(ctx,
474 "build/make/core/proguard/checknotnull.flags"))
475 }
476
Colin Cross312634e2023-11-21 15:13:56 -0800477 flagFiles = append(flagFiles, d.extraProguardFlagsFiles...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800478 // TODO(ccross): static android library proguard files
479
Liz Kammera7a64f32020-07-09 15:16:41 -0700480 flagFiles = append(flagFiles, android.PathsForModuleSrc(ctx, opt.Proguard_flags_files)...)
Colin Crossbd1cef52018-08-13 10:28:18 -0700481
Jared Duke0ac6ae72025-03-10 23:03:00 +0000482 traceReferencesSources := android.Paths{}
483 ctx.VisitDirectDepsProxyWithTag(traceReferencesTag, func(m android.ModuleProxy) {
484 if dep, ok := android.OtherModuleProvider(ctx, m, JavaInfoProvider); ok {
485 traceReferencesSources = append(traceReferencesSources, dep.ImplementationJars...)
486 }
487 })
488 if len(traceReferencesSources) > 0 {
489 traceTarget := dexParams.classesJar
490 traceLibs := android.FirstUniquePaths(append(flags.bootClasspath.Paths(), flags.dexClasspath.Paths()...))
491 traceReferencesFlags := android.PathForModuleOut(ctx, "proguard", "trace_references.flags")
492 TraceReferences(ctx, traceReferencesSources, traceTarget, traceLibs, traceReferencesFlags)
493 flagFiles = append(flagFiles, traceReferencesFlags)
494 }
495
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000496 flagFiles = android.FirstUniquePaths(flagFiles)
497
Colin Cross66dbc0b2017-12-28 12:23:20 -0800498 r8Flags = append(r8Flags, android.JoinWithPrefix(flagFiles.Strings(), "-include "))
499 r8Deps = append(r8Deps, flagFiles...)
500
501 // TODO(b/70942988): This is included from build/make/core/proguard.flags
502 r8Deps = append(r8Deps, android.PathForSource(ctx,
503 "build/make/core/proguard_basic_keeps.flags"))
504
Liz Kammera7a64f32020-07-09 15:16:41 -0700505 r8Flags = append(r8Flags, opt.Proguard_flags...)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800506
Christoffer Adamsenc8fd1f12025-01-06 19:04:03 +0100507 if BoolDefault(opt.Ignore_library_extends_program, false) {
508 r8Flags = append(r8Flags, "--ignore-library-extends-program")
509 }
510
Christoffer Adamsen8ec5f612025-01-09 11:05:11 +0100511 if BoolDefault(opt.Keep_runtime_invisible_annotations, false) {
512 r8Flags = append(r8Flags, "--keep-runtime-invisible-annotations")
513 }
514
Christoffer Adamsenf4f4aa62025-01-14 09:15:11 +0100515 if BoolDefault(opt.Proguard_compatibility, !ctx.Config().UseR8FullModeByDefault()) {
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200516 r8Flags = append(r8Flags, "--force-proguard-compatibility")
Jared Dukeb832fbb2023-09-15 17:16:36 +0000517 }
518
Christoffer Adamsen18c1da52025-02-07 03:36:47 -0800519 if BoolDefault(opt.Protect_api_surface, false) {
520 r8Flags = append(r8Flags, "--protect-api-surface")
521 }
522
Jared Duke91d0bee2024-11-14 23:10:09 +0000523 // Avoid unnecessary stack frame noise by only injecting source map ids for non-debug
524 // optimized or obfuscated targets.
525 if (Bool(opt.Optimize) || Bool(opt.Obfuscate)) && !debugMode {
Ian Zernyfc7df612021-11-02 15:37:06 +0100526 // TODO(b/213833843): Allow configuration of the prefix via a build variable.
527 var sourceFilePrefix = "go/retraceme "
528 var sourceFileTemplate = "\"" + sourceFilePrefix + "%MAP_ID\""
Jared Dukeb832fbb2023-09-15 17:16:36 +0000529 r8Flags = append(r8Flags, "--map-id-template", "%MAP_HASH")
530 r8Flags = append(r8Flags, "--source-file-template", sourceFileTemplate)
Christoffer Quist Adamsenf2d7b162020-08-24 15:56:16 +0200531 }
532
Colin Cross66dbc0b2017-12-28 12:23:20 -0800533 // TODO(ccross): Don't shrink app instrumentation tests by default.
534 if !Bool(opt.Shrink) {
535 r8Flags = append(r8Flags, "-dontshrink")
536 }
537
538 if !Bool(opt.Optimize) {
539 r8Flags = append(r8Flags, "-dontoptimize")
540 }
541
542 // TODO(ccross): error if obufscation + app instrumentation test.
543 if !Bool(opt.Obfuscate) {
544 r8Flags = append(r8Flags, "-dontobfuscate")
545 }
Colin Cross4b964c02018-10-15 16:18:06 -0700546 // TODO(ccross): if this is an instrumentation test of an obfuscated app, use the
547 // dictionary of the app and move the app from libraryjars to injars.
Colin Cross66dbc0b2017-12-28 12:23:20 -0800548
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100549 // TODO(b/180878971): missing classes should be added to the relevant builds.
Ajinkya Chalkeddad41b2023-02-09 14:09:58 +0000550 // TODO(b/229727645): do not use true as default for Android platform builds.
551 if proptools.BoolDefault(opt.Ignore_warnings, true) {
Remi NGUYEN VANbdad3142022-08-04 13:19:03 +0900552 r8Flags = append(r8Flags, "-ignorewarnings")
553 }
Christoffer Quist Adamsene8507372021-02-22 09:44:09 +0100554
Rico Winda2fa2632024-03-13 13:09:17 +0100555 // resourcesInput is empty when we don't use resource shrinking, if on, pass these to R8
Rico Wind98e7fa82023-11-27 09:44:03 +0100556 if d.resourcesInput.Valid() {
557 r8Flags = append(r8Flags, "--resource-input", d.resourcesInput.Path().String())
558 r8Deps = append(r8Deps, d.resourcesInput.Path())
559 r8Flags = append(r8Flags, "--resource-output", d.resourcesOutput.Path().String())
Rico Winda7b38592024-08-26 12:10:44 +0200560 if d.dexProperties.optimizedResourceShrinkingEnabled(ctx) {
Rico Winda2fa2632024-03-13 13:09:17 +0100561 r8Flags = append(r8Flags, "--optimized-resource-shrinking")
Rico Wind619ed5c2024-10-22 14:00:23 +0200562 if Bool(d.dexProperties.Optimize.Optimized_shrink_resources) {
563 // Explicitly opted into optimized shrinking, no need for keeping R$id entries
564 r8Flags = append(r8Flags, "--force-optimized-resource-shrinking")
565 }
Rico Winda2fa2632024-03-13 13:09:17 +0100566 }
Rico Wind98e7fa82023-11-27 09:44:03 +0100567 }
568
Spandan Das3dbda182024-05-20 22:23:10 +0000569 if flags, deps, profileOutput := d.addArtProfile(ctx, dexParams); profileOutput != nil {
570 r8Flags = append(r8Flags, flags...)
571 r8Deps = append(r8Deps, deps...)
572 artProfileOutput = profileOutput
573 }
574
Christoffer Adamsenb81fc912024-12-17 14:30:47 +0100575 if ctx.Config().UseR8StoreStoreFenceConstructorInlining() {
576 r8Flags = append(r8Flags, "--store-store-fence-constructor-inlining")
577 }
578
Christoffer Adamsen914fe682025-02-27 08:23:49 +0100579 if opt.Exclude != nil {
580 r8Flags = append(r8Flags, "--exclude", *opt.Exclude)
581 r8Deps = append(r8Deps, android.PathForModuleSrc(ctx, *opt.Exclude))
582 }
583
Spandan Das3dbda182024-05-20 22:23:10 +0000584 return r8Flags, r8Deps, artProfileOutput
Colin Cross66dbc0b2017-12-28 12:23:20 -0800585}
586
Spandan Dasc404cc72023-02-23 18:05:05 +0000587type compileDexParams struct {
Spandan Das3dbda182024-05-20 22:23:10 +0000588 flags javaBuilderFlags
589 sdkVersion android.SdkSpec
590 minSdkVersion android.ApiLevel
591 classesJar android.Path
592 jarName string
593 artProfileInput *string
Spandan Dasc404cc72023-02-23 18:05:05 +0000594}
595
Spandan Das3dbda182024-05-20 22:23:10 +0000596// Adds --art-profile to r8/d8 command.
597// r8/d8 will output a generated profile file to match the optimized dex code.
598func (d *dexer) addArtProfile(ctx android.ModuleContext, dexParams *compileDexParams) (flags []string, deps android.Paths, artProfileOutputPath *android.OutputPath) {
Cole Faust4e9f5922024-11-13 16:09:23 -0800599 if dexParams.artProfileInput == nil {
600 return nil, nil, nil
Spandan Das3dbda182024-05-20 22:23:10 +0000601 }
Cole Faust4e9f5922024-11-13 16:09:23 -0800602 artProfileInputPath := android.PathForModuleSrc(ctx, *dexParams.artProfileInput)
603 artProfileOutputPathValue := android.PathForModuleOut(ctx, "profile.prof.txt").OutputPath
604 artProfileOutputPath = &artProfileOutputPathValue
605 flags = []string{
606 "--art-profile",
607 artProfileInputPath.String(),
608 artProfileOutputPath.String(),
609 }
610 deps = append(deps, artProfileInputPath)
Spandan Das3dbda182024-05-20 22:23:10 +0000611 return flags, deps, artProfileOutputPath
612
613}
614
615// Return the compiled dex jar and (optional) profile _after_ r8 optimization
Colin Cross7707b242024-07-26 12:02:36 -0700616func (d *dexer) compileDex(ctx android.ModuleContext, dexParams *compileDexParams) (android.Path, android.Path) {
Colin Crossf0056cb2017-12-22 15:56:08 -0800617
Colin Crossf0056cb2017-12-22 15:56:08 -0800618 // Compile classes.jar into classes.dex and then javalib.jar
Spandan Dasc404cc72023-02-23 18:05:05 +0000619 javalibJar := android.PathForModuleOut(ctx, "dex", dexParams.jarName).OutputPath
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800620 cleanPhonyPath := android.PathForModuleOut(ctx, "dex", dexParams.jarName+"-partialcompileclean").OutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800621 outDir := android.PathForModuleOut(ctx, "dex")
622
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800623 zipFlags := "--ignore_missing_files"
Liz Kammera7a64f32020-07-09 15:16:41 -0700624 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Sasha Smundakd3cf4ee2019-02-15 10:14:23 -0800625 zipFlags += " -L 0"
Colin Cross5a0dcd52018-10-05 14:20:06 -0700626 }
627
Spandan Dasc404cc72023-02-23 18:05:05 +0000628 commonFlags, commonDeps := d.dexCommonFlags(ctx, dexParams)
Liz Kammera7a64f32020-07-09 15:16:41 -0700629
Wei Li1e73c652021-12-06 13:35:11 -0800630 // Exclude kotlinc generated files when "exclude_kotlinc_generated_files" is set to true.
631 mergeZipsFlags := ""
632 if proptools.BoolDefault(d.dexProperties.Exclude_kotlinc_generated_files, false) {
633 mergeZipsFlags = "-stripFile META-INF/*.kotlin_module -stripFile **/*.kotlin_builtins"
634 }
635
LaMont Jonesb97f1d12025-03-18 15:18:58 -0700636 useR8 := d.effectiveOptimizeEnabled(ctx)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800637 useD8 := !useR8 || ctx.Config().PartialCompileFlags().Use_d8
638 rbeR8 := ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_R8")
639 rbeD8 := ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_D8")
640 var rule blueprint.Rule
641 var description string
Spandan Das3dbda182024-05-20 22:23:10 +0000642 var artProfileOutputPath *android.OutputPath
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800643 var implicitOutputs android.WritablePaths
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800644 var deps android.Paths
645 args := map[string]string{
646 "zipFlags": zipFlags,
647 "outDir": outDir.String(),
648 "mergeZipsFlags": mergeZipsFlags,
649 }
Colin Cross66dbc0b2017-12-28 12:23:20 -0800650 if useR8 {
Colin Crossc0c664c2018-05-16 16:47:21 -0700651 proguardDictionary := android.PathForModuleOut(ctx, "proguard_dictionary")
Liz Kammera7a64f32020-07-09 15:16:41 -0700652 d.proguardDictionary = android.OptionalPathForPath(proguardDictionary)
Ian Zerny82044f12023-01-25 12:11:27 +0100653 proguardConfiguration := android.PathForModuleOut(ctx, "proguard_configuration")
654 d.proguardConfiguration = android.OptionalPathForPath(proguardConfiguration)
Colin Crosscb6143a2020-08-14 17:39:29 -0700655 proguardUsageDir := android.PathForModuleOut(ctx, "proguard_usage")
656 proguardUsage := proguardUsageDir.Join(ctx, ctx.Namespace().Path,
657 android.ModuleNameWithPossibleOverride(ctx), "unused.txt")
658 proguardUsageZip := android.PathForModuleOut(ctx, "proguard_usage.zip")
659 d.proguardUsageZip = android.OptionalPathForPath(proguardUsageZip)
Rico Wind98e7fa82023-11-27 09:44:03 +0100660 resourcesOutput := android.PathForModuleOut(ctx, "package-res-shrunken.apk")
661 d.resourcesOutput = android.OptionalPathForPath(resourcesOutput)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800662 implicitOutputs = append(implicitOutputs, android.WritablePaths{
Spandan Das3dbda182024-05-20 22:23:10 +0000663 proguardDictionary,
664 proguardUsageZip,
665 proguardConfiguration,
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800666 }...)
667 description = "r8"
Jared Duke91d0bee2024-11-14 23:10:09 +0000668 debugMode := android.InList("--debug", commonFlags)
669 r8Flags, r8Deps, r8ArtProfileOutputPath := d.r8Flags(ctx, dexParams, debugMode)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800670 deps = append(deps, r8Deps...)
671 args["r8Flags"] = strings.Join(append(commonFlags, r8Flags...), " ")
Spandan Dasd447bbb2024-06-24 17:13:30 +0000672 if r8ArtProfileOutputPath != nil {
673 artProfileOutputPath = r8ArtProfileOutputPath
Spandan Dasd447bbb2024-06-24 17:13:30 +0000674 // Add the implicit r8 Art profile output to args so that r8RE knows
675 // about this implicit output
LaMont Jones61d14fa2025-02-20 13:49:07 -0800676 args["outR8ArtProfile"] = r8ArtProfileOutputPath.String()
Spandan Dasd447bbb2024-06-24 17:13:30 +0000677 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800678 args["outDict"] = proguardDictionary.String()
679 args["outConfig"] = proguardConfiguration.String()
680 args["outUsageDir"] = proguardUsageDir.String()
681 args["outUsage"] = proguardUsage.String()
682 args["outUsageZip"] = proguardUsageZip.String()
Rico Wind98e7fa82023-11-27 09:44:03 +0100683 if d.resourcesInput.Valid() {
684 implicitOutputs = append(implicitOutputs, resourcesOutput)
685 args["resourcesOutput"] = resourcesOutput.String()
686 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800687
688 rule = r8
689 if rbeR8 {
690 rule = r8RE
691 args["implicits"] = strings.Join(deps.Strings(), ",")
692 }
693 }
694 if useD8 {
695 description = "d8"
Spandan Das3dbda182024-05-20 22:23:10 +0000696 d8Flags, d8Deps, d8ArtProfileOutputPath := d.d8Flags(ctx, dexParams)
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800697 deps = append(deps, d8Deps...)
698 deps = append(deps, commonDeps...)
699 args["d8Flags"] = strings.Join(append(commonFlags, d8Flags...), " ")
Spandan Das3dbda182024-05-20 22:23:10 +0000700 if d8ArtProfileOutputPath != nil {
701 artProfileOutputPath = d8ArtProfileOutputPath
Spandan Das3dbda182024-05-20 22:23:10 +0000702 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800703 // If we are generating both d8 and r8, only use RBE when both are enabled.
704 switch {
705 case useR8 && rule == r8:
706 rule = d8r8
707 description = "d8r8"
708 case useR8 && rule == r8RE && rbeD8:
709 rule = d8r8RE
710 description = "d8r8"
711 case rbeD8:
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400712 rule = d8RE
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800713 default:
714 rule = d8
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400715 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800716 }
LaMont Jones61d14fa2025-02-20 13:49:07 -0800717 if artProfileOutputPath != nil {
718 implicitOutputs = append(
719 implicitOutputs,
720 artProfileOutputPath,
721 )
722 }
LaMont Jonesed6f2b22025-02-10 16:24:40 -0800723 ctx.Build(pctx, android.BuildParams{
724 Rule: rule,
725 Description: description,
726 Output: javalibJar,
727 ImplicitOutputs: implicitOutputs,
728 Input: dexParams.classesJar,
729 Implicits: deps,
730 Args: args,
731 })
732 if useR8 && useD8 {
733 // Generate the rule for partial compile clean.
734 args["builtOut"] = javalibJar.String()
735 ctx.Build(pctx, android.BuildParams{
736 Rule: d8r8Clean,
737 Description: "d8r8Clean",
738 Output: cleanPhonyPath,
739 Args: args,
740 PhonyOutput: true,
741 })
742 ctx.Phony("partialcompileclean", cleanPhonyPath)
743 }
744
Liz Kammera7a64f32020-07-09 15:16:41 -0700745 if proptools.Bool(d.dexProperties.Uncompress_dex) {
Spandan Dasc404cc72023-02-23 18:05:05 +0000746 alignedJavalibJar := android.PathForModuleOut(ctx, "aligned", dexParams.jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +0000747 TransformZipAlign(ctx, alignedJavalibJar, javalibJar, nil)
Nicolas Geoffray65fd8ba2019-01-21 23:20:23 +0000748 javalibJar = alignedJavalibJar
749 }
Colin Crossf0056cb2017-12-22 15:56:08 -0800750
Spandan Das3dbda182024-05-20 22:23:10 +0000751 return javalibJar, artProfileOutputPath
Colin Crossf0056cb2017-12-22 15:56:08 -0800752}
Cole Faust1dcf9e42025-02-19 17:23:34 -0800753
754type ProguardInfo struct {
755 ModuleName string
756 Class string
757 ProguardDictionary android.Path
758 ProguardUsageZip android.Path
759 ClassesJar android.Path
760}
761
762var ProguardProvider = blueprint.NewProvider[ProguardInfo]()