blob: 57aaa1a2dde6dcd0ce5d69706fe090a89e4a9dcd [file] [log] [blame]
Colin Cross43f08db2018-11-12 10:13:39 -08001// Copyright 2018 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 (
Jiakai Zhangca9bc982021-09-09 08:09:41 +000018 "path/filepath"
Jiakai Zhang51b2a8b2023-06-26 16:47:38 +010019 "sort"
Jiakai Zhangca9bc982021-09-09 08:09:41 +000020 "strings"
21
Spandan Das3dbda182024-05-20 22:23:10 +000022 "github.com/google/blueprint/proptools"
23
Colin Cross43f08db2018-11-12 10:13:39 -080024 "android/soong/android"
25 "android/soong/dexpreopt"
26)
27
Jiakai Zhangca9bc982021-09-09 08:09:41 +000028type DexpreopterInterface interface {
Jiakai Zhang81e46812023-02-08 21:56:07 +080029 // True if the java module is to be dexed and installed on devices.
30 // Structs that embed dexpreopter must implement this.
31 IsInstallable() bool
32
33 // True if dexpreopt is disabled for the java module.
Spandan Dase21a8d42024-01-23 23:56:29 +000034 dexpreoptDisabled(ctx android.BaseModuleContext, libraryName string) bool
Jiakai Zhang81e46812023-02-08 21:56:07 +080035
36 // If the java module is to be installed into an APEX, this list contains information about the
37 // dexpreopt outputs to be installed on devices. Note that these dexpreopt outputs are installed
38 // outside of the APEX.
Jiakai Zhangca9bc982021-09-09 08:09:41 +000039 DexpreoptBuiltInstalledForApex() []dexpreopterInstall
Jiakai Zhang81e46812023-02-08 21:56:07 +080040
41 // The Make entries to install the dexpreopt outputs. Derived from
42 // `DexpreoptBuiltInstalledForApex`.
Jiakai Zhangca9bc982021-09-09 08:09:41 +000043 AndroidMkEntriesForApex() []android.AndroidMkEntries
Jiakai Zhang81e46812023-02-08 21:56:07 +080044
45 // See `dexpreopter.outputProfilePathOnHost`.
46 OutputProfilePathOnHost() android.Path
Jiakai Zhangca9bc982021-09-09 08:09:41 +000047}
48
49type dexpreopterInstall struct {
50 // A unique name to distinguish an output from others for the same java library module. Usually in
51 // the form of `<arch>-<encoded-path>.odex/vdex/art`.
52 name string
53
54 // The name of the input java module.
55 moduleName string
56
57 // The path to the dexpreopt output on host.
58 outputPathOnHost android.Path
59
60 // The directory on the device for the output to install to.
61 installDirOnDevice android.InstallPath
62
63 // The basename (the last segment of the path) for the output to install as.
64 installFileOnDevice string
65}
66
67// The full module name of the output in the makefile.
68func (install *dexpreopterInstall) FullModuleName() string {
69 return install.moduleName + install.SubModuleName()
70}
71
72// The sub-module name of the output in the makefile (the name excluding the java module name).
73func (install *dexpreopterInstall) SubModuleName() string {
74 return "-dexpreopt-" + install.name
Martin Stjernholm6d415272020-01-31 17:10:36 +000075}
76
Jiakai Zhang6decef92022-01-12 17:56:19 +000077// Returns Make entries for installing the file.
78//
79// This function uses a value receiver rather than a pointer receiver to ensure that the object is
80// safe to use in `android.AndroidMkExtraEntriesFunc`.
81func (install dexpreopterInstall) ToMakeEntries() android.AndroidMkEntries {
82 return android.AndroidMkEntries{
83 Class: "ETC",
Jiakai Zhang6decef92022-01-12 17:56:19 +000084 OutputFile: android.OptionalPathForPath(install.outputPathOnHost),
85 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
86 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
Spandan Das2069c3f2023-12-06 19:40:24 +000087 entries.SetString("LOCAL_MODULE", install.FullModuleName())
Jiakai Zhang6decef92022-01-12 17:56:19 +000088 entries.SetString("LOCAL_MODULE_PATH", install.installDirOnDevice.String())
89 entries.SetString("LOCAL_INSTALLED_MODULE_STEM", install.installFileOnDevice)
90 entries.SetString("LOCAL_NOT_AVAILABLE_FOR_PLATFORM", "false")
Spandan Das2069c3f2023-12-06 19:40:24 +000091 // Unset LOCAL_SOONG_INSTALLED_MODULE so that this does not default to the primary .apex file
92 // Without this, installation of the dexpreopt artifacts get skipped
93 entries.SetString("LOCAL_SOONG_INSTALLED_MODULE", "")
Jiakai Zhang6decef92022-01-12 17:56:19 +000094 },
95 },
96 }
97}
98
Spandan Das2069c3f2023-12-06 19:40:24 +000099type Dexpreopter struct {
100 dexpreopter
101}
102
Colin Cross43f08db2018-11-12 10:13:39 -0800103type dexpreopter struct {
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800104 dexpreoptProperties DexpreoptProperties
105 importDexpreoptProperties ImportDexpreoptProperties
Colin Cross43f08db2018-11-12 10:13:39 -0800106
Spandan Das0727ba72024-02-13 16:37:43 +0000107 // If true, the dexpreopt rules will not be generated
108 // Unlike Dex_preopt.Enabled which is user-facing,
109 // shouldDisableDexpreopt is a mutated propery.
110 shouldDisableDexpreopt bool
111
Colin Cross70dda7e2019-10-01 22:05:35 -0700112 installPath android.InstallPath
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700113 uncompressedDex bool
114 isSDKLibrary bool
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000115 isApp bool
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700116 isTest bool
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700117 isPresignedPrebuilt bool
Colin Crossfa9bfcd2021-11-10 16:42:38 -0800118 preventInstall bool
Colin Cross43f08db2018-11-12 10:13:39 -0800119
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000120 manifestFile android.Path
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000121 statusFile android.WritablePath
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000122 enforceUsesLibs bool
123 classLoaderContexts dexpreopt.ClassLoaderContextMap
Colin Cross50ddcc42019-05-16 12:28:22 -0700124
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000125 // See the `dexpreopt` function for details.
126 builtInstalled string
127 builtInstalledForApex []dexpreopterInstall
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000128
Jeongik Chac6246672021-04-08 00:00:19 +0900129 // The config is used for two purposes:
130 // - Passing dexpreopt information about libraries from Soong to Make. This is needed when
131 // a <uses-library> is defined in Android.bp, but used in Android.mk (see dex_preopt_config_merger.py).
132 // Note that dexpreopt.config might be needed even if dexpreopt is disabled for the library itself.
133 // - Dexpreopt post-processing (using dexpreopt artifacts from a prebuilt system image to incrementally
134 // dexpreopt another partition).
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000135 configPath android.WritablePath
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800136
Jiakai Zhang81e46812023-02-08 21:56:07 +0800137 // The path to the profile on host that dexpreopter generates. This is used as the input for
138 // dex2oat.
139 outputProfilePathOnHost android.Path
140
141 // The path to the profile that dexpreopter accepts. It must be in the binary format. If this is
142 // set, it overrides the profile settings in `dexpreoptProperties`.
143 inputProfilePathOnHost android.Path
Spandan Das3dbda182024-05-20 22:23:10 +0000144
145 // The path to the profile that matches the dex optimized by r8/d8. It is in text format. If this is
146 // set, it will be converted to a binary profile which will be subsequently used for dexpreopt.
147 rewrittenProfile android.Path
Colin Cross43f08db2018-11-12 10:13:39 -0800148}
149
150type DexpreoptProperties struct {
151 Dex_preopt struct {
Nicolas Geoffrayc1bf7242019-10-18 14:51:38 +0100152 // If false, prevent dexpreopting. Defaults to true.
Colin Cross43f08db2018-11-12 10:13:39 -0800153 Enabled *bool
154
155 // If true, generate an app image (.art file) for this module.
156 App_image *bool
157
158 // If true, use a checked-in profile to guide optimization. Defaults to false unless
159 // a matching profile is set or a profile is found in PRODUCT_DEX_PREOPT_PROFILE_DIR
160 // that matches the name of this module, in which case it is defaulted to true.
161 Profile_guided *bool
162
163 // If set, provides the path to profile relative to the Android.bp file. If not set,
164 // defaults to searching for a file that matches the name of this module in the default
165 // profile location set by PRODUCT_DEX_PREOPT_PROFILE_DIR, or empty if not found.
Colin Crossde4e4e62019-04-26 10:52:32 -0700166 Profile *string `android:"path"`
Spandan Das3dbda182024-05-20 22:23:10 +0000167
168 // If set to true, r8/d8 will use `profile` as input to generate a new profile that matches
169 // the optimized dex.
170 // The new profile will be subsequently used as the profile to dexpreopt the dex file.
171 Enable_profile_rewriting *bool
Colin Cross43f08db2018-11-12 10:13:39 -0800172 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800173
174 Dex_preopt_result struct {
175 // True if profile-guided optimization is actually enabled.
176 Profile_guided bool
177 } `blueprint:"mutated"`
178}
179
180type ImportDexpreoptProperties struct {
181 Dex_preopt struct {
182 // If true, use the profile in the prebuilt APEX to guide optimization. Defaults to false.
183 Profile_guided *bool
184 }
Colin Cross43f08db2018-11-12 10:13:39 -0800185}
186
Ulya Trafimovich6cf2c0c2020-04-24 12:15:20 +0100187func init() {
188 dexpreopt.DexpreoptRunningInSoong = true
189}
190
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000191func isApexVariant(ctx android.BaseModuleContext) bool {
Colin Crossff694a82023-12-13 15:54:49 -0800192 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000193 return !apexInfo.IsForPlatform()
194}
195
Jiakai Zhang28bc9a82021-12-20 15:08:57 +0000196func forPrebuiltApex(ctx android.BaseModuleContext) bool {
Colin Crossff694a82023-12-13 15:54:49 -0800197 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jiakai Zhang28bc9a82021-12-20 15:08:57 +0000198 return apexInfo.ForPrebuiltApex
199}
200
Spandan Dasa8afdcb2024-02-29 06:40:16 +0000201// For apex variant of modules, this returns true on the source variant if the prebuilt apex
202// has been selected using apex_contributions.
203// The prebuilt apex will be responsible for generating the dexpreopt rules of the deapexed java lib.
204func disableSourceApexVariant(ctx android.BaseModuleContext) bool {
205 if !isApexVariant(ctx) {
206 return false // platform variant
207 }
208 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
209 psi := android.PrebuiltSelectionInfoMap{}
Jihoon Kanga3a05462024-04-05 00:36:44 +0000210 ctx.VisitDirectDeps(func(am android.Module) {
211 if prebuiltSelectionInfo, ok := android.OtherModuleProvider(ctx, am, android.PrebuiltSelectionInfoProvider); ok {
212 psi = prebuiltSelectionInfo
213 }
Spandan Dasa8afdcb2024-02-29 06:40:16 +0000214 })
215 // Find the apex variant for this module
216 _, apexVariantsWithoutTestApexes, _ := android.ListSetDifference(apexInfo.InApexVariants, apexInfo.TestApexes)
217 disableSource := false
218 // find the selected apexes
219 for _, apexVariant := range apexVariantsWithoutTestApexes {
220 for _, selected := range psi.GetSelectedModulesForApiDomain(apexVariant) {
221 // If the apex_contribution for this api domain contains a prebuilt apex, disable the source variant
222 if strings.HasPrefix(selected, "prebuilt_com.google.android") {
223 disableSource = true
224 }
225 }
226 }
227 return disableSource
228}
229
Jiakai Zhangcf61e3c2023-05-08 16:28:38 +0000230// Returns whether dexpreopt is applicable to the module.
231// When it returns true, neither profile nor dexpreopt artifacts will be generated.
Spandan Dase21a8d42024-01-23 23:56:29 +0000232func (d *dexpreopter) dexpreoptDisabled(ctx android.BaseModuleContext, libName string) bool {
Colin Cross38310bb2021-12-01 10:34:14 -0800233 if !ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -0800234 return true
235 }
236
Colin Cross43f08db2018-11-12 10:13:39 -0800237 if d.isTest {
238 return true
239 }
240
241 if !BoolDefault(d.dexpreoptProperties.Dex_preopt.Enabled, true) {
242 return true
243 }
244
Spandan Das0727ba72024-02-13 16:37:43 +0000245 if d.shouldDisableDexpreopt {
246 return true
247 }
248
Jiakai Zhang28bc9a82021-12-20 15:08:57 +0000249 // If the module is from a prebuilt APEX, it shouldn't be installable, but it can still be
250 // dexpreopted.
251 if !ctx.Module().(DexpreopterInterface).IsInstallable() && !forPrebuiltApex(ctx) {
Martin Stjernholm6d415272020-01-31 17:10:36 +0000252 return true
253 }
254
Colin Cross38310bb2021-12-01 10:34:14 -0800255 if !android.IsModulePreferred(ctx.Module()) {
256 return true
257 }
258
Spandan Dase21a8d42024-01-23 23:56:29 +0000259 if _, isApex := android.ModuleProvider(ctx, android.ApexBundleInfoProvider); isApex {
260 // dexpreopt rules for system server jars can be generated in the ModuleCtx of prebuilt apexes
261 return false
262 }
263
Colin Cross38310bb2021-12-01 10:34:14 -0800264 global := dexpreopt.GetGlobalConfig(ctx)
265
Spandan Dase21a8d42024-01-23 23:56:29 +0000266 // Use the libName argument to determine if the library being dexpreopt'd is a system server jar
267 // ctx.ModuleName() is not safe. In case of prebuilt apexes, the dexpreopt rules of system server jars
268 // are created in the ctx object of the top-level prebuilt apex.
269 isApexSystemServerJar := global.AllApexSystemServerJars(ctx).ContainsJar(libName)
270
271 if _, isApex := android.ModuleProvider(ctx, android.ApexBundleInfoProvider); isApex || isApexVariant(ctx) {
272 // dexpreopt rules for system server jars can be generated in the ModuleCtx of prebuilt apexes
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800273 if !isApexSystemServerJar {
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000274 return true
275 }
Spandan Das50801e22024-05-13 18:29:45 +0000276 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
277 allApexInfos := []android.ApexInfo{}
278 if allApexInfosProvider, ok := android.ModuleProvider(ctx, android.AllApexInfoProvider); ok {
279 allApexInfos = allApexInfosProvider.ApexInfos
280 }
281 if len(allApexInfos) > 0 && !ai.MinSdkVersion.EqualTo(allApexInfos[0].MinSdkVersion) {
282 // Apex system server jars are dexpreopted and installed on to the system image.
283 // Since we can have BigAndroid and Go variants of system server jar providing apexes,
284 // and these two variants can have different min_sdk_versions, hide one of the apex variants
285 // from make to prevent collisions.
286 //
287 // Unlike cc, min_sdk_version does not have an effect on the build actions of java libraries.
288 ctx.Module().MakeUninstallable()
289 }
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000290 } else {
291 // Don't preopt the platform variant of an APEX system server jar to avoid conflicts.
Jiakai Zhang389a6472021-12-14 18:54:06 +0000292 if isApexSystemServerJar {
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000293 return true
294 }
Yo Chiangdbdf8f92020-01-09 19:00:27 +0800295 }
296
Colin Cross43f08db2018-11-12 10:13:39 -0800297 // TODO: contains no java code
298
299 return false
300}
301
Martin Stjernholm6d415272020-01-31 17:10:36 +0000302func dexpreoptToolDepsMutator(ctx android.BottomUpMutatorContext) {
Spandan Dase21a8d42024-01-23 23:56:29 +0000303 if _, isApex := android.ModuleProvider(ctx, android.ApexBundleInfoProvider); isApex && dexpreopt.IsDex2oatNeeded(ctx) {
304 // prebuilt apexes can genererate rules to dexpreopt deapexed jars
305 // Add a dex2oat dep aggressively on _every_ apex module
306 dexpreopt.RegisterToolDeps(ctx)
307 return
308 }
309 if d, ok := ctx.Module().(DexpreopterInterface); !ok || d.dexpreoptDisabled(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName())) || !dexpreopt.IsDex2oatNeeded(ctx) {
Martin Stjernholm6d415272020-01-31 17:10:36 +0000310 return
311 }
312 dexpreopt.RegisterToolDeps(ctx)
313}
314
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000315// Returns the install path of the dex jar of a module.
316//
317// Do not rely on `ApexInfo.ApexVariationName` because it can be something like "apex1000", rather
318// than the `name` in the path `/apex/<name>` as suggested in its comment.
319//
320// This function is on a best-effort basis. It cannot handle the case where an APEX jar is not a
321// system server jar, which is fine because we currently only preopt system server jars for APEXes.
322func (d *dexpreopter) getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +0000323 ctx android.ModuleContext, libName string, defaultInstallPath android.InstallPath) android.InstallPath {
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000324 global := dexpreopt.GetGlobalConfig(ctx)
Spandan Dase21a8d42024-01-23 23:56:29 +0000325 if global.AllApexSystemServerJars(ctx).ContainsJar(libName) {
326 dexLocation := dexpreopt.GetSystemServerDexLocation(ctx, global, libName)
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000327 return android.PathForModuleInPartitionInstall(ctx, "", strings.TrimPrefix(dexLocation, "/"))
328 }
Spandan Dase21a8d42024-01-23 23:56:29 +0000329 if !d.dexpreoptDisabled(ctx, libName) && isApexVariant(ctx) &&
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000330 filepath.Base(defaultInstallPath.PartitionDir()) != "apex" {
331 ctx.ModuleErrorf("unable to get the install path of the dex jar for dexpreopt")
332 }
333 return defaultInstallPath
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000334}
335
Spandan Das2069c3f2023-12-06 19:40:24 +0000336// DexpreoptPrebuiltApexSystemServerJars generates the dexpreopt artifacts from a jar file that has been deapexed from a prebuilt apex
337func (d *Dexpreopter) DexpreoptPrebuiltApexSystemServerJars(ctx android.ModuleContext, libraryName string, di *android.DeapexerInfo) {
338 // A single prebuilt apex can have multiple apex system jars
339 // initialize the output path for this dex jar
340 dc := dexpreopt.GetGlobalConfig(ctx)
341 d.installPath = android.PathForModuleInPartitionInstall(ctx, "", strings.TrimPrefix(dexpreopt.GetSystemServerDexLocation(ctx, dc, libraryName), "/"))
342 // generate the rules for creating the .odex and .vdex files for this system server jar
Spandan Das5be63332023-12-13 00:06:32 +0000343 dexJarFile := di.PrebuiltExportPath(ApexRootRelativePathToJavaLib(libraryName))
Spandan Das2ea84dd2024-01-25 22:12:50 +0000344
345 d.inputProfilePathOnHost = nil // reset: TODO(spandandas): Make dexpreopter stateless
346 if android.InList(libraryName, di.GetDexpreoptProfileGuidedExportedModuleNames()) {
347 // Set the profile path to guide optimization
348 prof := di.PrebuiltExportPath(ApexRootRelativePathToJavaLib(libraryName) + ".prof")
349 if prof == nil {
350 ctx.ModuleErrorf("Could not find a .prof file in this prebuilt apex")
351 }
352 d.inputProfilePathOnHost = prof
353 }
354
Spandan Dase21a8d42024-01-23 23:56:29 +0000355 d.dexpreopt(ctx, libraryName, dexJarFile)
Spandan Das2069c3f2023-12-06 19:40:24 +0000356}
357
Spandan Dase21a8d42024-01-23 23:56:29 +0000358func (d *dexpreopter) dexpreopt(ctx android.ModuleContext, libName string, dexJarFile android.WritablePath) {
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000359 global := dexpreopt.GetGlobalConfig(ctx)
360
Martin Stjernholm6d415272020-01-31 17:10:36 +0000361 // TODO(b/148690468): The check on d.installPath is to bail out in cases where
362 // the dexpreopter struct hasn't been fully initialized before we're called,
363 // e.g. in aar.go. This keeps the behaviour that dexpreopting is effectively
364 // disabled, even if installable is true.
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000365 if d.installPath.Base() == "." {
366 return
367 }
368
369 dexLocation := android.InstallPathToOnDevicePath(ctx, d.installPath)
370
Spandan Dase21a8d42024-01-23 23:56:29 +0000371 providesUsesLib := libName
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000372 if ulib, ok := ctx.Module().(ProvidesUsesLib); ok {
373 name := ulib.ProvidesUsesLib()
374 if name != nil {
375 providesUsesLib = *name
376 }
377 }
378
Jeongik Cha4b073cd2021-06-08 11:35:00 +0900379 // If it is test, make config files regardless of its dexpreopt setting.
Jeongik Chac6246672021-04-08 00:00:19 +0900380 // The config files are required for apps defined in make which depend on the lib.
Spandan Dase21a8d42024-01-23 23:56:29 +0000381 if d.isTest && d.dexpreoptDisabled(ctx, libName) {
Jaewoong Jung4b97a562020-12-17 09:43:28 -0800382 return
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000383 }
384
Spandan Dase21a8d42024-01-23 23:56:29 +0000385 isSystemServerJar := global.AllSystemServerJars(ctx).ContainsJar(libName)
Ulya Trafimovich9023b022021-03-22 16:02:28 +0000386
Colin Cross44df5812019-02-15 23:06:46 -0800387 bootImage := defaultBootImageConfig(ctx)
Jiakai Zhangb8796202023-03-06 19:16:48 +0000388 // When `global.PreoptWithUpdatableBcp` is true, `bcpForDexpreopt` below includes the mainline
389 // boot jars into bootclasspath, so we should include the mainline boot image as well because it's
390 // generated from those jars.
391 if global.PreoptWithUpdatableBcp {
392 bootImage = mainlineBootImageConfig(ctx)
393 }
Jiakai Zhang02669e82021-09-11 03:44:06 +0000394 dexFiles, dexLocations := bcpForDexpreopt(ctx, global.PreoptWithUpdatableBcp)
Ulya Trafimovich9023b022021-03-22 16:02:28 +0000395
David Srbeckyc177ebe2020-02-18 20:43:06 +0000396 targets := ctx.MultiTargets()
397 if len(targets) == 0 {
Colin Cross43f08db2018-11-12 10:13:39 -0800398 // assume this is a java library, dexpreopt for all arches for now
399 for _, target := range ctx.Config().Targets[android.Android] {
dimitry1f33e402019-03-26 12:39:31 +0100400 if target.NativeBridge == android.NativeBridgeDisabled {
David Srbeckyc177ebe2020-02-18 20:43:06 +0000401 targets = append(targets, target)
dimitry1f33e402019-03-26 12:39:31 +0100402 }
Colin Cross43f08db2018-11-12 10:13:39 -0800403 }
Spandan Dase21a8d42024-01-23 23:56:29 +0000404 if isSystemServerJar && libName != "com.android.location.provider" {
Jiakai Zhang2fbc3552022-11-28 15:38:23 +0000405 // If the module is a system server jar, only preopt for the primary arch because the jar can
406 // only be loaded by system server. "com.android.location.provider" is a special case because
407 // it's also used by apps as a shared library.
David Srbeckyc177ebe2020-02-18 20:43:06 +0000408 targets = targets[:1]
Colin Cross43f08db2018-11-12 10:13:39 -0800409 }
410 }
Colin Cross43f08db2018-11-12 10:13:39 -0800411
David Srbeckyc177ebe2020-02-18 20:43:06 +0000412 var archs []android.ArchType
Colin Cross69f59a32019-02-15 10:39:37 -0800413 var images android.Paths
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000414 var imagesDeps []android.OutputPaths
David Srbeckyc177ebe2020-02-18 20:43:06 +0000415 for _, target := range targets {
416 archs = append(archs, target.Arch.ArchType)
417 variant := bootImage.getVariant(target)
Jeongik Chaa5969092021-05-07 18:53:21 +0900418 images = append(images, variant.imagePathOnHost)
David Srbeckyc177ebe2020-02-18 20:43:06 +0000419 imagesDeps = append(imagesDeps, variant.imagesDeps)
Colin Crossc7e40aa2019-02-08 21:37:00 -0800420 }
David Srbeckyab994982020-03-30 17:24:13 +0100421 // The image locations for all Android variants are identical.
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900422 hostImageLocations, deviceImageLocations := bootImage.getAnyAndroidVariant().imageLocations()
Colin Crossc7e40aa2019-02-08 21:37:00 -0800423
Colin Cross43f08db2018-11-12 10:13:39 -0800424 var profileClassListing android.OptionalPath
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100425 var profileBootListing android.OptionalPath
Colin Cross43f08db2018-11-12 10:13:39 -0800426 profileIsTextListing := false
Spandan Das2ea84dd2024-01-25 22:12:50 +0000427
Jiakai Zhang81e46812023-02-08 21:56:07 +0800428 if d.inputProfilePathOnHost != nil {
429 profileClassListing = android.OptionalPathForPath(d.inputProfilePathOnHost)
430 } else if BoolDefault(d.dexpreoptProperties.Dex_preopt.Profile_guided, true) && !forPrebuiltApex(ctx) {
Spandan Das3dbda182024-05-20 22:23:10 +0000431 // If enable_profile_rewriting is set, use the rewritten profile instead of the checked-in profile
432 if d.EnableProfileRewriting() {
433 profileClassListing = android.OptionalPathForPath(d.GetRewrittenProfile())
434 profileIsTextListing = true
435 } else if profile := d.GetProfile(); profile != "" {
436 // If dex_preopt.profile_guided is not set, default it based on the existence of the
437 // dexprepot.profile option or the profile class listing.
Colin Cross43f08db2018-11-12 10:13:39 -0800438 profileClassListing = android.OptionalPathForPath(
Spandan Das3dbda182024-05-20 22:23:10 +0000439 android.PathForModuleSrc(ctx, profile))
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100440 profileBootListing = android.ExistentPathForSource(ctx,
Spandan Das3dbda182024-05-20 22:23:10 +0000441 ctx.ModuleDir(), profile+"-boot")
Colin Cross43f08db2018-11-12 10:13:39 -0800442 profileIsTextListing = true
Dan Willemsen78d51b02020-06-24 16:33:31 -0700443 } else if global.ProfileDir != "" {
Colin Cross43f08db2018-11-12 10:13:39 -0800444 profileClassListing = android.ExistentPathForSource(ctx,
Spandan Dase21a8d42024-01-23 23:56:29 +0000445 global.ProfileDir, libName+".prof")
Colin Cross43f08db2018-11-12 10:13:39 -0800446 }
447 }
448
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800449 d.dexpreoptProperties.Dex_preopt_result.Profile_guided = profileClassListing.Valid()
450
Spandan Das2069c3f2023-12-06 19:40:24 +0000451 // A single apex can have multiple system server jars
452 // Use the dexJar to create a unique scope for each
453 dexJarStem := strings.TrimSuffix(dexJarFile.Base(), dexJarFile.Ext())
454
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000455 // Full dexpreopt config, used to create dexpreopt build rules.
Martin Stjernholm8d80cee2020-01-31 17:44:54 +0000456 dexpreoptConfig := &dexpreopt.ModuleConfig{
Spandan Dase21a8d42024-01-23 23:56:29 +0000457 Name: libName,
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800458 DexLocation: dexLocation,
Spandan Dase21a8d42024-01-23 23:56:29 +0000459 BuildPath: android.PathForModuleOut(ctx, "dexpreopt", dexJarStem, libName+".jar").OutputPath,
Colin Cross69f59a32019-02-15 10:39:37 -0800460 DexPath: dexJarFile,
Jeongik Cha33a3a812021-04-15 09:12:49 +0900461 ManifestPath: android.OptionalPathForPath(d.manifestFile),
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800462 UncompressedDex: d.uncompressedDex,
463 HasApkLibraries: false,
464 PreoptFlags: nil,
Colin Cross43f08db2018-11-12 10:13:39 -0800465
Colin Cross69f59a32019-02-15 10:39:37 -0800466 ProfileClassListing: profileClassListing,
Colin Cross43f08db2018-11-12 10:13:39 -0800467 ProfileIsTextListing: profileIsTextListing,
Nicolas Geoffraye7102422019-07-24 13:19:29 +0100468 ProfileBootListing: profileBootListing,
Colin Cross43f08db2018-11-12 10:13:39 -0800469
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000470 EnforceUsesLibrariesStatusFile: dexpreopt.UsesLibrariesStatusFile(ctx),
471 EnforceUsesLibraries: d.enforceUsesLibs,
472 ProvidesUsesLibrary: providesUsesLib,
473 ClassLoaderContexts: d.classLoaderContexts,
Colin Cross43f08db2018-11-12 10:13:39 -0800474
Jeongik Cha4dda75e2021-04-27 23:56:44 +0900475 Archs: archs,
476 DexPreoptImagesDeps: imagesDeps,
477 DexPreoptImageLocationsOnHost: hostImageLocations,
478 DexPreoptImageLocationsOnDevice: deviceImageLocations,
Colin Cross43f08db2018-11-12 10:13:39 -0800479
Ulya Trafimovich9023b022021-03-22 16:02:28 +0000480 PreoptBootClassPathDexFiles: dexFiles.Paths(),
Vladimir Marko40139d62020-02-06 15:14:29 +0000481 PreoptBootClassPathDexLocations: dexLocations,
Colin Cross800fe132019-02-11 14:21:24 -0800482
Colin Cross43f08db2018-11-12 10:13:39 -0800483 NoCreateAppImage: !BoolDefault(d.dexpreoptProperties.Dex_preopt.App_image, true),
484 ForceCreateAppImage: BoolDefault(d.dexpreoptProperties.Dex_preopt.App_image, false),
485
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700486 PresignedPrebuilt: d.isPresignedPrebuilt,
Colin Cross43f08db2018-11-12 10:13:39 -0800487 }
488
Spandan Das2069c3f2023-12-06 19:40:24 +0000489 d.configPath = android.PathForModuleOut(ctx, "dexpreopt", dexJarStem, "dexpreopt.config")
Jeongik Chac6246672021-04-08 00:00:19 +0900490 dexpreopt.WriteModuleConfig(ctx, dexpreoptConfig, d.configPath)
491
Spandan Dase21a8d42024-01-23 23:56:29 +0000492 if d.dexpreoptDisabled(ctx, libName) {
Jeongik Chac6246672021-04-08 00:00:19 +0900493 return
494 }
495
496 globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
497
Jiakai Zhang51b2a8b2023-06-26 16:47:38 +0100498 // The root "product_packages.txt" is generated by `build/make/core/Makefile`. It contains a list
499 // of all packages that are installed on the device. We use `grep` to filter the list by the app's
500 // dependencies to create a per-app list, and use `rsync --checksum` to prevent the file's mtime
501 // from being changed if the contents don't change. This avoids unnecessary dexpreopt reruns.
Jiakai Zhanga4496782023-05-17 16:57:30 +0100502 productPackages := android.PathForModuleInPartitionInstall(ctx, "", "product_packages.txt")
Spandan Das2069c3f2023-12-06 19:40:24 +0000503 appProductPackages := android.PathForModuleOut(ctx, "dexpreopt", dexJarStem, "product_packages.txt")
Jiakai Zhang51b2a8b2023-06-26 16:47:38 +0100504 appProductPackagesStaging := appProductPackages.ReplaceExtension(ctx, "txt.tmp")
505 clcNames, _ := dexpreopt.ComputeClassLoaderContextDependencies(dexpreoptConfig.ClassLoaderContexts)
506 sort.Strings(clcNames) // The order needs to be deterministic.
507 productPackagesRule := android.NewRuleBuilder(pctx, ctx)
508 if len(clcNames) > 0 {
509 productPackagesRule.Command().
510 Text("grep -F -x").
511 FlagForEachArg("-e ", clcNames).
512 Input(productPackages).
513 FlagWithOutput("> ", appProductPackagesStaging).
514 Text("|| true")
515 } else {
516 productPackagesRule.Command().
517 Text("rm -f").Output(appProductPackagesStaging).
518 Text("&&").
519 Text("touch").Output(appProductPackagesStaging)
520 }
521 productPackagesRule.Command().
522 Text("rsync --checksum").
523 Input(appProductPackagesStaging).
524 Output(appProductPackages)
Spandan Das2069c3f2023-12-06 19:40:24 +0000525 productPackagesRule.Restat().Build("product_packages."+dexJarStem, "dexpreopt product_packages")
Jiakai Zhanga4496782023-05-17 16:57:30 +0100526
Spandan Das5ae65ee2024-04-16 22:03:26 +0000527 // Prebuilts are active, do not copy the dexpreopt'd source javalib to out/soong/system_server_dexjars
528 // The javalib from the deapexed prebuilt will be copied to this location.
529 // TODO (b/331665856): Implement a principled solution for this.
Spandan Das50801e22024-05-13 18:29:45 +0000530 copyApexSystemServerJarDex := !disableSourceApexVariant(ctx) && !ctx.Module().IsHideFromMake()
Jiakai Zhanga4496782023-05-17 16:57:30 +0100531 dexpreoptRule, err := dexpreopt.GenerateDexpreoptRule(
Spandan Das5ae65ee2024-04-16 22:03:26 +0000532 ctx, globalSoong, global, dexpreoptConfig, appProductPackages, copyApexSystemServerJarDex)
Colin Cross43f08db2018-11-12 10:13:39 -0800533 if err != nil {
534 ctx.ModuleErrorf("error generating dexpreopt rule: %s", err.Error())
Jaewoong Jung4b97a562020-12-17 09:43:28 -0800535 return
Colin Cross43f08db2018-11-12 10:13:39 -0800536 }
537
Spandan Das2069c3f2023-12-06 19:40:24 +0000538 dexpreoptRule.Build("dexpreopt"+"."+dexJarStem, "dexpreopt")
Colin Cross43f08db2018-11-12 10:13:39 -0800539
Spandan Das2069c3f2023-12-06 19:40:24 +0000540 // The current ctx might be of a deapexer module created by a prebuilt apex
541 // Use the path of the dex file to determine the library name
542 isApexSystemServerJar := global.AllApexSystemServerJars(ctx).ContainsJar(dexJarStem)
Jiakai Zhang389a6472021-12-14 18:54:06 +0000543
Justin Yun22c8aca2024-06-05 20:25:03 +0900544 partition := d.installPath.Partition()
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700545 for _, install := range dexpreoptRule.Installs() {
546 // Remove the "/" prefix because the path should be relative to $ANDROID_PRODUCT_OUT.
547 installDir := strings.TrimPrefix(filepath.Dir(install.To), "/")
Justin Yun22c8aca2024-06-05 20:25:03 +0900548 if strings.HasPrefix(installDir, partition+"/") {
549 installDir = strings.TrimPrefix(installDir, partition+"/")
550 } else {
551 // If the partition for the installDir is different from the install partition, set the
552 // partition empty to install the dexpreopt files to the desired partition.
553 // TODO(b/346439786): Define and use the dexpreopt module type to avoid this mismatch.
554 partition = ""
555 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700556 installBase := filepath.Base(install.To)
557 arch := filepath.Base(installDir)
Justin Yun22c8aca2024-06-05 20:25:03 +0900558 installPath := android.PathForModuleInPartitionInstall(ctx, partition, installDir)
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800559 isProfile := strings.HasSuffix(installBase, ".prof")
560
561 if isProfile {
Jiakai Zhang81e46812023-02-08 21:56:07 +0800562 d.outputProfilePathOnHost = install.From
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800563 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700564
Jiakai Zhang389a6472021-12-14 18:54:06 +0000565 if isApexSystemServerJar {
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800566 // Profiles are handled separately because they are installed into the APEX.
567 if !isProfile {
568 // APEX variants of java libraries are hidden from Make, so their dexpreopt
569 // outputs need special handling. Currently, for APEX variants of java
570 // libraries, only those in the system server classpath are handled here.
571 // Preopting of boot classpath jars in the ART APEX are handled in
572 // java/dexpreopt_bootjars.go, and other APEX jars are not preopted.
573 // The installs will be handled by Make as sub-modules of the java library.
574 d.builtInstalledForApex = append(d.builtInstalledForApex, dexpreopterInstall{
575 name: arch + "-" + installBase,
Spandan Dase21a8d42024-01-23 23:56:29 +0000576 moduleName: libName,
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800577 outputPathOnHost: install.From,
578 installDirOnDevice: installPath,
579 installFileOnDevice: installBase,
580 })
581 }
Colin Crossfa9bfcd2021-11-10 16:42:38 -0800582 } else if !d.preventInstall {
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700583 ctx.InstallFile(installPath, installBase, install.From)
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000584 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700585 }
586
Jiakai Zhang389a6472021-12-14 18:54:06 +0000587 if !isApexSystemServerJar {
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000588 d.builtInstalled = dexpreoptRule.Installs().String()
589 }
590}
591
Justin Yun22c8aca2024-06-05 20:25:03 +0900592func getModuleInstallPathInfo(ctx android.ModuleContext, fullInstallPath string) (android.InstallPath, string, string) {
593 installPath := android.PathForModuleInstall(ctx)
594 installDir, installBase := filepath.Split(strings.TrimPrefix(fullInstallPath, "/"))
595
596 if !strings.HasPrefix(installDir, installPath.Partition()+"/") {
597 // Return empty filename if the install partition is not for the target image.
598 return installPath, "", ""
599 }
600 relDir, err := filepath.Rel(installPath.Partition(), installDir)
601 if err != nil {
602 panic(err)
603 }
604 return installPath, relDir, installBase
605}
606
607// RuleBuilder.Install() adds output-to-install copy pairs to a list for Make. To share this
608// information with PackagingSpec in soong, call PackageFile for them.
609// The install path and the target install partition of the module must be the same.
610func packageFile(ctx android.ModuleContext, install android.RuleBuilderInstall) {
611 installPath, relDir, name := getModuleInstallPathInfo(ctx, install.To)
612 // Empty name means the install partition is not for the target image.
613 // For the system image, files for "apex" and "system_other" are skipped here.
614 // The skipped "apex" files are for testing only, for example,
615 // "/apex/art_boot_images/javalib/x86/boot.vdex".
616 // TODO(b/320196894): Files for "system_other" are skipped because soong creates the system
617 // image only for now.
618 if name != "" {
619 ctx.PackageFile(installPath.Join(ctx, relDir), name, install.From)
620 }
621}
622
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000623func (d *dexpreopter) DexpreoptBuiltInstalledForApex() []dexpreopterInstall {
624 return d.builtInstalledForApex
625}
626
627func (d *dexpreopter) AndroidMkEntriesForApex() []android.AndroidMkEntries {
628 var entries []android.AndroidMkEntries
629 for _, install := range d.builtInstalledForApex {
Jiakai Zhang6decef92022-01-12 17:56:19 +0000630 entries = append(entries, install.ToMakeEntries())
Jiakai Zhangca9bc982021-09-09 08:09:41 +0000631 }
632 return entries
Colin Cross43f08db2018-11-12 10:13:39 -0800633}
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800634
Jiakai Zhang81e46812023-02-08 21:56:07 +0800635func (d *dexpreopter) OutputProfilePathOnHost() android.Path {
636 return d.outputProfilePathOnHost
Jiakai Zhang3317ce72023-02-08 01:19:19 +0800637}
Spandan Das0727ba72024-02-13 16:37:43 +0000638
639func (d *dexpreopter) disableDexpreopt() {
640 d.shouldDisableDexpreopt = true
641}
Spandan Das3dbda182024-05-20 22:23:10 +0000642
643func (d *dexpreopter) EnableProfileRewriting() bool {
644 return proptools.Bool(d.dexpreoptProperties.Dex_preopt.Enable_profile_rewriting)
645}
646
647func (d *dexpreopter) GetProfile() string {
648 return proptools.String(d.dexpreoptProperties.Dex_preopt.Profile)
649}
650
651func (d *dexpreopter) GetProfileGuided() bool {
652 return proptools.Bool(d.dexpreoptProperties.Dex_preopt.Profile_guided)
653}
654
655func (d *dexpreopter) GetRewrittenProfile() android.Path {
656 return d.rewrittenProfile
657}
658
659func (d *dexpreopter) SetRewrittenProfile(p android.Path) {
660 d.rewrittenProfile = p
661}