blob: 308a48cac2e834ceda2575075b60d426424499f8 [file] [log] [blame]
Colin Crossfabb6082018-02-20 17:22:23 -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 (
Colin Crossa592e3e2019-02-19 16:59:53 -080018 "fmt"
Jaewoong Jung5b425e22019-06-17 17:40:56 -070019 "path/filepath"
Colin Crossc20dc852020-11-10 12:27:45 -080020 "strconv"
Colin Crossa97c5d32018-03-28 14:58:31 -070021 "strings"
Colin Crossfabb6082018-02-20 17:22:23 -080022
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080023 "android/soong/android"
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -050024 "android/soong/bazel"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010025 "android/soong/dexpreopt"
Romain Jobredeaux7a71e072023-08-16 17:39:12 -040026 "android/soong/ui/metrics/bp2build_metrics_proto"
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080027
Colin Crossfabb6082018-02-20 17:22:23 -080028 "github.com/google/blueprint"
Colin Crossa97c5d32018-03-28 14:58:31 -070029 "github.com/google/blueprint/proptools"
Colin Crossfabb6082018-02-20 17:22:23 -080030)
31
Colin Crossa97c5d32018-03-28 14:58:31 -070032type AndroidLibraryDependency interface {
Jared Duke5979b302022-12-19 21:08:39 +000033 LibraryDependency
Colin Crossa97c5d32018-03-28 14:58:31 -070034 ExportPackage() android.Path
Colin Crossab8d1382023-07-14 17:23:41 +000035 ResourcesNodeDepSet() *android.DepSet[*resourcesNode]
36 RRODirsDepSet() *android.DepSet[rroDir]
37 ManifestsDepSet() *android.DepSet[android.Path]
Jaewoong Jungc779cd42020-10-06 18:56:10 -070038 SetRROEnforcedForDependent(enforce bool)
39 IsRROEnforced(ctx android.BaseModuleContext) bool
Colin Crossa97c5d32018-03-28 14:58:31 -070040}
41
42func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000043 RegisterAARBuildComponents(android.InitRegistrationContext)
44}
45
46func RegisterAARBuildComponents(ctx android.RegistrationContext) {
47 ctx.RegisterModuleType("android_library_import", AARImportFactory)
48 ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
Paul Duffin04ba70d2021-03-22 13:56:43 +000049 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
50 ctx.TopDown("propagate_rro_enforcement", propagateRROEnforcementMutator).Parallel()
51 })
Colin Crossa97c5d32018-03-28 14:58:31 -070052}
53
54//
55// AAR (android library)
56//
57
58type androidLibraryProperties struct {
59 BuildAAR bool `blueprint:"mutated"`
60}
61
62type aaptProperties struct {
63 // flags passed to aapt when creating the apk
64 Aaptflags []string
65
Dan Willemsen72be5902018-10-24 20:24:57 -070066 // include all resource configurations, not just the product-configured
67 // ones.
68 Aapt_include_all_resources *bool
69
Colin Crossa97c5d32018-03-28 14:58:31 -070070 // list of directories relative to the Blueprints file containing assets.
Colin Cross0ddae7f2019-02-07 15:30:01 -080071 // Defaults to ["assets"] if a directory called assets exists. Set to []
72 // to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070073 Asset_dirs []string
74
75 // list of directories relative to the Blueprints file containing
Colin Cross0ddae7f2019-02-07 15:30:01 -080076 // Android resources. Defaults to ["res"] if a directory called res exists.
77 // Set to [] to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070078 Resource_dirs []string
79
Colin Crossa592e3e2019-02-19 16:59:53 -080080 // list of zip files containing Android resources.
Colin Cross27b922f2019-03-04 22:35:41 -080081 Resource_zips []string `android:"path"`
Colin Crossa592e3e2019-02-19 16:59:53 -080082
Colin Crossa97c5d32018-03-28 14:58:31 -070083 // path to AndroidManifest.xml. If unset, defaults to "AndroidManifest.xml".
Colin Cross27b922f2019-03-04 22:35:41 -080084 Manifest *string `android:"path"`
changho.shinb5432b72019-08-08 18:37:17 +090085
86 // paths to additional manifest files to merge with main manifest.
87 Additional_manifests []string `android:"path"`
Sasha Smundak541056c2019-10-28 15:50:06 -070088
89 // do not include AndroidManifest from dependent libraries
90 Dont_merge_manifests *bool
Jaewoong Jungc779cd42020-10-06 18:56:10 -070091
Colin Cross4eae06d2023-06-20 22:40:02 -070092 // If use_resource_processor is set, use Bazel's resource processor instead of aapt2 to generate R.class files.
93 // The resource processor produces more optimal R.class files that only list resources in the package of the
94 // library that provided them, as opposed to aapt2 which produces R.java files for every package containing
95 // every resource. Using the resource processor can provide significant build time speedups, but requires
96 // fixing the module to use the correct package to reference each resource, and to avoid having any other
97 // libraries in the tree that use the same package name. Defaults to false, but will default to true in the
98 // future.
99 Use_resource_processor *bool
100
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700101 // true if RRO is enforced for any of the dependent modules
102 RROEnforcedForDependent bool `blueprint:"mutated"`
Colin Crossa97c5d32018-03-28 14:58:31 -0700103}
104
105type aapt struct {
Colin Cross4eae06d2023-06-20 22:40:02 -0700106 aaptSrcJar android.Path
107 transitiveAaptRJars android.Paths
108 transitiveAaptResourcePackages android.Paths
109 exportPackage android.Path
110 manifestPath android.Path
111 proguardOptionsFile android.Path
112 rTxt android.Path
113 rJar android.Path
114 extraAaptPackagesFile android.Path
115 mergedManifestFile android.Path
116 noticeFile android.OptionalPath
117 assetPackage android.OptionalPath
118 isLibrary bool
119 defaultManifestVersion string
120 useEmbeddedNativeLibs bool
121 useEmbeddedDex bool
122 usesNonSdkApis bool
123 hasNoCode bool
124 LoggingParent string
125 resourceFiles android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700126
Colin Crosse560c4a2019-03-19 16:03:11 -0700127 splitNames []string
128 splits []split
129
Colin Crossa97c5d32018-03-28 14:58:31 -0700130 aaptProperties aaptProperties
Colin Crossab8d1382023-07-14 17:23:41 +0000131
132 resourcesNodesDepSet *android.DepSet[*resourcesNode]
133 rroDirsDepSet *android.DepSet[rroDir]
134 manifestsDepSet *android.DepSet[android.Path]
Colin Crossa97c5d32018-03-28 14:58:31 -0700135}
136
Colin Crosse560c4a2019-03-19 16:03:11 -0700137type split struct {
138 name string
139 suffix string
140 path android.Path
141}
142
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700143// Propagate RRO enforcement flag to static lib dependencies transitively.
144func propagateRROEnforcementMutator(ctx android.TopDownMutatorContext) {
145 m := ctx.Module()
146 if d, ok := m.(AndroidLibraryDependency); ok && d.IsRROEnforced(ctx) {
147 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
148 if a, ok := d.(AndroidLibraryDependency); ok {
149 a.SetRROEnforcedForDependent(true)
150 }
151 })
152 }
153}
154
Colin Cross4eae06d2023-06-20 22:40:02 -0700155func (a *aapt) useResourceProcessorBusyBox() bool {
156 return BoolDefault(a.aaptProperties.Use_resource_processor, false)
157}
158
Colin Crossa97c5d32018-03-28 14:58:31 -0700159func (a *aapt) ExportPackage() android.Path {
160 return a.exportPackage
161}
Colin Crossab8d1382023-07-14 17:23:41 +0000162func (a *aapt) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
163 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800164}
165
Colin Crossab8d1382023-07-14 17:23:41 +0000166func (a *aapt) RRODirsDepSet() *android.DepSet[rroDir] {
167 return a.rroDirsDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800168}
169
Colin Crossab8d1382023-07-14 17:23:41 +0000170func (a *aapt) ManifestsDepSet() *android.DepSet[android.Path] {
171 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800172}
173
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700174func (a *aapt) SetRROEnforcedForDependent(enforce bool) {
175 a.aaptProperties.RROEnforcedForDependent = enforce
176}
177
178func (a *aapt) IsRROEnforced(ctx android.BaseModuleContext) bool {
179 // True if RRO is enforced for this module or...
180 return ctx.Config().EnforceRROForModule(ctx.ModuleName()) ||
Jeongik Chacee5ba92021-02-19 12:11:51 +0900181 // if RRO is enforced for any of its dependents.
182 a.aaptProperties.RROEnforcedForDependent
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700183}
184
Jiyong Parkf1691d22021-03-29 20:11:58 +0900185func (a *aapt) aapt2Flags(ctx android.ModuleContext, sdkContext android.SdkContext,
Colin Crossa0ba2f52019-06-22 12:59:27 -0700186 manifestPath android.Path) (compileFlags, linkFlags []string, linkDeps android.Paths,
187 resDirs, overlayDirs []globbedResourceDir, rroDirs []rroDir, resZips android.Paths) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700188
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800189 hasVersionCode := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-code")
190 hasVersionName := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-name")
Colin Crossa97c5d32018-03-28 14:58:31 -0700191
Colin Crossa97c5d32018-03-28 14:58:31 -0700192 // Flags specified in Android.bp
193 linkFlags = append(linkFlags, a.aaptProperties.Aaptflags...)
194
Colin Crossa97c5d32018-03-28 14:58:31 -0700195 // Find implicit or explicit asset and resource dirs
196 assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
197 resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
Colin Cross8a497952019-03-05 22:25:09 -0800198 resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
Colin Crossa97c5d32018-03-28 14:58:31 -0700199
Colin Crossa97c5d32018-03-28 14:58:31 -0700200 // Glob directories into lists of paths
201 for _, dir := range resourceDirs {
202 resDirs = append(resDirs, globbedResourceDir{
203 dir: dir,
204 files: androidResourceGlob(ctx, dir),
205 })
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700206 resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
Colin Crossa97c5d32018-03-28 14:58:31 -0700207 overlayDirs = append(overlayDirs, resOverlayDirs...)
208 rroDirs = append(rroDirs, resRRODirs...)
209 }
210
Colin Crossc20dc852020-11-10 12:27:45 -0800211 var assetDeps android.Paths
212 for i, dir := range assetDirs {
213 // Add a dependency on every file in the asset directory. This ensures the aapt2
214 // rule will be rerun if one of the files in the asset directory is modified.
215 assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
216
217 // Add a dependency on a file that contains a list of all the files in the asset directory.
218 // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
219 // or a file is added whose timestamp is older than the output of aapt2.
220 assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
221 androidResourceGlobList(ctx, dir, assetFileListFile)
222 assetDeps = append(assetDeps, assetFileListFile)
Colin Crossa97c5d32018-03-28 14:58:31 -0700223 }
224
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700225 assetDirStrings := assetDirs.Strings()
226 if a.noticeFile.Valid() {
227 assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
Colin Crossc20dc852020-11-10 12:27:45 -0800228 assetDeps = append(assetDeps, a.noticeFile.Path())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700229 }
230
Colin Crossa97c5d32018-03-28 14:58:31 -0700231 linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
232 linkDeps = append(linkDeps, manifestPath)
233
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700234 linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
Colin Crossc20dc852020-11-10 12:27:45 -0800235 linkDeps = append(linkDeps, assetDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700236
Spandan Das50885c02023-02-23 21:31:33 +0000237 // Returns the effective version for {min|target}_sdk_version
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000238 effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
Spandan Das50885c02023-02-23 21:31:33 +0000239 // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
240 // This is necessary for vendor modules.
241 // The effective version does not _only_ depend on {min|target}_sdk_version(level),
242 // but also on the sdk_version (kind+level)
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000243 if minSdkVersion.IsCurrent() {
Spandan Das50885c02023-02-23 21:31:33 +0000244 ret, err := sdkVersion.EffectiveVersionString(ctx)
245 if err != nil {
246 ctx.ModuleErrorf("invalid sdk_version: %s", err)
247 }
248 return ret
249 }
250 ret, err := minSdkVersion.EffectiveVersionString(ctx)
251 if err != nil {
252 ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
253 }
254 return ret
Jiyong Park6a927c42020-01-21 02:03:43 +0900255 }
Spandan Das50885c02023-02-23 21:31:33 +0000256 // SDK version flags
257 sdkVersion := sdkContext.SdkVersion(ctx)
258 minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
Colin Crossa97c5d32018-03-28 14:58:31 -0700259
Colin Cross83bb3162018-06-25 15:48:06 -0700260 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000261 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
262 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700263 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700264
Colin Crossa97c5d32018-03-28 14:58:31 -0700265 // Version code
266 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700267 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700268 }
269
270 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700271 var versionName string
272 if ctx.ModuleName() == "framework-res" {
273 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
274 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700275 // if it contains the build number. Use the PlatformVersionName instead.
276 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700277 } else {
278 versionName = ctx.Config().AppsDefaultVersionName()
279 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800280 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700281 linkFlags = append(linkFlags, "--version-name ", versionName)
282 }
283
Colin Crossa0ba2f52019-06-22 12:59:27 -0700284 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
285
286 // Always set --pseudo-localize, it will be stripped out later for release
287 // builds that don't want it.
288 compileFlags = append(compileFlags, "--pseudo-localize")
289
290 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700291}
292
Paul Duffin250e6192019-06-07 10:44:37 +0100293func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800294 if sdkDep.frameworkResModule != "" {
295 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700296 }
297}
298
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800299var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
300 blueprint.RuleParams{
301 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
302 CommandDeps: []string{"${config.Zip2ZipCmd}"},
303 })
304
Jiyong Parkf1691d22021-03-29 20:11:58 +0900305func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000306 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000307 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700308
Colin Crossab8d1382023-07-14 17:23:41 +0000309 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100310 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100311
Paul Duffin06530572022-02-03 17:54:15 +0000312 // Exclude any libraries from the supplied list.
313 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
314
Colin Cross31656952018-05-24 16:11:20 -0700315 // App manifest file
316 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
317 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
318
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000319 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000320 SdkContext: sdkContext,
321 ClassLoaderContexts: classLoaderContexts,
322 IsLibrary: a.isLibrary,
323 DefaultManifestVersion: a.defaultManifestVersion,
324 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
325 UsesNonSdkApis: a.usesNonSdkApis,
326 UseEmbeddedDex: a.useEmbeddedDex,
327 HasNoCode: a.hasNoCode,
328 LoggingParent: a.LoggingParent,
329 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000330 })
Colin Cross90c25c62019-04-19 16:22:57 -0700331
Colin Crossab8d1382023-07-14 17:23:41 +0000332 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
333
Luca Stefanifd898822019-09-10 22:13:31 +0200334 // Add additional manifest files to transitive manifests.
335 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
Colin Crossab8d1382023-07-14 17:23:41 +0000336 transitiveManifestPaths := append(android.Paths{manifestPath}, additionalManifests...)
337 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
338 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
339 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
340 // android_library_import modules. If this is fixed, staticManifestsDepSet can be dropped completely in favor of
341 // staticResourcesNodesDepSet.manifests()
342 transitiveManifestPaths = append(transitiveManifestPaths, staticManifestsDepSet.ToList()...)
Colin Cross90c25c62019-04-19 16:22:57 -0700343
Colin Crossab8d1382023-07-14 17:23:41 +0000344 if len(transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
345 a.mergedManifestFile = manifestMerger(ctx, transitiveManifestPaths[0], transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700346 if !a.isLibrary {
347 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
348 // will be propagated to the final application and merged there. The merged manifest for libraries is
349 // only passed to Make, which can't handle transitive dependencies.
350 manifestPath = a.mergedManifestFile
351 }
352 } else {
353 a.mergedManifestFile = manifestPath
354 }
Colin Cross31656952018-05-24 16:11:20 -0700355
Colin Crossa0ba2f52019-06-22 12:59:27 -0700356 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700357
358 linkFlags = append(linkFlags, libFlags...)
Colin Crossab8d1382023-07-14 17:23:41 +0000359 linkDeps = append(linkDeps, sharedDeps...)
360 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700361 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700362 if a.isLibrary {
363 linkFlags = append(linkFlags, "--static-lib")
364 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700365
Colin Cross4eae06d2023-06-20 22:40:02 -0700366 if a.isLibrary && a.useResourceProcessorBusyBox() {
367 // When building an android_library using ResourceProcessorBusyBox the resources are merged into
368 // package-res.apk with --merge-only, but --no-static-lib-packages is not used so that R.txt only
369 // contains resources from this library.
370 linkFlags = append(linkFlags, "--merge-only")
371 } else {
372 // When building and app or when building an android_library without ResourceProcessorBusyBox
373 // --no-static-lib-packages is used to put all the resources into the app. If ResourceProcessorBusyBox
374 // is used then the app's R.txt will be post-processed along with the R.txt files from dependencies to
375 // sort resources into the right packages in R.class.
376 linkFlags = append(linkFlags, "--no-static-lib-packages")
377 }
378
Colin Crossa97c5d32018-03-28 14:58:31 -0700379 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossa97c5d32018-03-28 14:58:31 -0700380 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
381 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700382 // This file isn't used by Soong, but is generated for exporting
383 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Cross4eae06d2023-06-20 22:40:02 -0700384 var transitiveRJars android.Paths
Colin Crossf3b7bad2023-08-02 15:49:00 -0700385 var srcJar android.WritablePath
Colin Crossa97c5d32018-03-28 14:58:31 -0700386
Colin Cross4aaa84a2018-08-21 15:14:37 -0700387 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700388 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700389 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700390 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700391 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700392
Colin Crossa592e3e2019-02-19 16:59:53 -0800393 for i, zip := range resZips {
394 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700395 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800396 compiledResDirs = append(compiledResDirs, android.Paths{flata})
397 }
398
Colin Cross4aaa84a2018-08-21 15:14:37 -0700399 var compiledRes, compiledOverlay android.Paths
400
Colin Crossab8d1382023-07-14 17:23:41 +0000401 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
402 // of transitiveStaticLibs.
403 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
404
Colin Cross4eae06d2023-06-20 22:40:02 -0700405 if a.isLibrary && a.useResourceProcessorBusyBox() {
406 // When building an android_library with ResourceProcessorBusyBox enabled treat static library dependencies
407 // as imports. The resources from dependencies will not be merged into this module's package-res.apk, and
408 // instead modules depending on this module will reference package-res.apk from all transitive static
409 // dependencies.
410 for _, staticDep := range staticDeps {
411 linkDeps = append(linkDeps, staticDep.resPackage)
412 linkFlags = append(linkFlags, "-I "+staticDep.resPackage.String())
413 if staticDep.usedResourceProcessor {
414 transitiveRJars = append(transitiveRJars, staticDep.rJar)
415 }
416 }
417 } else {
418 // When building an app or building a library without ResourceProcessorBusyBox enabled all static
419 // dependencies are compiled into this module's package-res.apk as overlays.
420 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
421 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700422
Colin Crossbec85302019-02-13 13:15:46 -0800423 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700424 // If we are using static android libraries, every source file becomes an overlay.
425 // This is to emulate old AAPT behavior which simulated library support.
426 for _, compiledResDir := range compiledResDirs {
427 compiledOverlay = append(compiledOverlay, compiledResDir...)
428 }
Colin Crossbec85302019-02-13 13:15:46 -0800429 } else if a.isLibrary {
430 // Otherwise, for a static library we treat all the resources equally with no overlay.
431 for _, compiledResDir := range compiledResDirs {
432 compiledRes = append(compiledRes, compiledResDir...)
433 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700434 } else if len(compiledResDirs) > 0 {
435 // Without static libraries, the first directory is our directory, which can then be
436 // overlaid by the rest.
437 compiledRes = append(compiledRes, compiledResDirs[0]...)
438 for _, compiledResDir := range compiledResDirs[1:] {
439 compiledOverlay = append(compiledOverlay, compiledResDir...)
440 }
441 }
442
Colin Crossa97c5d32018-03-28 14:58:31 -0700443 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700444 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700445 }
446
Colin Crosse560c4a2019-03-19 16:03:11 -0700447 var splitPackages android.WritablePaths
448 var splits []split
449
450 for _, s := range a.splitNames {
451 suffix := strings.Replace(s, ",", "_", -1)
452 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
453 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
454 splitPackages = append(splitPackages, path)
455 splits = append(splits, split{
456 name: s,
457 suffix: suffix,
458 path: path,
459 })
460 }
461
Colin Crossf3b7bad2023-08-02 15:49:00 -0700462 if !a.useResourceProcessorBusyBox() {
463 // the subdir "android" is required to be filtered by package names
464 srcJar = android.PathForModuleGen(ctx, "android", "R.srcjar")
465 }
466
Colin Crossab8d1382023-07-14 17:23:41 +0000467 // No need to specify assets from dependencies to aapt2Link for libraries, all transitive assets will be
468 // provided to the final app aapt2Link step.
469 var transitiveAssets android.Paths
470 if !a.isLibrary {
471 transitiveAssets = android.ReverseSliceInPlace(staticDeps.assets())
472 }
Colin Crossf3b7bad2023-08-02 15:49:00 -0700473 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt,
Colin Crossab8d1382023-07-14 17:23:41 +0000474 linkFlags, linkDeps, compiledRes, compiledOverlay, transitiveAssets, splitPackages)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800475 // Extract assets from the resource package output so that they can be used later in aapt2link
476 // for modules that depend on this one.
Colin Crossab8d1382023-07-14 17:23:41 +0000477 if android.PrefixInList(linkFlags, "-A ") {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800478 assets := android.PathForModuleOut(ctx, "assets.zip")
479 ctx.Build(pctx, android.BuildParams{
480 Rule: extractAssetsRule,
481 Input: packageRes,
482 Output: assets,
483 Description: "extract assets from built resource file",
484 })
485 a.assetPackage = android.OptionalPathForPath(assets)
486 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700487
Colin Cross4eae06d2023-06-20 22:40:02 -0700488 if a.useResourceProcessorBusyBox() {
489 rJar := android.PathForModuleOut(ctx, "busybox/R.jar")
490 resourceProcessorBusyBoxGenerateBinaryR(ctx, rTxt, a.mergedManifestFile, rJar, staticDeps, a.isLibrary)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700491 aapt2ExtractExtraPackages(ctx, extraPackages, rJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700492 transitiveRJars = append(transitiveRJars, rJar)
493 a.rJar = rJar
Colin Crossf3b7bad2023-08-02 15:49:00 -0700494 } else {
495 aapt2ExtractExtraPackages(ctx, extraPackages, srcJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700496 }
497
Colin Crossa97c5d32018-03-28 14:58:31 -0700498 a.aaptSrcJar = srcJar
Colin Cross4eae06d2023-06-20 22:40:02 -0700499 a.transitiveAaptRJars = transitiveRJars
500 a.transitiveAaptResourcePackages = staticDeps.resPackages()
Colin Crossa97c5d32018-03-28 14:58:31 -0700501 a.exportPackage = packageRes
502 a.manifestPath = manifestPath
503 a.proguardOptionsFile = proguardOptionsFile
Colin Cross66f78822018-05-02 12:58:28 -0700504 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700505 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700506 a.splits = splits
Colin Crossab8d1382023-07-14 17:23:41 +0000507 a.resourcesNodesDepSet = android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL).
508 Direct(&resourcesNode{
509 resPackage: a.exportPackage,
510 manifest: a.manifestPath,
511 additionalManifests: additionalManifests,
Colin Cross4eae06d2023-06-20 22:40:02 -0700512 rTxt: a.rTxt,
513 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +0000514 assets: a.assetPackage,
Colin Cross4eae06d2023-06-20 22:40:02 -0700515
516 usedResourceProcessor: a.useResourceProcessorBusyBox(),
Colin Crossab8d1382023-07-14 17:23:41 +0000517 }).
518 Transitive(staticResourcesNodesDepSet).Build()
519 a.rroDirsDepSet = android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL).
520 Direct(rroDirs...).
521 Transitive(staticRRODirsDepSet).Build()
522 a.manifestsDepSet = android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
523 Direct(a.manifestPath).
524 DirectSlice(additionalManifests).
525 Transitive(staticManifestsDepSet).Build()
526}
527
Colin Cross4eae06d2023-06-20 22:40:02 -0700528var resourceProcessorBusyBox = pctx.AndroidStaticRule("resourceProcessorBusyBox",
529 blueprint.RuleParams{
530 Command: "${config.JavaCmd} -cp ${config.ResourceProcessorBusyBox} " +
531 "com.google.devtools.build.android.ResourceProcessorBusyBox --tool=GENERATE_BINARY_R -- @${out}.args && " +
532 "if cmp -s ${out}.tmp ${out} ; then rm ${out}.tmp ; else mv ${out}.tmp ${out}; fi",
533 CommandDeps: []string{"${config.ResourceProcessorBusyBox}"},
534 Rspfile: "${out}.args",
535 RspfileContent: "--primaryRTxt ${rTxt} --primaryManifest ${manifest} --classJarOutput ${out}.tmp ${args}",
536 Restat: true,
537 }, "rTxt", "manifest", "args")
538
539// resourceProcessorBusyBoxGenerateBinaryR converts the R.txt file produced by aapt2 into R.class files
540// using Bazel's ResourceProcessorBusyBox tool, which is faster than compiling the R.java files and
541// supports producing classes for static dependencies that only include resources from that dependency.
542func resourceProcessorBusyBoxGenerateBinaryR(ctx android.ModuleContext, rTxt, manifest android.Path,
543 rJar android.WritablePath, transitiveDeps transitiveAarDeps, isLibrary bool) {
544
545 var args []string
546 var deps android.Paths
547
548 if !isLibrary {
549 // When compiling an app, pass all R.txt and AndroidManifest.xml from transitive static library dependencies
550 // to ResourceProcessorBusyBox so that it can regenerate R.class files with the final resource IDs for each
551 // package.
552 args, deps = transitiveDeps.resourceProcessorDeps()
553 } else {
554 // When compiling a library don't pass any dependencies as it only needs to generate an R.class file for this
555 // library. Pass --finalFields=false so that the R.class file contains non-final fields so they don't get
556 // inlined into the library before the final IDs are assigned during app compilation.
557 args = append(args, "--finalFields=false")
558 }
559
560 deps = append(deps, rTxt, manifest)
561
562 ctx.Build(pctx, android.BuildParams{
563 Rule: resourceProcessorBusyBox,
564 Output: rJar,
565 Implicits: deps,
566 Description: "ResourceProcessorBusyBox",
567 Args: map[string]string{
568 "rTxt": rTxt.String(),
569 "manifest": manifest.String(),
570 "args": strings.Join(args, " "),
571 },
572 })
573}
574
Colin Crossab8d1382023-07-14 17:23:41 +0000575type resourcesNode struct {
576 resPackage android.Path
577 manifest android.Path
578 additionalManifests android.Paths
Colin Cross4eae06d2023-06-20 22:40:02 -0700579 rTxt android.Path
580 rJar android.Path
Colin Crossab8d1382023-07-14 17:23:41 +0000581 assets android.OptionalPath
Colin Cross4eae06d2023-06-20 22:40:02 -0700582
583 usedResourceProcessor bool
Colin Crossab8d1382023-07-14 17:23:41 +0000584}
585
586type transitiveAarDeps []*resourcesNode
587
588func (t transitiveAarDeps) resPackages() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700589 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000590 for _, dep := range t {
591 paths = append(paths, dep.resPackage)
592 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700593 return paths
Colin Crossab8d1382023-07-14 17:23:41 +0000594}
595
596func (t transitiveAarDeps) manifests() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700597 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000598 for _, dep := range t {
599 paths = append(paths, dep.manifest)
600 paths = append(paths, dep.additionalManifests...)
601 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700602 return paths
603}
604
605func (t transitiveAarDeps) resourceProcessorDeps() (args []string, deps android.Paths) {
606 for _, dep := range t {
607 args = append(args, "--library="+dep.rTxt.String()+","+dep.manifest.String())
608 deps = append(deps, dep.rTxt, dep.manifest)
609 }
610 return args, deps
Colin Crossab8d1382023-07-14 17:23:41 +0000611}
612
613func (t transitiveAarDeps) assets() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700614 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000615 for _, dep := range t {
616 if dep.assets.Valid() {
617 paths = append(paths, dep.assets.Path())
618 }
619 }
620 return paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700621}
622
623// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900624func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Colin Crossab8d1382023-07-14 17:23:41 +0000625 staticResourcesNodes *android.DepSet[*resourcesNode], staticRRODirs *android.DepSet[rroDir],
626 staticManifests *android.DepSet[android.Path], sharedLibs android.Paths, flags []string) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700627
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100628 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000629 // Not all callers need to compute class loader context, those who don't just pass nil.
630 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100631 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000632 }
633
Colin Cross83bb3162018-06-25 15:48:06 -0700634 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700635 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700636 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700637 }
638
Colin Crossab8d1382023-07-14 17:23:41 +0000639 var resourcesNodeDepSets []*android.DepSet[*resourcesNode]
640 rroDirsDepSetBuilder := android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL)
641 manifestsDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
642
Colin Crossa97c5d32018-03-28 14:58:31 -0700643 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000644 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000645
Colin Crossa97c5d32018-03-28 14:58:31 -0700646 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700647 aarDep, _ := module.(AndroidLibraryDependency)
648 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700649 exportPackage = aarDep.ExportPackage()
650 }
651
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000652 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700653 case instrumentationForTag:
654 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400655 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700656 if exportPackage != nil {
657 sharedLibs = append(sharedLibs, exportPackage)
658 }
Colin Cross5446e882019-05-22 10:46:27 -0700659 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700660 if exportPackage != nil {
661 sharedLibs = append(sharedLibs, exportPackage)
662 }
663 case staticLibTag:
664 if exportPackage != nil {
Colin Crossab8d1382023-07-14 17:23:41 +0000665 resourcesNodeDepSets = append(resourcesNodeDepSets, aarDep.ResourcesNodeDepSet())
666 rroDirsDepSetBuilder.Transitive(aarDep.RRODirsDepSet())
667 manifestsDepSetBuilder.Transitive(aarDep.ManifestsDepSet())
Colin Crossa97c5d32018-03-28 14:58:31 -0700668 }
669 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000670
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000671 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700672 })
673
Colin Crossab8d1382023-07-14 17:23:41 +0000674 // AAPT2 overlays are in lowest to highest priority order, the topological order will be reversed later.
675 // Reverse the dependency order now going into the depset so that it comes out in order after the second
676 // reverse later.
677 // NOTE: this is legacy and probably incorrect behavior, for most other cases (e.g. conflicting classes in
678 // dependencies) the highest priority dependency is listed first, but for resources the highest priority
679 // dependency has to be listed last.
680 staticResourcesNodes = android.NewDepSet(android.TOPOLOGICAL, nil,
681 android.ReverseSliceInPlace(resourcesNodeDepSets))
Colin Crossa97c5d32018-03-28 14:58:31 -0700682
Colin Crossab8d1382023-07-14 17:23:41 +0000683 staticRRODirs = rroDirsDepSetBuilder.Build()
684 staticManifests = manifestsDepSetBuilder.Build()
685
686 if len(staticResourcesNodes.ToList()) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700687 flags = append(flags, "--auto-add-overlay")
688 }
689
690 for _, sharedLib := range sharedLibs {
691 flags = append(flags, "-I "+sharedLib.String())
692 }
693
Colin Crossab8d1382023-07-14 17:23:41 +0000694 return staticResourcesNodes, staticRRODirs, staticManifests, sharedLibs, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700695}
696
697type AndroidLibrary struct {
698 Library
699 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500700 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700701
702 androidLibraryProperties androidLibraryProperties
703
704 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700705}
706
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000707var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
708
709// For OutputFileProducer interface
710func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
711 switch tag {
712 case ".aar":
713 return []android.Path{a.aarFile}, nil
714 default:
715 return a.Library.OutputFiles(tag)
716 }
717}
718
Colin Crossa97c5d32018-03-28 14:58:31 -0700719var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
720
721func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
722 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900723 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100724 if sdkDep.hasFrameworkLibs() {
725 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700726 }
Colin Cross4a80a152022-12-21 21:51:52 -0800727 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700728}
729
730func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800731 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100732 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000733 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700734
Colin Cross56a83212020-09-15 18:30:11 -0700735 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
736
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000737 a.stem = proptools.StringDefault(a.overridableDeviceProperties.Stem, ctx.ModuleName())
738
Colin Cross4eae06d2023-06-20 22:40:02 -0700739 ctx.CheckbuildFile(a.aapt.proguardOptionsFile)
740 ctx.CheckbuildFile(a.aapt.exportPackage)
Colin Cross4eae06d2023-06-20 22:40:02 -0700741 if a.useResourceProcessorBusyBox() {
742 ctx.CheckbuildFile(a.aapt.rJar)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700743 } else {
744 ctx.CheckbuildFile(a.aapt.aaptSrcJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700745 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700746
747 // apps manifests are handled by aapt, don't let Module see them
748 a.properties.Manifest = nil
749
Colin Cross014489c2020-06-02 20:09:13 -0700750 a.linter.mergedManifest = a.aapt.mergedManifestFile
751 a.linter.manifest = a.aapt.manifestPath
752 a.linter.resources = a.aapt.resourceFiles
753
Colin Crossa97c5d32018-03-28 14:58:31 -0700754 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
755 a.proguardOptionsFile)
756
Colin Cross4eae06d2023-06-20 22:40:02 -0700757 var extraSrcJars android.Paths
758 var extraCombinedJars android.Paths
759 var extraClasspathJars android.Paths
760 if a.useResourceProcessorBusyBox() {
761 // When building a library with ResourceProcessorBusyBox enabled ResourceProcessorBusyBox for this
762 // library and each of the transitive static android_library dependencies has already created an
763 // R.class file for the appropriate package. Add all of those R.class files to the classpath.
764 extraClasspathJars = a.transitiveAaptRJars
765 } else {
766 // When building a library without ResourceProcessorBusyBox the aapt2 rule creates R.srcjar containing
767 // R.java files for the library's package and the packages from all transitive static android_library
768 // dependencies. Compile the srcjar alongside the rest of the sources.
769 extraSrcJars = android.Paths{a.aapt.aaptSrcJar}
770 }
771
772 a.Module.compile(ctx, extraSrcJars, extraClasspathJars, extraCombinedJars)
Colin Crossa97c5d32018-03-28 14:58:31 -0700773
Colin Crossf57c5782019-01-25 13:20:38 -0800774 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700775 var res android.Paths
776 if a.androidLibraryProperties.BuildAAR {
777 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
778 ctx.CheckbuildFile(a.aarFile)
779 }
Colin Cross89c31582018-04-30 15:55:11 -0700780
Cole Faust9a631312020-10-22 21:05:24 +0000781 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
782 android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
Colin Crossab8d1382023-07-14 17:23:41 +0000783
Colin Cross89c31582018-04-30 15:55:11 -0700784 ctx.VisitDirectDeps(func(m android.Module) {
Jared Duke5979b302022-12-19 21:08:39 +0000785 if ctx.OtherModuleDependencyTag(m) == staticLibTag {
786 if lib, ok := m.(LibraryDependency); ok {
787 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
788 }
Colin Cross89c31582018-04-30 15:55:11 -0700789 }
790 })
Colin Cross89c31582018-04-30 15:55:11 -0700791 a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
Sam Delmerico82602492022-06-10 17:05:42 +0000792
793 prebuiltJniPackages := android.Paths{}
794 ctx.VisitDirectDeps(func(module android.Module) {
795 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
796 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
797 }
798 })
799 if len(prebuiltJniPackages) > 0 {
800 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
801 JniPackages: prebuiltJniPackages,
802 })
803 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700804}
805
Colin Cross1b16b0e2019-02-12 14:41:32 -0800806// android_library builds and links sources into a `.jar` file for the device along with Android resources.
807//
808// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000809// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800810// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
811// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700812func AndroidLibraryFactory() android.Module {
813 module := &AndroidLibrary{}
814
Colin Crossce6734e2020-06-15 16:09:53 -0700815 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700816 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700817 &module.aaptProperties,
818 &module.androidLibraryProperties)
819
820 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700821 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700822
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900823 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700824 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500825 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700826 return module
827}
828
Colin Crossfabb6082018-02-20 17:22:23 -0800829//
830// AAR (android library) prebuilts
831//
Colin Crossfabb6082018-02-20 17:22:23 -0800832
Vinh Trance0781f2022-04-13 01:30:44 +0000833// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800834type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000835 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800836 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000837 // If not blank, set to the version of the sdk to compile against.
838 // Defaults to private.
839 // Values are of one of the following forms:
840 // 1) numerical API level, "current", "none", or "core_platform"
841 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
842 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
843 // If the SDK kind is empty, it will be set to public
844 Sdk_version *string
845 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
846 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700847 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000848 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700849 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000850 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
851 Libs []string
852 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700853 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000854 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
855 // will be passed transitively through android_libraries to an android_app.
856 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
857 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800858}
859
860type AARImport struct {
861 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700862 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900863 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500864 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800865 prebuilt android.Prebuilt
866
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900867 // Functionality common to Module and Import.
868 embeddableInModuleAndImport
869
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500870 providesTransitiveHeaderJars
871
Colin Crossfabb6082018-02-20 17:22:23 -0800872 properties AARImportProperties
873
Colin Cross4eae06d2023-06-20 22:40:02 -0700874 classpathFile android.WritablePath
875 proguardFlags android.WritablePath
876 exportPackage android.WritablePath
877 transitiveAaptResourcePackages android.Paths
878 extraAaptPackagesFile android.WritablePath
879 manifest android.WritablePath
880 assetsPackage android.WritablePath
881 rTxt android.WritablePath
882 rJar android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700883
Colin Crossab8d1382023-07-14 17:23:41 +0000884 resourcesNodesDepSet *android.DepSet[*resourcesNode]
885 manifestsDepSet *android.DepSet[android.Path]
Colin Cross56a83212020-09-15 18:30:11 -0700886
887 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000888
Sam Delmerico82602492022-06-10 17:05:42 +0000889 aarPath android.Path
890 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900891
892 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000893 minSdkVersion android.ApiLevel
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000894}
895
896var _ android.OutputFileProducer = (*AARImport)(nil)
897
898// For OutputFileProducer interface
899func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
900 switch tag {
901 case ".aar":
902 return []android.Path{a.aarPath}, nil
903 case "":
904 return []android.Path{a.classpathFile}, nil
905 default:
906 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
907 }
Colin Crossfabb6082018-02-20 17:22:23 -0800908}
909
Jiyong Park92315372021-04-02 08:45:46 +0900910func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
911 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700912}
913
Jiyong Parkf1691d22021-03-29 20:11:58 +0900914func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100915 return ""
916}
917
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000918func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Colin Cross479884c2018-07-10 13:39:30 -0700919 if a.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000920 return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700921 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000922 return a.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -0700923}
924
Spandan Dasa26eda72023-03-02 00:56:06 +0000925func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
926 return android.SdkSpecFrom(ctx, "").ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000927}
928
Spandan Dasca70fc42023-03-01 23:38:49 +0000929func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
930 return a.SdkVersion(ctx).ApiLevel
Dan Willemsen419290a2018-10-31 15:28:47 -0700931}
932
Colin Cross1e743852019-10-28 11:37:20 -0700933func (a *AARImport) javaVersion() string {
934 return ""
935}
936
Colin Crossa97c5d32018-03-28 14:58:31 -0700937var _ AndroidLibraryDependency = (*AARImport)(nil)
938
939func (a *AARImport) ExportPackage() android.Path {
940 return a.exportPackage
941}
Colin Cross89c31582018-04-30 15:55:11 -0700942func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
943 return android.Paths{a.proguardFlags}
944}
945
Colin Crossab8d1382023-07-14 17:23:41 +0000946func (a *AARImport) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
947 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800948}
949
Colin Crossab8d1382023-07-14 17:23:41 +0000950func (a *AARImport) RRODirsDepSet() *android.DepSet[rroDir] {
951 return android.NewDepSet[rroDir](android.TOPOLOGICAL, nil, nil)
Colin Cross66f78822018-05-02 12:58:28 -0700952}
953
Colin Crossab8d1382023-07-14 17:23:41 +0000954func (a *AARImport) ManifestsDepSet() *android.DepSet[android.Path] {
955 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800956}
957
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700958// RRO enforcement is not available on aar_import since its RRO dirs are not
959// exported.
960func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
961}
962
963// RRO enforcement is not available on aar_import since its RRO dirs are not
964// exported.
965func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
966 return false
967}
968
Colin Crossfabb6082018-02-20 17:22:23 -0800969func (a *AARImport) Prebuilt() *android.Prebuilt {
970 return &a.prebuilt
971}
972
973func (a *AARImport) Name() string {
974 return a.prebuilt.Name(a.ModuleBase.Name())
975}
976
Jiyong Park618922e2020-01-08 13:35:43 +0900977func (a *AARImport) JacocoReportClassesFile() android.Path {
978 return nil
979}
980
Colin Crossfabb6082018-02-20 17:22:23 -0800981func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900982 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900983 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700984 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700985 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800986 }
987 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700988
Colin Cross42d48b72018-08-29 14:10:52 -0700989 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
990 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800991}
992
Sam Delmerico82602492022-06-10 17:05:42 +0000993type JniPackageInfo struct {
994 // List of zip files containing JNI libraries
995 // Zip files should have directory structure jni/<arch>/*.so
996 JniPackages android.Paths
997}
998
999var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
1000
1001// Unzip an AAR and extract the JNI libs for $archString.
1002var extractJNI = pctx.AndroidStaticRule("extractJNI",
1003 blueprint.RuleParams{
1004 Command: `rm -rf $out $outDir && touch $out && ` +
1005 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
1006 `jni_files=$$(find $outDir/jni -type f) && ` +
1007 // print error message if there are no JNI libs for this arch
1008 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
1009 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
1010 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
1011 CommandDeps: []string{"${config.SoongZipCmd}"},
1012 },
1013 "outDir", "archString")
1014
Colin Crossfabb6082018-02-20 17:22:23 -08001015// Unzip an AAR into its constituent files and directories. Any files in Outputs that don't exist in the AAR will be
Dan Willemsen304cfec2019-05-28 14:49:06 -07001016// touched to create an empty file. The res directory is not extracted, as it will be extracted in its own rule.
Colin Crossfabb6082018-02-20 17:22:23 -08001017var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
1018 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -07001019 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001020 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001021 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001022 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001023 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -08001024 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001025 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -08001026
1027func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1028 if len(a.properties.Aars) != 1 {
1029 ctx.PropertyErrorf("aars", "exactly one aar is required")
1030 return
1031 }
1032
Jiyong Park92315372021-04-02 08:45:46 +09001033 a.sdkVersion = a.SdkVersion(ctx)
1034 a.minSdkVersion = a.MinSdkVersion(ctx)
1035
Colin Cross56a83212020-09-15 18:30:11 -07001036 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
1037
Nan Zhang4c819fb2018-08-27 18:31:46 -07001038 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001039 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
1040
Colin Cross1001a792019-03-21 22:21:39 -07001041 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001042 inputFile := a.aarPath
1043 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
1044 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -07001045 }
Colin Crossfabb6082018-02-20 17:22:23 -08001046
1047 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -07001048 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Crossfabb6082018-02-20 17:22:23 -08001049 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
Colin Cross10f7c4a2018-05-23 10:59:28 -07001050 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Colin Cross4eae06d2023-06-20 22:40:02 -07001051 aarRTxt := extractedAARDir.Join(ctx, "R.txt")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001052 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Colin Crossfabb6082018-02-20 17:22:23 -08001053
1054 ctx.Build(pctx, android.BuildParams{
1055 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001056 Input: a.aarPath,
Colin Cross4eae06d2023-06-20 22:40:02 -07001057 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage, aarRTxt},
Colin Crossfabb6082018-02-20 17:22:23 -08001058 Description: "unzip AAR",
1059 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -07001060 "outDir": extractedAARDir.String(),
1061 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001062 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -08001063 },
1064 })
1065
Colin Crossa0ba2f52019-06-22 12:59:27 -07001066 // Always set --pseudo-localize, it will be stripped out later for release
1067 // builds that don't want it.
1068 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -08001069 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -08001070 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001071 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -08001072
1073 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossfabb6082018-02-20 17:22:23 -08001074 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Cross4eae06d2023-06-20 22:40:02 -07001075 a.rTxt = android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -07001076 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -08001077
1078 var linkDeps android.Paths
1079
1080 linkFlags := []string{
1081 "--static-lib",
Colin Cross4eae06d2023-06-20 22:40:02 -07001082 "--merge-only",
Colin Crossfabb6082018-02-20 17:22:23 -08001083 "--auto-add-overlay",
1084 }
1085
Colin Cross10f7c4a2018-05-23 10:59:28 -07001086 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
1087 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -08001088
Colin Crossab8d1382023-07-14 17:23:41 +00001089 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedLibs, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +09001090 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -07001091
Colin Crossab8d1382023-07-14 17:23:41 +00001092 _ = staticRRODirsDepSet
1093 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
Colin Crossfabb6082018-02-20 17:22:23 -08001094
Colin Crossab8d1382023-07-14 17:23:41 +00001095 linkDeps = append(linkDeps, sharedLibs...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001096 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -07001097 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -08001098
Colin Cross4eae06d2023-06-20 22:40:02 -07001099 overlayRes := android.Paths{flata}
1100
1101 // Treat static library dependencies of static libraries as imports.
1102 transitiveStaticLibs := staticDeps.resPackages()
1103 linkDeps = append(linkDeps, transitiveStaticLibs...)
1104 for _, staticLib := range transitiveStaticLibs {
1105 linkFlags = append(linkFlags, "-I "+staticLib.String())
1106 }
Colin Crossfabb6082018-02-20 17:22:23 -08001107
Colin Crossab8d1382023-07-14 17:23:41 +00001108 transitiveAssets := android.ReverseSliceInPlace(staticDeps.assets())
Colin Crossf3b7bad2023-08-02 15:49:00 -07001109 aapt2Link(ctx, a.exportPackage, nil, proguardOptionsFile, a.rTxt,
Jaewoong Jung6431ca72020-01-15 14:15:10 -08001110 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001111
Colin Cross4eae06d2023-06-20 22:40:02 -07001112 a.rJar = android.PathForModuleOut(ctx, "busybox/R.jar")
1113 resourceProcessorBusyBoxGenerateBinaryR(ctx, a.rTxt, a.manifest, a.rJar, nil, true)
1114
Colin Crossf3b7bad2023-08-02 15:49:00 -07001115 aapt2ExtractExtraPackages(ctx, a.extraAaptPackagesFile, a.rJar)
1116
Colin Crossab8d1382023-07-14 17:23:41 +00001117 resourcesNodesDepSetBuilder := android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL)
1118 resourcesNodesDepSetBuilder.Direct(&resourcesNode{
1119 resPackage: a.exportPackage,
1120 manifest: a.manifest,
Colin Cross4eae06d2023-06-20 22:40:02 -07001121 rTxt: a.rTxt,
1122 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +00001123 assets: android.OptionalPathForPath(a.assetsPackage),
Colin Cross4eae06d2023-06-20 22:40:02 -07001124
1125 usedResourceProcessor: true,
Colin Crossab8d1382023-07-14 17:23:41 +00001126 })
1127 resourcesNodesDepSetBuilder.Transitive(staticResourcesNodesDepSet)
1128 a.resourcesNodesDepSet = resourcesNodesDepSetBuilder.Build()
1129
1130 manifestDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(a.manifest)
1131 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
1132 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
1133 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
1134 // android_library_import modules. If this is fixed, AndroidLibraryDependency.ManifestsDepSet can be dropped
1135 // completely in favor of AndroidLibraryDependency.ResourceNodesDepSet.manifest
1136 //manifestDepSetBuilder.Transitive(transitiveStaticDeps.manifests)
1137 _ = staticManifestsDepSet
1138 a.manifestsDepSet = manifestDepSetBuilder.Build()
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001139
Colin Cross4eae06d2023-06-20 22:40:02 -07001140 a.transitiveAaptResourcePackages = staticDeps.resPackages()
1141
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001142 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -08001143 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1144 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001145 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
1146 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08001147 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
1148 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001149 // TransitiveAconfigFiles: // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08001150 })
Sam Delmerico82602492022-06-10 17:05:42 +00001151
1152 if proptools.Bool(a.properties.Extract_jni) {
1153 for _, t := range ctx.MultiTargets() {
1154 arch := t.Arch.Abi[0]
1155 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
1156 a.jniPackages = append(a.jniPackages, path)
1157
1158 outDir := android.PathForModuleOut(ctx, "aarForJni")
1159 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
1160 ctx.Build(pctx, android.BuildParams{
1161 Rule: extractJNI,
1162 Input: aarPath,
1163 Outputs: android.WritablePaths{path},
1164 Description: "extract JNI from AAR",
1165 Args: map[string]string{
1166 "outDir": outDir.String(),
1167 "archString": arch,
1168 },
1169 })
1170 }
1171
1172 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
1173 JniPackages: a.jniPackages,
1174 })
1175 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001176}
Colin Crossfabb6082018-02-20 17:22:23 -08001177
1178func (a *AARImport) HeaderJars() android.Paths {
1179 return android.Paths{a.classpathFile}
1180}
1181
Colin Cross331a1212018-08-15 20:40:52 -07001182func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
1183 return android.Paths{a.classpathFile}
1184}
1185
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +00001186func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -08001187 return nil
1188}
1189
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001190func (a *AARImport) DexJarInstallPath() android.Path {
1191 return nil
1192}
1193
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001194func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +09001195 return nil
1196}
1197
Jiyong Park45bf82e2020-12-15 22:29:02 +09001198var _ android.ApexModule = (*AARImport)(nil)
1199
1200// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001201func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1202 return a.depIsInSameApex(ctx, dep)
1203}
1204
Jiyong Park45bf82e2020-12-15 22:29:02 +09001205// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001206func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1207 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001208 return nil
1209}
1210
Sam Delmericoaf8bb702022-07-25 15:39:32 -04001211var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001212
Colin Cross1b16b0e2019-02-12 14:41:32 -08001213// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
1214//
1215// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
1216// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -08001217func AARImportFactory() android.Module {
1218 module := &AARImport{}
1219
1220 module.AddProperties(&module.properties)
1221
1222 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001223 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +00001224 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001225 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -08001226 return module
1227}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001228
1229type bazelAapt struct {
1230 Manifest bazel.Label
1231 Resource_files bazel.LabelListAttribute
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001232 Assets_dir bazel.StringAttribute
1233 Assets bazel.LabelListAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001234}
1235
1236type bazelAndroidLibrary struct {
1237 *javaLibraryAttributes
1238 *bazelAapt
1239}
1240
1241type bazelAndroidLibraryImport struct {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001242 Aar bazel.Label
1243 Deps bazel.LabelListAttribute
1244 Exports bazel.LabelListAttribute
1245 Sdk_version bazel.StringAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001246}
1247
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001248func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) (*bazelAapt, bool) {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001249 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1250
1251 resourceFiles := bazel.LabelList{
1252 Includes: []bazel.Label{},
1253 }
1254 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1255 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1256 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1257 }
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001258
1259 assetsDir := bazel.StringAttribute{}
1260 var assets bazel.LabelList
1261 for i, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets") {
1262 if i > 0 {
1263 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "multiple asset_dirs")
1264 return &bazelAapt{}, false
1265 }
1266 // Assets_dirs are relative to the module dir when specified, but if the default in used in
1267 // PathsWithOptionalDefaultForModuleSrc, then dir is relative to the top.
1268 assetsRelDir, error := filepath.Rel(ctx.ModuleDir(), dir.Rel())
1269 if error != nil {
1270 assetsRelDir = dir.Rel()
1271 }
1272 assetsDir.Value = proptools.StringPtr(assetsRelDir)
1273 assets = bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir)))
1274
1275 }
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001276 return &bazelAapt{
1277 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1278 bazel.MakeLabelListAttribute(resourceFiles),
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001279 assetsDir,
1280 bazel.MakeLabelListAttribute(assets),
1281 }, true
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001282}
1283
1284func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1285 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1286 exportableStaticLibs := []string{}
1287 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1288 for _, depName := range a.properties.Static_libs {
1289 if dep, ok := ctx.ModuleFromName(depName); ok {
1290 switch dep.(type) {
1291 case *AARImport, *Import:
1292 exportableStaticLibs = append(exportableStaticLibs, depName)
1293 }
1294 }
1295 }
1296 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1297 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1298 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1299
1300 ctx.CreateBazelTargetModule(
1301 bazel.BazelTargetModuleProperties{
1302 Rule_class: "aar_import",
Alixa381cd12023-05-10 14:49:38 +00001303 Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001304 },
1305 android.CommonAttributes{Name: name},
1306 &bazelAndroidLibraryImport{
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001307 Aar: aars.Includes[0],
1308 Deps: bazel.MakeLabelListAttribute(deps),
1309 Exports: bazel.MakeLabelListAttribute(exports),
1310 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001311 },
1312 )
1313
Alix14101de2023-01-06 03:42:07 +00001314 neverlink := true
1315 ctx.CreateBazelTargetModule(
Alix32540022023-03-16 21:06:13 +00001316 AndroidLibraryBazelTargetModuleProperties(),
Alix14101de2023-01-06 03:42:07 +00001317 android.CommonAttributes{Name: name + "-neverlink"},
1318 &bazelAndroidLibrary{
1319 javaLibraryAttributes: &javaLibraryAttributes{
1320 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1321 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001322 javaCommonAttributes: &javaCommonAttributes{
1323 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
1324 },
Alix14101de2023-01-06 03:42:07 +00001325 },
1326 },
1327 )
1328
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001329}
Alix32540022023-03-16 21:06:13 +00001330func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
1331 return bazel.BazelTargetModuleProperties{
1332 Rule_class: "android_library",
Alixa381cd12023-05-10 14:49:38 +00001333 Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
Alix32540022023-03-16 21:06:13 +00001334 }
1335}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001336
1337func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer7f375862023-08-04 16:37:42 -04001338 commonAttrs, bp2buildInfo, supported := a.convertLibraryAttrsBp2Build(ctx)
1339 if !supported {
1340 return
1341 }
1342
Alix8062f4d2022-11-14 21:38:07 +00001343 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001344
1345 deps := depLabels.Deps
1346 if !commonAttrs.Srcs.IsEmpty() {
1347 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1348 } else if !depLabels.Deps.IsEmpty() {
1349 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1350 }
Alix82fb94e2022-10-26 20:40:18 +00001351 name := a.Name()
Alix32540022023-03-16 21:06:13 +00001352 props := AndroidLibraryBazelTargetModuleProperties()
Alix82fb94e2022-10-26 20:40:18 +00001353
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001354 aaptAttrs, supported := a.convertAaptAttrsWithBp2Build(ctx)
1355 if !supported {
1356 return
1357 }
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001358 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001359 props,
1360 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001361 &bazelAndroidLibrary{
1362 &javaLibraryAttributes{
1363 javaCommonAttributes: commonAttrs,
1364 Deps: deps,
1365 Exports: depLabels.StaticDeps,
1366 },
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001367 aaptAttrs,
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001368 },
1369 )
Alix82fb94e2022-10-26 20:40:18 +00001370
1371 neverlink := true
1372 ctx.CreateBazelTargetModule(
1373 props,
1374 android.CommonAttributes{Name: name + "-neverlink"},
1375 &bazelAndroidLibrary{
1376 javaLibraryAttributes: &javaLibraryAttributes{
1377 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1378 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001379 javaCommonAttributes: &javaCommonAttributes{
1380 Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
1381 Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
1382 },
Alix82fb94e2022-10-26 20:40:18 +00001383 },
1384 },
1385 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001386}