blob: 19b4039cbca015fde0cc0a423710e3ae647e8525 [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"
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080026
Colin Crossfabb6082018-02-20 17:22:23 -080027 "github.com/google/blueprint"
Colin Crossa97c5d32018-03-28 14:58:31 -070028 "github.com/google/blueprint/proptools"
Colin Crossfabb6082018-02-20 17:22:23 -080029)
30
Colin Crossa97c5d32018-03-28 14:58:31 -070031type AndroidLibraryDependency interface {
Jared Duke5979b302022-12-19 21:08:39 +000032 LibraryDependency
Colin Crossa97c5d32018-03-28 14:58:31 -070033 ExportPackage() android.Path
Colin Crossab8d1382023-07-14 17:23:41 +000034 ResourcesNodeDepSet() *android.DepSet[*resourcesNode]
35 RRODirsDepSet() *android.DepSet[rroDir]
36 ManifestsDepSet() *android.DepSet[android.Path]
Jaewoong Jungc779cd42020-10-06 18:56:10 -070037 SetRROEnforcedForDependent(enforce bool)
38 IsRROEnforced(ctx android.BaseModuleContext) bool
Colin Crossa97c5d32018-03-28 14:58:31 -070039}
40
41func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000042 RegisterAARBuildComponents(android.InitRegistrationContext)
43}
44
45func RegisterAARBuildComponents(ctx android.RegistrationContext) {
46 ctx.RegisterModuleType("android_library_import", AARImportFactory)
47 ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
Paul Duffin04ba70d2021-03-22 13:56:43 +000048 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
49 ctx.TopDown("propagate_rro_enforcement", propagateRROEnforcementMutator).Parallel()
50 })
Colin Crossa97c5d32018-03-28 14:58:31 -070051}
52
53//
54// AAR (android library)
55//
56
57type androidLibraryProperties struct {
58 BuildAAR bool `blueprint:"mutated"`
59}
60
61type aaptProperties struct {
62 // flags passed to aapt when creating the apk
63 Aaptflags []string
64
Dan Willemsen72be5902018-10-24 20:24:57 -070065 // include all resource configurations, not just the product-configured
66 // ones.
67 Aapt_include_all_resources *bool
68
Colin Crossa97c5d32018-03-28 14:58:31 -070069 // list of directories relative to the Blueprints file containing assets.
Colin Cross0ddae7f2019-02-07 15:30:01 -080070 // Defaults to ["assets"] if a directory called assets exists. Set to []
71 // to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070072 Asset_dirs []string
73
74 // list of directories relative to the Blueprints file containing
Colin Cross0ddae7f2019-02-07 15:30:01 -080075 // Android resources. Defaults to ["res"] if a directory called res exists.
76 // Set to [] to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070077 Resource_dirs []string
78
Colin Crossa592e3e2019-02-19 16:59:53 -080079 // list of zip files containing Android resources.
Colin Cross27b922f2019-03-04 22:35:41 -080080 Resource_zips []string `android:"path"`
Colin Crossa592e3e2019-02-19 16:59:53 -080081
Colin Crossa97c5d32018-03-28 14:58:31 -070082 // path to AndroidManifest.xml. If unset, defaults to "AndroidManifest.xml".
Colin Cross27b922f2019-03-04 22:35:41 -080083 Manifest *string `android:"path"`
changho.shinb5432b72019-08-08 18:37:17 +090084
85 // paths to additional manifest files to merge with main manifest.
86 Additional_manifests []string `android:"path"`
Sasha Smundak541056c2019-10-28 15:50:06 -070087
88 // do not include AndroidManifest from dependent libraries
89 Dont_merge_manifests *bool
Jaewoong Jungc779cd42020-10-06 18:56:10 -070090
Colin Cross039d8df2023-06-20 22:40:02 -070091 // If use_resource_processor is set, use Bazel's resource processor instead of aapt2 to generate R.class files.
92 // The resource processor produces more optimal R.class files that only list resources in the package of the
93 // library that provided them, as opposed to aapt2 which produces R.java files for every package containing
94 // every resource. Using the resource processor can provide significant build time speedups, but requires
95 // fixing the module to use the correct package to reference each resource, and to avoid having any other
96 // libraries in the tree that use the same package name. Defaults to false, but will default to true in the
97 // future.
98 Use_resource_processor *bool
99
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700100 // true if RRO is enforced for any of the dependent modules
101 RROEnforcedForDependent bool `blueprint:"mutated"`
Colin Crossa97c5d32018-03-28 14:58:31 -0700102}
103
104type aapt struct {
Colin Cross039d8df2023-06-20 22:40:02 -0700105 aaptSrcJar android.Path
106 transitiveAaptRJars android.Paths
107 transitiveAaptResourcePackages android.Paths
108 exportPackage android.Path
109 manifestPath android.Path
110 proguardOptionsFile android.Path
111 rTxt android.Path
112 rJar android.Path
113 extraAaptPackagesFile android.Path
114 mergedManifestFile android.Path
115 noticeFile android.OptionalPath
116 assetPackage android.OptionalPath
117 isLibrary bool
118 defaultManifestVersion string
119 useEmbeddedNativeLibs bool
120 useEmbeddedDex bool
121 usesNonSdkApis bool
122 hasNoCode bool
123 LoggingParent string
124 resourceFiles android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700125
Colin Crosse560c4a2019-03-19 16:03:11 -0700126 splitNames []string
127 splits []split
128
Colin Crossa97c5d32018-03-28 14:58:31 -0700129 aaptProperties aaptProperties
Colin Crossab8d1382023-07-14 17:23:41 +0000130
131 resourcesNodesDepSet *android.DepSet[*resourcesNode]
132 rroDirsDepSet *android.DepSet[rroDir]
133 manifestsDepSet *android.DepSet[android.Path]
Colin Crossa97c5d32018-03-28 14:58:31 -0700134}
135
Colin Crosse560c4a2019-03-19 16:03:11 -0700136type split struct {
137 name string
138 suffix string
139 path android.Path
140}
141
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700142// Propagate RRO enforcement flag to static lib dependencies transitively.
143func propagateRROEnforcementMutator(ctx android.TopDownMutatorContext) {
144 m := ctx.Module()
145 if d, ok := m.(AndroidLibraryDependency); ok && d.IsRROEnforced(ctx) {
146 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
147 if a, ok := d.(AndroidLibraryDependency); ok {
148 a.SetRROEnforcedForDependent(true)
149 }
150 })
151 }
152}
153
Colin Cross039d8df2023-06-20 22:40:02 -0700154func (a *aapt) useResourceProcessorBusyBox() bool {
155 return BoolDefault(a.aaptProperties.Use_resource_processor, false)
156}
157
Colin Crossa97c5d32018-03-28 14:58:31 -0700158func (a *aapt) ExportPackage() android.Path {
159 return a.exportPackage
160}
Colin Crossab8d1382023-07-14 17:23:41 +0000161func (a *aapt) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
162 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800163}
164
Colin Crossab8d1382023-07-14 17:23:41 +0000165func (a *aapt) RRODirsDepSet() *android.DepSet[rroDir] {
166 return a.rroDirsDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800167}
168
Colin Crossab8d1382023-07-14 17:23:41 +0000169func (a *aapt) ManifestsDepSet() *android.DepSet[android.Path] {
170 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800171}
172
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700173func (a *aapt) SetRROEnforcedForDependent(enforce bool) {
174 a.aaptProperties.RROEnforcedForDependent = enforce
175}
176
177func (a *aapt) IsRROEnforced(ctx android.BaseModuleContext) bool {
178 // True if RRO is enforced for this module or...
179 return ctx.Config().EnforceRROForModule(ctx.ModuleName()) ||
Jeongik Chacee5ba92021-02-19 12:11:51 +0900180 // if RRO is enforced for any of its dependents.
181 a.aaptProperties.RROEnforcedForDependent
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700182}
183
Jiyong Parkf1691d22021-03-29 20:11:58 +0900184func (a *aapt) aapt2Flags(ctx android.ModuleContext, sdkContext android.SdkContext,
Colin Crossa0ba2f52019-06-22 12:59:27 -0700185 manifestPath android.Path) (compileFlags, linkFlags []string, linkDeps android.Paths,
186 resDirs, overlayDirs []globbedResourceDir, rroDirs []rroDir, resZips android.Paths) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700187
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800188 hasVersionCode := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-code")
189 hasVersionName := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-name")
Colin Crossa97c5d32018-03-28 14:58:31 -0700190
Colin Crossa97c5d32018-03-28 14:58:31 -0700191 // Flags specified in Android.bp
192 linkFlags = append(linkFlags, a.aaptProperties.Aaptflags...)
193
Eric Miao40eab202023-03-30 16:57:17 +0000194 linkFlags = append(linkFlags, "--enable-compact-entries")
Colin Crossa97c5d32018-03-28 14:58:31 -0700195
196 // Find implicit or explicit asset and resource dirs
197 assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
198 resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
Colin Cross8a497952019-03-05 22:25:09 -0800199 resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
Colin Crossa97c5d32018-03-28 14:58:31 -0700200
Colin Crossa97c5d32018-03-28 14:58:31 -0700201 // Glob directories into lists of paths
202 for _, dir := range resourceDirs {
203 resDirs = append(resDirs, globbedResourceDir{
204 dir: dir,
205 files: androidResourceGlob(ctx, dir),
206 })
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700207 resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
Colin Crossa97c5d32018-03-28 14:58:31 -0700208 overlayDirs = append(overlayDirs, resOverlayDirs...)
209 rroDirs = append(rroDirs, resRRODirs...)
210 }
211
Colin Crossc20dc852020-11-10 12:27:45 -0800212 var assetDeps android.Paths
213 for i, dir := range assetDirs {
214 // Add a dependency on every file in the asset directory. This ensures the aapt2
215 // rule will be rerun if one of the files in the asset directory is modified.
216 assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
217
218 // Add a dependency on a file that contains a list of all the files in the asset directory.
219 // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
220 // or a file is added whose timestamp is older than the output of aapt2.
221 assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
222 androidResourceGlobList(ctx, dir, assetFileListFile)
223 assetDeps = append(assetDeps, assetFileListFile)
Colin Crossa97c5d32018-03-28 14:58:31 -0700224 }
225
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700226 assetDirStrings := assetDirs.Strings()
227 if a.noticeFile.Valid() {
228 assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
Colin Crossc20dc852020-11-10 12:27:45 -0800229 assetDeps = append(assetDeps, a.noticeFile.Path())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700230 }
231
Colin Crossa97c5d32018-03-28 14:58:31 -0700232 linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
233 linkDeps = append(linkDeps, manifestPath)
234
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700235 linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
Colin Crossc20dc852020-11-10 12:27:45 -0800236 linkDeps = append(linkDeps, assetDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700237
Spandan Das50885c02023-02-23 21:31:33 +0000238 // Returns the effective version for {min|target}_sdk_version
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000239 effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
Spandan Das50885c02023-02-23 21:31:33 +0000240 // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
241 // This is necessary for vendor modules.
242 // The effective version does not _only_ depend on {min|target}_sdk_version(level),
243 // but also on the sdk_version (kind+level)
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000244 if minSdkVersion.IsCurrent() {
Spandan Das50885c02023-02-23 21:31:33 +0000245 ret, err := sdkVersion.EffectiveVersionString(ctx)
246 if err != nil {
247 ctx.ModuleErrorf("invalid sdk_version: %s", err)
248 }
249 return ret
250 }
251 ret, err := minSdkVersion.EffectiveVersionString(ctx)
252 if err != nil {
253 ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
254 }
255 return ret
Jiyong Park6a927c42020-01-21 02:03:43 +0900256 }
Spandan Das50885c02023-02-23 21:31:33 +0000257 // SDK version flags
258 sdkVersion := sdkContext.SdkVersion(ctx)
259 minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
Colin Crossa97c5d32018-03-28 14:58:31 -0700260
Colin Cross83bb3162018-06-25 15:48:06 -0700261 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000262 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
263 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700264 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700265
Colin Crossa97c5d32018-03-28 14:58:31 -0700266 // Version code
267 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700268 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700269 }
270
271 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700272 var versionName string
273 if ctx.ModuleName() == "framework-res" {
274 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
275 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700276 // if it contains the build number. Use the PlatformVersionName instead.
277 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700278 } else {
279 versionName = ctx.Config().AppsDefaultVersionName()
280 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800281 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700282 linkFlags = append(linkFlags, "--version-name ", versionName)
283 }
284
Colin Crossa0ba2f52019-06-22 12:59:27 -0700285 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
286
287 // Always set --pseudo-localize, it will be stripped out later for release
288 // builds that don't want it.
289 compileFlags = append(compileFlags, "--pseudo-localize")
290
291 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700292}
293
Paul Duffin250e6192019-06-07 10:44:37 +0100294func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800295 if sdkDep.frameworkResModule != "" {
296 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700297 }
298}
299
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800300var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
301 blueprint.RuleParams{
302 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
303 CommandDeps: []string{"${config.Zip2ZipCmd}"},
304 })
305
Jiyong Parkf1691d22021-03-29 20:11:58 +0900306func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000307 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000308 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700309
Colin Crossab8d1382023-07-14 17:23:41 +0000310 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100311 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100312
Paul Duffin06530572022-02-03 17:54:15 +0000313 // Exclude any libraries from the supplied list.
314 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
315
Colin Cross31656952018-05-24 16:11:20 -0700316 // App manifest file
317 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
318 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
319
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000320 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000321 SdkContext: sdkContext,
322 ClassLoaderContexts: classLoaderContexts,
323 IsLibrary: a.isLibrary,
324 DefaultManifestVersion: a.defaultManifestVersion,
325 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
326 UsesNonSdkApis: a.usesNonSdkApis,
327 UseEmbeddedDex: a.useEmbeddedDex,
328 HasNoCode: a.hasNoCode,
329 LoggingParent: a.LoggingParent,
330 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000331 })
Colin Cross90c25c62019-04-19 16:22:57 -0700332
Colin Crossab8d1382023-07-14 17:23:41 +0000333 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
334
Luca Stefanifd898822019-09-10 22:13:31 +0200335 // Add additional manifest files to transitive manifests.
336 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
Colin Crossab8d1382023-07-14 17:23:41 +0000337 transitiveManifestPaths := append(android.Paths{manifestPath}, additionalManifests...)
338 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
339 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
340 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
341 // android_library_import modules. If this is fixed, staticManifestsDepSet can be dropped completely in favor of
342 // staticResourcesNodesDepSet.manifests()
343 transitiveManifestPaths = append(transitiveManifestPaths, staticManifestsDepSet.ToList()...)
Colin Cross90c25c62019-04-19 16:22:57 -0700344
Colin Crossab8d1382023-07-14 17:23:41 +0000345 if len(transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
346 a.mergedManifestFile = manifestMerger(ctx, transitiveManifestPaths[0], transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700347 if !a.isLibrary {
348 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
349 // will be propagated to the final application and merged there. The merged manifest for libraries is
350 // only passed to Make, which can't handle transitive dependencies.
351 manifestPath = a.mergedManifestFile
352 }
353 } else {
354 a.mergedManifestFile = manifestPath
355 }
Colin Cross31656952018-05-24 16:11:20 -0700356
Colin Crossa0ba2f52019-06-22 12:59:27 -0700357 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700358
359 linkFlags = append(linkFlags, libFlags...)
Colin Crossab8d1382023-07-14 17:23:41 +0000360 linkDeps = append(linkDeps, sharedDeps...)
361 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700362 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700363 if a.isLibrary {
364 linkFlags = append(linkFlags, "--static-lib")
365 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700366
Colin Cross039d8df2023-06-20 22:40:02 -0700367 if a.isLibrary && a.useResourceProcessorBusyBox() {
368 // When building an android_library using ResourceProcessorBusyBox the resources are merged into
369 // package-res.apk with --merge-only, but --no-static-lib-packages is not used so that R.txt only
370 // contains resources from this library.
371 linkFlags = append(linkFlags, "--merge-only")
372 } else {
373 // When building and app or when building an android_library without ResourceProcessorBusyBox
374 // --no-static-lib-packages is used to put all the resources into the app. If ResourceProcessorBusyBox
375 // is used then the app's R.txt will be post-processed along with the R.txt files from dependencies to
376 // sort resources into the right packages in R.class.
377 linkFlags = append(linkFlags, "--no-static-lib-packages")
378 }
379
Colin Crossa97c5d32018-03-28 14:58:31 -0700380 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossa97c5d32018-03-28 14:58:31 -0700381 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
382 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700383 // This file isn't used by Soong, but is generated for exporting
384 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Cross039d8df2023-06-20 22:40:02 -0700385 var transitiveRJars android.Paths
Colin Crossf3b7bad2023-08-02 15:49:00 -0700386 var srcJar android.WritablePath
Colin Crossa97c5d32018-03-28 14:58:31 -0700387
Colin Cross4aaa84a2018-08-21 15:14:37 -0700388 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700389 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700390 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700391 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700392 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700393
Colin Crossa592e3e2019-02-19 16:59:53 -0800394 for i, zip := range resZips {
395 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700396 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800397 compiledResDirs = append(compiledResDirs, android.Paths{flata})
398 }
399
Colin Cross4aaa84a2018-08-21 15:14:37 -0700400 var compiledRes, compiledOverlay android.Paths
401
Colin Crossab8d1382023-07-14 17:23:41 +0000402 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
403 // of transitiveStaticLibs.
404 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
405
Colin Cross039d8df2023-06-20 22:40:02 -0700406 if a.isLibrary && a.useResourceProcessorBusyBox() {
407 // When building an android_library with ResourceProcessorBusyBox enabled treat static library dependencies
408 // as imports. The resources from dependencies will not be merged into this module's package-res.apk, and
409 // instead modules depending on this module will reference package-res.apk from all transitive static
410 // dependencies.
411 for _, staticDep := range staticDeps {
412 linkDeps = append(linkDeps, staticDep.resPackage)
413 linkFlags = append(linkFlags, "-I "+staticDep.resPackage.String())
414 if staticDep.usedResourceProcessor {
415 transitiveRJars = append(transitiveRJars, staticDep.rJar)
416 }
417 }
418 } else {
419 // When building an app or building a library without ResourceProcessorBusyBox enabled all static
420 // dependencies are compiled into this module's package-res.apk as overlays.
421 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
422 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700423
Colin Crossbec85302019-02-13 13:15:46 -0800424 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700425 // If we are using static android libraries, every source file becomes an overlay.
426 // This is to emulate old AAPT behavior which simulated library support.
427 for _, compiledResDir := range compiledResDirs {
428 compiledOverlay = append(compiledOverlay, compiledResDir...)
429 }
Colin Crossbec85302019-02-13 13:15:46 -0800430 } else if a.isLibrary {
431 // Otherwise, for a static library we treat all the resources equally with no overlay.
432 for _, compiledResDir := range compiledResDirs {
433 compiledRes = append(compiledRes, compiledResDir...)
434 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700435 } else if len(compiledResDirs) > 0 {
436 // Without static libraries, the first directory is our directory, which can then be
437 // overlaid by the rest.
438 compiledRes = append(compiledRes, compiledResDirs[0]...)
439 for _, compiledResDir := range compiledResDirs[1:] {
440 compiledOverlay = append(compiledOverlay, compiledResDir...)
441 }
442 }
443
Colin Crossa97c5d32018-03-28 14:58:31 -0700444 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700445 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700446 }
447
Colin Crosse560c4a2019-03-19 16:03:11 -0700448 var splitPackages android.WritablePaths
449 var splits []split
450
451 for _, s := range a.splitNames {
452 suffix := strings.Replace(s, ",", "_", -1)
453 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
454 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
455 splitPackages = append(splitPackages, path)
456 splits = append(splits, split{
457 name: s,
458 suffix: suffix,
459 path: path,
460 })
461 }
462
Colin Crossf3b7bad2023-08-02 15:49:00 -0700463 if !a.useResourceProcessorBusyBox() {
464 // the subdir "android" is required to be filtered by package names
465 srcJar = android.PathForModuleGen(ctx, "android", "R.srcjar")
466 }
467
Colin Crossab8d1382023-07-14 17:23:41 +0000468 // No need to specify assets from dependencies to aapt2Link for libraries, all transitive assets will be
469 // provided to the final app aapt2Link step.
470 var transitiveAssets android.Paths
471 if !a.isLibrary {
472 transitiveAssets = android.ReverseSliceInPlace(staticDeps.assets())
473 }
Colin Crossf3b7bad2023-08-02 15:49:00 -0700474 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt,
Colin Crossab8d1382023-07-14 17:23:41 +0000475 linkFlags, linkDeps, compiledRes, compiledOverlay, transitiveAssets, splitPackages)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800476 // Extract assets from the resource package output so that they can be used later in aapt2link
477 // for modules that depend on this one.
Colin Crossab8d1382023-07-14 17:23:41 +0000478 if android.PrefixInList(linkFlags, "-A ") {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800479 assets := android.PathForModuleOut(ctx, "assets.zip")
480 ctx.Build(pctx, android.BuildParams{
481 Rule: extractAssetsRule,
482 Input: packageRes,
483 Output: assets,
484 Description: "extract assets from built resource file",
485 })
486 a.assetPackage = android.OptionalPathForPath(assets)
487 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700488
Colin Cross039d8df2023-06-20 22:40:02 -0700489 if a.useResourceProcessorBusyBox() {
490 rJar := android.PathForModuleOut(ctx, "busybox/R.jar")
491 resourceProcessorBusyBoxGenerateBinaryR(ctx, rTxt, a.mergedManifestFile, rJar, staticDeps, a.isLibrary)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700492 aapt2ExtractExtraPackages(ctx, extraPackages, rJar)
Colin Cross039d8df2023-06-20 22:40:02 -0700493 transitiveRJars = append(transitiveRJars, rJar)
494 a.rJar = rJar
Colin Crossf3b7bad2023-08-02 15:49:00 -0700495 } else {
496 aapt2ExtractExtraPackages(ctx, extraPackages, srcJar)
Colin Cross039d8df2023-06-20 22:40:02 -0700497 }
498
Colin Crossa97c5d32018-03-28 14:58:31 -0700499 a.aaptSrcJar = srcJar
Colin Cross039d8df2023-06-20 22:40:02 -0700500 a.transitiveAaptRJars = transitiveRJars
501 a.transitiveAaptResourcePackages = staticDeps.resPackages()
Colin Crossa97c5d32018-03-28 14:58:31 -0700502 a.exportPackage = packageRes
503 a.manifestPath = manifestPath
504 a.proguardOptionsFile = proguardOptionsFile
Colin Cross66f78822018-05-02 12:58:28 -0700505 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700506 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700507 a.splits = splits
Colin Crossab8d1382023-07-14 17:23:41 +0000508 a.resourcesNodesDepSet = android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL).
509 Direct(&resourcesNode{
510 resPackage: a.exportPackage,
511 manifest: a.manifestPath,
512 additionalManifests: additionalManifests,
Colin Cross039d8df2023-06-20 22:40:02 -0700513 rTxt: a.rTxt,
514 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +0000515 assets: a.assetPackage,
Colin Cross039d8df2023-06-20 22:40:02 -0700516
517 usedResourceProcessor: a.useResourceProcessorBusyBox(),
Colin Crossab8d1382023-07-14 17:23:41 +0000518 }).
519 Transitive(staticResourcesNodesDepSet).Build()
520 a.rroDirsDepSet = android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL).
521 Direct(rroDirs...).
522 Transitive(staticRRODirsDepSet).Build()
523 a.manifestsDepSet = android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
524 Direct(a.manifestPath).
525 DirectSlice(additionalManifests).
526 Transitive(staticManifestsDepSet).Build()
527}
528
Colin Cross039d8df2023-06-20 22:40:02 -0700529var resourceProcessorBusyBox = pctx.AndroidStaticRule("resourceProcessorBusyBox",
530 blueprint.RuleParams{
531 Command: "${config.JavaCmd} -cp ${config.ResourceProcessorBusyBox} " +
532 "com.google.devtools.build.android.ResourceProcessorBusyBox --tool=GENERATE_BINARY_R -- @${out}.args && " +
533 "if cmp -s ${out}.tmp ${out} ; then rm ${out}.tmp ; else mv ${out}.tmp ${out}; fi",
534 CommandDeps: []string{"${config.ResourceProcessorBusyBox}"},
535 Rspfile: "${out}.args",
536 RspfileContent: "--primaryRTxt ${rTxt} --primaryManifest ${manifest} --classJarOutput ${out}.tmp ${args}",
537 Restat: true,
538 }, "rTxt", "manifest", "args")
539
540// resourceProcessorBusyBoxGenerateBinaryR converts the R.txt file produced by aapt2 into R.class files
541// using Bazel's ResourceProcessorBusyBox tool, which is faster than compiling the R.java files and
542// supports producing classes for static dependencies that only include resources from that dependency.
543func resourceProcessorBusyBoxGenerateBinaryR(ctx android.ModuleContext, rTxt, manifest android.Path,
544 rJar android.WritablePath, transitiveDeps transitiveAarDeps, isLibrary bool) {
545
546 var args []string
547 var deps android.Paths
548
549 if !isLibrary {
550 // When compiling an app, pass all R.txt and AndroidManifest.xml from transitive static library dependencies
551 // to ResourceProcessorBusyBox so that it can regenerate R.class files with the final resource IDs for each
552 // package.
553 args, deps = transitiveDeps.resourceProcessorDeps()
554 } else {
555 // When compiling a library don't pass any dependencies as it only needs to generate an R.class file for this
556 // library. Pass --finalFields=false so that the R.class file contains non-final fields so they don't get
557 // inlined into the library before the final IDs are assigned during app compilation.
558 args = append(args, "--finalFields=false")
559 }
560
561 deps = append(deps, rTxt, manifest)
562
563 ctx.Build(pctx, android.BuildParams{
564 Rule: resourceProcessorBusyBox,
565 Output: rJar,
566 Implicits: deps,
567 Description: "ResourceProcessorBusyBox",
568 Args: map[string]string{
569 "rTxt": rTxt.String(),
570 "manifest": manifest.String(),
571 "args": strings.Join(args, " "),
572 },
573 })
574}
575
Colin Crossab8d1382023-07-14 17:23:41 +0000576type resourcesNode struct {
577 resPackage android.Path
578 manifest android.Path
579 additionalManifests android.Paths
Colin Cross039d8df2023-06-20 22:40:02 -0700580 rTxt android.Path
581 rJar android.Path
Colin Crossab8d1382023-07-14 17:23:41 +0000582 assets android.OptionalPath
Colin Cross039d8df2023-06-20 22:40:02 -0700583
584 usedResourceProcessor bool
Colin Crossab8d1382023-07-14 17:23:41 +0000585}
586
587type transitiveAarDeps []*resourcesNode
588
589func (t transitiveAarDeps) resPackages() android.Paths {
Colin Cross039d8df2023-06-20 22:40:02 -0700590 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000591 for _, dep := range t {
592 paths = append(paths, dep.resPackage)
593 }
Colin Cross039d8df2023-06-20 22:40:02 -0700594 return paths
Colin Crossab8d1382023-07-14 17:23:41 +0000595}
596
597func (t transitiveAarDeps) manifests() android.Paths {
Colin Cross039d8df2023-06-20 22:40:02 -0700598 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000599 for _, dep := range t {
600 paths = append(paths, dep.manifest)
601 paths = append(paths, dep.additionalManifests...)
602 }
Colin Cross039d8df2023-06-20 22:40:02 -0700603 return paths
604}
605
606func (t transitiveAarDeps) resourceProcessorDeps() (args []string, deps android.Paths) {
607 for _, dep := range t {
608 args = append(args, "--library="+dep.rTxt.String()+","+dep.manifest.String())
609 deps = append(deps, dep.rTxt, dep.manifest)
610 }
611 return args, deps
Colin Crossab8d1382023-07-14 17:23:41 +0000612}
613
614func (t transitiveAarDeps) assets() android.Paths {
Colin Cross039d8df2023-06-20 22:40:02 -0700615 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000616 for _, dep := range t {
617 if dep.assets.Valid() {
618 paths = append(paths, dep.assets.Path())
619 }
620 }
621 return paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700622}
623
624// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900625func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Colin Crossab8d1382023-07-14 17:23:41 +0000626 staticResourcesNodes *android.DepSet[*resourcesNode], staticRRODirs *android.DepSet[rroDir],
627 staticManifests *android.DepSet[android.Path], sharedLibs android.Paths, flags []string) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700628
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100629 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000630 // Not all callers need to compute class loader context, those who don't just pass nil.
631 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100632 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000633 }
634
Colin Cross83bb3162018-06-25 15:48:06 -0700635 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700636 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700637 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700638 }
639
Colin Crossab8d1382023-07-14 17:23:41 +0000640 var resourcesNodeDepSets []*android.DepSet[*resourcesNode]
641 rroDirsDepSetBuilder := android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL)
642 manifestsDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
643
Colin Crossa97c5d32018-03-28 14:58:31 -0700644 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000645 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000646
Colin Crossa97c5d32018-03-28 14:58:31 -0700647 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700648 aarDep, _ := module.(AndroidLibraryDependency)
649 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700650 exportPackage = aarDep.ExportPackage()
651 }
652
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000653 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700654 case instrumentationForTag:
655 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400656 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700657 if exportPackage != nil {
658 sharedLibs = append(sharedLibs, exportPackage)
659 }
Colin Cross5446e882019-05-22 10:46:27 -0700660 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700661 if exportPackage != nil {
662 sharedLibs = append(sharedLibs, exportPackage)
663 }
664 case staticLibTag:
665 if exportPackage != nil {
Colin Crossab8d1382023-07-14 17:23:41 +0000666 resourcesNodeDepSets = append(resourcesNodeDepSets, aarDep.ResourcesNodeDepSet())
667 rroDirsDepSetBuilder.Transitive(aarDep.RRODirsDepSet())
668 manifestsDepSetBuilder.Transitive(aarDep.ManifestsDepSet())
Colin Crossa97c5d32018-03-28 14:58:31 -0700669 }
670 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000671
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000672 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700673 })
674
Colin Crossab8d1382023-07-14 17:23:41 +0000675 // AAPT2 overlays are in lowest to highest priority order, the topological order will be reversed later.
676 // Reverse the dependency order now going into the depset so that it comes out in order after the second
677 // reverse later.
678 // NOTE: this is legacy and probably incorrect behavior, for most other cases (e.g. conflicting classes in
679 // dependencies) the highest priority dependency is listed first, but for resources the highest priority
680 // dependency has to be listed last.
681 staticResourcesNodes = android.NewDepSet(android.TOPOLOGICAL, nil,
682 android.ReverseSliceInPlace(resourcesNodeDepSets))
Colin Crossa97c5d32018-03-28 14:58:31 -0700683
Colin Crossab8d1382023-07-14 17:23:41 +0000684 staticRRODirs = rroDirsDepSetBuilder.Build()
685 staticManifests = manifestsDepSetBuilder.Build()
686
687 if len(staticResourcesNodes.ToList()) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700688 flags = append(flags, "--auto-add-overlay")
689 }
690
691 for _, sharedLib := range sharedLibs {
692 flags = append(flags, "-I "+sharedLib.String())
693 }
694
Colin Crossab8d1382023-07-14 17:23:41 +0000695 return staticResourcesNodes, staticRRODirs, staticManifests, sharedLibs, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700696}
697
698type AndroidLibrary struct {
699 Library
700 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500701 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700702
703 androidLibraryProperties androidLibraryProperties
704
705 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700706}
707
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000708var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
709
710// For OutputFileProducer interface
711func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
712 switch tag {
713 case ".aar":
714 return []android.Path{a.aarFile}, nil
715 default:
716 return a.Library.OutputFiles(tag)
717 }
718}
719
Colin Crossa97c5d32018-03-28 14:58:31 -0700720var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
721
722func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
723 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900724 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100725 if sdkDep.hasFrameworkLibs() {
726 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700727 }
Colin Cross4a80a152022-12-21 21:51:52 -0800728 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700729}
730
731func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800732 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100733 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000734 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700735
Colin Cross56a83212020-09-15 18:30:11 -0700736 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
737
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000738 a.stem = proptools.StringDefault(a.overridableDeviceProperties.Stem, ctx.ModuleName())
739
Colin Cross039d8df2023-06-20 22:40:02 -0700740 ctx.CheckbuildFile(a.aapt.proguardOptionsFile)
741 ctx.CheckbuildFile(a.aapt.exportPackage)
Colin Cross039d8df2023-06-20 22:40:02 -0700742 if a.useResourceProcessorBusyBox() {
743 ctx.CheckbuildFile(a.aapt.rJar)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700744 } else {
745 ctx.CheckbuildFile(a.aapt.aaptSrcJar)
Colin Cross039d8df2023-06-20 22:40:02 -0700746 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700747
748 // apps manifests are handled by aapt, don't let Module see them
749 a.properties.Manifest = nil
750
Colin Cross014489c2020-06-02 20:09:13 -0700751 a.linter.mergedManifest = a.aapt.mergedManifestFile
752 a.linter.manifest = a.aapt.manifestPath
753 a.linter.resources = a.aapt.resourceFiles
754
Colin Crossa97c5d32018-03-28 14:58:31 -0700755 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
756 a.proguardOptionsFile)
757
Colin Cross039d8df2023-06-20 22:40:02 -0700758 var extraSrcJars android.Paths
759 var extraCombinedJars android.Paths
760 var extraClasspathJars android.Paths
761 if a.useResourceProcessorBusyBox() {
762 // When building a library with ResourceProcessorBusyBox enabled ResourceProcessorBusyBox for this
763 // library and each of the transitive static android_library dependencies has already created an
764 // R.class file for the appropriate package. Add all of those R.class files to the classpath.
765 extraClasspathJars = a.transitiveAaptRJars
766 } else {
767 // When building a library without ResourceProcessorBusyBox the aapt2 rule creates R.srcjar containing
768 // R.java files for the library's package and the packages from all transitive static android_library
769 // dependencies. Compile the srcjar alongside the rest of the sources.
770 extraSrcJars = android.Paths{a.aapt.aaptSrcJar}
771 }
772
773 a.Module.compile(ctx, extraSrcJars, extraClasspathJars, extraCombinedJars)
Colin Crossa97c5d32018-03-28 14:58:31 -0700774
Colin Crossf57c5782019-01-25 13:20:38 -0800775 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700776 var res android.Paths
777 if a.androidLibraryProperties.BuildAAR {
778 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
779 ctx.CheckbuildFile(a.aarFile)
780 }
Colin Cross89c31582018-04-30 15:55:11 -0700781
Cole Faust9a631312020-10-22 21:05:24 +0000782 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
783 android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
Colin Crossab8d1382023-07-14 17:23:41 +0000784
Colin Cross89c31582018-04-30 15:55:11 -0700785 ctx.VisitDirectDeps(func(m android.Module) {
Jared Duke5979b302022-12-19 21:08:39 +0000786 if ctx.OtherModuleDependencyTag(m) == staticLibTag {
787 if lib, ok := m.(LibraryDependency); ok {
788 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
789 }
Colin Cross89c31582018-04-30 15:55:11 -0700790 }
791 })
Colin Cross89c31582018-04-30 15:55:11 -0700792 a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
Sam Delmerico82602492022-06-10 17:05:42 +0000793
794 prebuiltJniPackages := android.Paths{}
795 ctx.VisitDirectDeps(func(module android.Module) {
796 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
797 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
798 }
799 })
800 if len(prebuiltJniPackages) > 0 {
801 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
802 JniPackages: prebuiltJniPackages,
803 })
804 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700805}
806
Colin Cross1b16b0e2019-02-12 14:41:32 -0800807// android_library builds and links sources into a `.jar` file for the device along with Android resources.
808//
809// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000810// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800811// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
812// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700813func AndroidLibraryFactory() android.Module {
814 module := &AndroidLibrary{}
815
Colin Crossce6734e2020-06-15 16:09:53 -0700816 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700817 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700818 &module.aaptProperties,
819 &module.androidLibraryProperties)
820
821 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700822 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700823
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900824 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700825 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500826 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700827 return module
828}
829
Colin Crossfabb6082018-02-20 17:22:23 -0800830//
831// AAR (android library) prebuilts
832//
Colin Crossfabb6082018-02-20 17:22:23 -0800833
Vinh Trance0781f2022-04-13 01:30:44 +0000834// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800835type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000836 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800837 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000838 // If not blank, set to the version of the sdk to compile against.
839 // Defaults to private.
840 // Values are of one of the following forms:
841 // 1) numerical API level, "current", "none", or "core_platform"
842 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
843 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
844 // If the SDK kind is empty, it will be set to public
845 Sdk_version *string
846 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
847 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700848 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000849 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700850 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000851 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
852 Libs []string
853 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700854 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000855 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
856 // will be passed transitively through android_libraries to an android_app.
857 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
858 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800859}
860
861type AARImport struct {
862 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700863 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900864 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500865 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800866 prebuilt android.Prebuilt
867
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900868 // Functionality common to Module and Import.
869 embeddableInModuleAndImport
870
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500871 providesTransitiveHeaderJars
872
Colin Crossfabb6082018-02-20 17:22:23 -0800873 properties AARImportProperties
874
Colin Cross039d8df2023-06-20 22:40:02 -0700875 classpathFile android.WritablePath
876 proguardFlags android.WritablePath
877 exportPackage android.WritablePath
878 transitiveAaptResourcePackages android.Paths
879 extraAaptPackagesFile android.WritablePath
880 manifest android.WritablePath
881 assetsPackage android.WritablePath
882 rTxt android.WritablePath
883 rJar android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700884
Colin Crossab8d1382023-07-14 17:23:41 +0000885 resourcesNodesDepSet *android.DepSet[*resourcesNode]
886 manifestsDepSet *android.DepSet[android.Path]
Colin Cross56a83212020-09-15 18:30:11 -0700887
888 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000889
Sam Delmerico82602492022-06-10 17:05:42 +0000890 aarPath android.Path
891 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900892
893 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000894 minSdkVersion android.ApiLevel
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000895}
896
897var _ android.OutputFileProducer = (*AARImport)(nil)
898
899// For OutputFileProducer interface
900func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
901 switch tag {
902 case ".aar":
903 return []android.Path{a.aarPath}, nil
904 case "":
905 return []android.Path{a.classpathFile}, nil
906 default:
907 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
908 }
Colin Crossfabb6082018-02-20 17:22:23 -0800909}
910
Jiyong Park92315372021-04-02 08:45:46 +0900911func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
912 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700913}
914
Jiyong Parkf1691d22021-03-29 20:11:58 +0900915func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100916 return ""
917}
918
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000919func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Colin Cross479884c2018-07-10 13:39:30 -0700920 if a.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000921 return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700922 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000923 return a.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -0700924}
925
Spandan Dasa26eda72023-03-02 00:56:06 +0000926func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
927 return android.SdkSpecFrom(ctx, "").ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000928}
929
Spandan Dasca70fc42023-03-01 23:38:49 +0000930func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
931 return a.SdkVersion(ctx).ApiLevel
Dan Willemsen419290a2018-10-31 15:28:47 -0700932}
933
Colin Cross1e743852019-10-28 11:37:20 -0700934func (a *AARImport) javaVersion() string {
935 return ""
936}
937
Colin Crossa97c5d32018-03-28 14:58:31 -0700938var _ AndroidLibraryDependency = (*AARImport)(nil)
939
940func (a *AARImport) ExportPackage() android.Path {
941 return a.exportPackage
942}
Colin Cross89c31582018-04-30 15:55:11 -0700943func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
944 return android.Paths{a.proguardFlags}
945}
946
Colin Crossab8d1382023-07-14 17:23:41 +0000947func (a *AARImport) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
948 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800949}
950
Colin Crossab8d1382023-07-14 17:23:41 +0000951func (a *AARImport) RRODirsDepSet() *android.DepSet[rroDir] {
952 return android.NewDepSet[rroDir](android.TOPOLOGICAL, nil, nil)
Colin Cross66f78822018-05-02 12:58:28 -0700953}
954
Colin Crossab8d1382023-07-14 17:23:41 +0000955func (a *AARImport) ManifestsDepSet() *android.DepSet[android.Path] {
956 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800957}
958
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700959// RRO enforcement is not available on aar_import since its RRO dirs are not
960// exported.
961func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
962}
963
964// RRO enforcement is not available on aar_import since its RRO dirs are not
965// exported.
966func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
967 return false
968}
969
Colin Crossfabb6082018-02-20 17:22:23 -0800970func (a *AARImport) Prebuilt() *android.Prebuilt {
971 return &a.prebuilt
972}
973
974func (a *AARImport) Name() string {
975 return a.prebuilt.Name(a.ModuleBase.Name())
976}
977
Jiyong Park618922e2020-01-08 13:35:43 +0900978func (a *AARImport) JacocoReportClassesFile() android.Path {
979 return nil
980}
981
Colin Crossfabb6082018-02-20 17:22:23 -0800982func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900983 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900984 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700985 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700986 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800987 }
988 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700989
Colin Cross42d48b72018-08-29 14:10:52 -0700990 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
991 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800992}
993
Sam Delmerico82602492022-06-10 17:05:42 +0000994type JniPackageInfo struct {
995 // List of zip files containing JNI libraries
996 // Zip files should have directory structure jni/<arch>/*.so
997 JniPackages android.Paths
998}
999
1000var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
1001
1002// Unzip an AAR and extract the JNI libs for $archString.
1003var extractJNI = pctx.AndroidStaticRule("extractJNI",
1004 blueprint.RuleParams{
1005 Command: `rm -rf $out $outDir && touch $out && ` +
1006 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
1007 `jni_files=$$(find $outDir/jni -type f) && ` +
1008 // print error message if there are no JNI libs for this arch
1009 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
1010 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
1011 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
1012 CommandDeps: []string{"${config.SoongZipCmd}"},
1013 },
1014 "outDir", "archString")
1015
Colin Crossfabb6082018-02-20 17:22:23 -08001016// 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 -07001017// 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 -08001018var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
1019 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -07001020 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001021 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001022 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001023 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001024 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -08001025 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001026 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -08001027
1028func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1029 if len(a.properties.Aars) != 1 {
1030 ctx.PropertyErrorf("aars", "exactly one aar is required")
1031 return
1032 }
1033
Jiyong Park92315372021-04-02 08:45:46 +09001034 a.sdkVersion = a.SdkVersion(ctx)
1035 a.minSdkVersion = a.MinSdkVersion(ctx)
1036
Colin Cross56a83212020-09-15 18:30:11 -07001037 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
1038
Nan Zhang4c819fb2018-08-27 18:31:46 -07001039 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001040 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
1041
Colin Cross1001a792019-03-21 22:21:39 -07001042 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001043 inputFile := a.aarPath
1044 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
1045 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -07001046 }
Colin Crossfabb6082018-02-20 17:22:23 -08001047
1048 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -07001049 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Crossfabb6082018-02-20 17:22:23 -08001050 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
Colin Cross10f7c4a2018-05-23 10:59:28 -07001051 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Colin Cross039d8df2023-06-20 22:40:02 -07001052 aarRTxt := extractedAARDir.Join(ctx, "R.txt")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001053 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Colin Crossfabb6082018-02-20 17:22:23 -08001054
1055 ctx.Build(pctx, android.BuildParams{
1056 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001057 Input: a.aarPath,
Colin Cross039d8df2023-06-20 22:40:02 -07001058 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage, aarRTxt},
Colin Crossfabb6082018-02-20 17:22:23 -08001059 Description: "unzip AAR",
1060 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -07001061 "outDir": extractedAARDir.String(),
1062 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001063 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -08001064 },
1065 })
1066
Colin Crossa0ba2f52019-06-22 12:59:27 -07001067 // Always set --pseudo-localize, it will be stripped out later for release
1068 // builds that don't want it.
1069 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -08001070 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -08001071 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001072 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -08001073
1074 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossfabb6082018-02-20 17:22:23 -08001075 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Cross039d8df2023-06-20 22:40:02 -07001076 a.rTxt = android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -07001077 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -08001078
1079 var linkDeps android.Paths
1080
1081 linkFlags := []string{
1082 "--static-lib",
Colin Cross039d8df2023-06-20 22:40:02 -07001083 "--merge-only",
Colin Crossfabb6082018-02-20 17:22:23 -08001084 "--auto-add-overlay",
1085 }
1086
Colin Cross10f7c4a2018-05-23 10:59:28 -07001087 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
1088 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -08001089
Colin Crossab8d1382023-07-14 17:23:41 +00001090 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedLibs, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +09001091 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -07001092
Colin Crossab8d1382023-07-14 17:23:41 +00001093 _ = staticRRODirsDepSet
1094 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
Colin Crossfabb6082018-02-20 17:22:23 -08001095
Colin Crossab8d1382023-07-14 17:23:41 +00001096 linkDeps = append(linkDeps, sharedLibs...)
Colin Cross039d8df2023-06-20 22:40:02 -07001097 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -07001098 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -08001099
Colin Cross039d8df2023-06-20 22:40:02 -07001100 overlayRes := android.Paths{flata}
1101
1102 // Treat static library dependencies of static libraries as imports.
1103 transitiveStaticLibs := staticDeps.resPackages()
1104 linkDeps = append(linkDeps, transitiveStaticLibs...)
1105 for _, staticLib := range transitiveStaticLibs {
1106 linkFlags = append(linkFlags, "-I "+staticLib.String())
1107 }
Colin Crossfabb6082018-02-20 17:22:23 -08001108
Colin Crossab8d1382023-07-14 17:23:41 +00001109 transitiveAssets := android.ReverseSliceInPlace(staticDeps.assets())
Colin Crossf3b7bad2023-08-02 15:49:00 -07001110 aapt2Link(ctx, a.exportPackage, nil, proguardOptionsFile, a.rTxt,
Jaewoong Jung6431ca72020-01-15 14:15:10 -08001111 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001112
Colin Cross039d8df2023-06-20 22:40:02 -07001113 a.rJar = android.PathForModuleOut(ctx, "busybox/R.jar")
1114 resourceProcessorBusyBoxGenerateBinaryR(ctx, a.rTxt, a.manifest, a.rJar, nil, true)
1115
Colin Crossf3b7bad2023-08-02 15:49:00 -07001116 aapt2ExtractExtraPackages(ctx, a.extraAaptPackagesFile, a.rJar)
1117
Colin Crossab8d1382023-07-14 17:23:41 +00001118 resourcesNodesDepSetBuilder := android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL)
1119 resourcesNodesDepSetBuilder.Direct(&resourcesNode{
1120 resPackage: a.exportPackage,
1121 manifest: a.manifest,
Colin Cross039d8df2023-06-20 22:40:02 -07001122 rTxt: a.rTxt,
1123 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +00001124 assets: android.OptionalPathForPath(a.assetsPackage),
Colin Cross039d8df2023-06-20 22:40:02 -07001125
1126 usedResourceProcessor: true,
Colin Crossab8d1382023-07-14 17:23:41 +00001127 })
1128 resourcesNodesDepSetBuilder.Transitive(staticResourcesNodesDepSet)
1129 a.resourcesNodesDepSet = resourcesNodesDepSetBuilder.Build()
1130
1131 manifestDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(a.manifest)
1132 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
1133 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
1134 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
1135 // android_library_import modules. If this is fixed, AndroidLibraryDependency.ManifestsDepSet can be dropped
1136 // completely in favor of AndroidLibraryDependency.ResourceNodesDepSet.manifest
1137 //manifestDepSetBuilder.Transitive(transitiveStaticDeps.manifests)
1138 _ = staticManifestsDepSet
1139 a.manifestsDepSet = manifestDepSetBuilder.Build()
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001140
Colin Cross039d8df2023-06-20 22:40:02 -07001141 a.transitiveAaptResourcePackages = staticDeps.resPackages()
1142
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001143 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -08001144 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1145 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001146 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
1147 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08001148 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
1149 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001150 // TransitiveAconfigFiles: // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08001151 })
Sam Delmerico82602492022-06-10 17:05:42 +00001152
1153 if proptools.Bool(a.properties.Extract_jni) {
1154 for _, t := range ctx.MultiTargets() {
1155 arch := t.Arch.Abi[0]
1156 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
1157 a.jniPackages = append(a.jniPackages, path)
1158
1159 outDir := android.PathForModuleOut(ctx, "aarForJni")
1160 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
1161 ctx.Build(pctx, android.BuildParams{
1162 Rule: extractJNI,
1163 Input: aarPath,
1164 Outputs: android.WritablePaths{path},
1165 Description: "extract JNI from AAR",
1166 Args: map[string]string{
1167 "outDir": outDir.String(),
1168 "archString": arch,
1169 },
1170 })
1171 }
1172
1173 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
1174 JniPackages: a.jniPackages,
1175 })
1176 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001177}
Colin Crossfabb6082018-02-20 17:22:23 -08001178
1179func (a *AARImport) HeaderJars() android.Paths {
1180 return android.Paths{a.classpathFile}
1181}
1182
Colin Cross331a1212018-08-15 20:40:52 -07001183func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
1184 return android.Paths{a.classpathFile}
1185}
1186
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +00001187func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -08001188 return nil
1189}
1190
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001191func (a *AARImport) DexJarInstallPath() android.Path {
1192 return nil
1193}
1194
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001195func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +09001196 return nil
1197}
1198
Jiyong Park45bf82e2020-12-15 22:29:02 +09001199var _ android.ApexModule = (*AARImport)(nil)
1200
1201// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001202func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1203 return a.depIsInSameApex(ctx, dep)
1204}
1205
Jiyong Park45bf82e2020-12-15 22:29:02 +09001206// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001207func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1208 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001209 return nil
1210}
1211
Sam Delmericoaf8bb702022-07-25 15:39:32 -04001212var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001213
Colin Cross1b16b0e2019-02-12 14:41:32 -08001214// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
1215//
1216// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
1217// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -08001218func AARImportFactory() android.Module {
1219 module := &AARImport{}
1220
1221 module.AddProperties(&module.properties)
1222
1223 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001224 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +00001225 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001226 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -08001227 return module
1228}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001229
1230type bazelAapt struct {
1231 Manifest bazel.Label
1232 Resource_files bazel.LabelListAttribute
1233}
1234
1235type bazelAndroidLibrary struct {
1236 *javaLibraryAttributes
1237 *bazelAapt
1238}
1239
1240type bazelAndroidLibraryImport struct {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001241 Aar bazel.Label
1242 Deps bazel.LabelListAttribute
1243 Exports bazel.LabelListAttribute
1244 Sdk_version bazel.StringAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001245}
1246
1247func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) *bazelAapt {
1248 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1249
1250 resourceFiles := bazel.LabelList{
1251 Includes: []bazel.Label{},
1252 }
1253 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1254 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1255 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1256 }
1257 return &bazelAapt{
1258 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1259 bazel.MakeLabelListAttribute(resourceFiles),
1260 }
1261}
1262
1263func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1264 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1265 exportableStaticLibs := []string{}
1266 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1267 for _, depName := range a.properties.Static_libs {
1268 if dep, ok := ctx.ModuleFromName(depName); ok {
1269 switch dep.(type) {
1270 case *AARImport, *Import:
1271 exportableStaticLibs = append(exportableStaticLibs, depName)
1272 }
1273 }
1274 }
1275 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1276 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1277 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1278
1279 ctx.CreateBazelTargetModule(
1280 bazel.BazelTargetModuleProperties{
1281 Rule_class: "aar_import",
Alixa381cd12023-05-10 14:49:38 +00001282 Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001283 },
1284 android.CommonAttributes{Name: name},
1285 &bazelAndroidLibraryImport{
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001286 Aar: aars.Includes[0],
1287 Deps: bazel.MakeLabelListAttribute(deps),
1288 Exports: bazel.MakeLabelListAttribute(exports),
1289 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001290 },
1291 )
1292
Alix14101de2023-01-06 03:42:07 +00001293 neverlink := true
1294 ctx.CreateBazelTargetModule(
Alix32540022023-03-16 21:06:13 +00001295 AndroidLibraryBazelTargetModuleProperties(),
Alix14101de2023-01-06 03:42:07 +00001296 android.CommonAttributes{Name: name + "-neverlink"},
1297 &bazelAndroidLibrary{
1298 javaLibraryAttributes: &javaLibraryAttributes{
1299 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1300 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001301 javaCommonAttributes: &javaCommonAttributes{
1302 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
1303 },
Alix14101de2023-01-06 03:42:07 +00001304 },
1305 },
1306 )
1307
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001308}
Alix32540022023-03-16 21:06:13 +00001309func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
1310 return bazel.BazelTargetModuleProperties{
1311 Rule_class: "android_library",
Alixa381cd12023-05-10 14:49:38 +00001312 Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
Alix32540022023-03-16 21:06:13 +00001313 }
1314}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001315
1316func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer7f375862023-08-04 16:37:42 -04001317 commonAttrs, bp2buildInfo, supported := a.convertLibraryAttrsBp2Build(ctx)
1318 if !supported {
1319 return
1320 }
1321
Alix8062f4d2022-11-14 21:38:07 +00001322 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001323
1324 deps := depLabels.Deps
1325 if !commonAttrs.Srcs.IsEmpty() {
1326 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1327 } else if !depLabels.Deps.IsEmpty() {
1328 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1329 }
Alix82fb94e2022-10-26 20:40:18 +00001330 name := a.Name()
Alix32540022023-03-16 21:06:13 +00001331 props := AndroidLibraryBazelTargetModuleProperties()
Alix82fb94e2022-10-26 20:40:18 +00001332
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001333 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001334 props,
1335 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001336 &bazelAndroidLibrary{
1337 &javaLibraryAttributes{
1338 javaCommonAttributes: commonAttrs,
1339 Deps: deps,
1340 Exports: depLabels.StaticDeps,
1341 },
1342 a.convertAaptAttrsWithBp2Build(ctx),
1343 },
1344 )
Alix82fb94e2022-10-26 20:40:18 +00001345
1346 neverlink := true
1347 ctx.CreateBazelTargetModule(
1348 props,
1349 android.CommonAttributes{Name: name + "-neverlink"},
1350 &bazelAndroidLibrary{
1351 javaLibraryAttributes: &javaLibraryAttributes{
1352 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1353 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001354 javaCommonAttributes: &javaCommonAttributes{
1355 Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
1356 Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
1357 },
Alix82fb94e2022-10-26 20:40:18 +00001358 },
1359 },
1360 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001361}