blob: 02161960307f1c4eeb9b4fbed7cdf96cb801b31d [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 {
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 Cross4eae06d2023-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 Cross4eae06d2023-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 Cross4eae06d2023-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
Colin Crossa97c5d32018-03-28 14:58:31 -0700194 // Find implicit or explicit asset and resource dirs
195 assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
196 resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
Colin Cross8a497952019-03-05 22:25:09 -0800197 resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
Colin Crossa97c5d32018-03-28 14:58:31 -0700198
Colin Crossa97c5d32018-03-28 14:58:31 -0700199 // Glob directories into lists of paths
200 for _, dir := range resourceDirs {
201 resDirs = append(resDirs, globbedResourceDir{
202 dir: dir,
203 files: androidResourceGlob(ctx, dir),
204 })
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700205 resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
Colin Crossa97c5d32018-03-28 14:58:31 -0700206 overlayDirs = append(overlayDirs, resOverlayDirs...)
207 rroDirs = append(rroDirs, resRRODirs...)
208 }
209
Colin Crossc20dc852020-11-10 12:27:45 -0800210 var assetDeps android.Paths
211 for i, dir := range assetDirs {
212 // Add a dependency on every file in the asset directory. This ensures the aapt2
213 // rule will be rerun if one of the files in the asset directory is modified.
214 assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
215
216 // Add a dependency on a file that contains a list of all the files in the asset directory.
217 // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
218 // or a file is added whose timestamp is older than the output of aapt2.
219 assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
220 androidResourceGlobList(ctx, dir, assetFileListFile)
221 assetDeps = append(assetDeps, assetFileListFile)
Colin Crossa97c5d32018-03-28 14:58:31 -0700222 }
223
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700224 assetDirStrings := assetDirs.Strings()
225 if a.noticeFile.Valid() {
226 assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
Colin Crossc20dc852020-11-10 12:27:45 -0800227 assetDeps = append(assetDeps, a.noticeFile.Path())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700228 }
229
Colin Crossa97c5d32018-03-28 14:58:31 -0700230 linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
231 linkDeps = append(linkDeps, manifestPath)
232
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700233 linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
Colin Crossc20dc852020-11-10 12:27:45 -0800234 linkDeps = append(linkDeps, assetDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700235
Spandan Das50885c02023-02-23 21:31:33 +0000236 // Returns the effective version for {min|target}_sdk_version
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000237 effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
Spandan Das50885c02023-02-23 21:31:33 +0000238 // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
239 // This is necessary for vendor modules.
240 // The effective version does not _only_ depend on {min|target}_sdk_version(level),
241 // but also on the sdk_version (kind+level)
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000242 if minSdkVersion.IsCurrent() {
Spandan Das50885c02023-02-23 21:31:33 +0000243 ret, err := sdkVersion.EffectiveVersionString(ctx)
244 if err != nil {
245 ctx.ModuleErrorf("invalid sdk_version: %s", err)
246 }
247 return ret
248 }
249 ret, err := minSdkVersion.EffectiveVersionString(ctx)
250 if err != nil {
251 ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
252 }
253 return ret
Jiyong Park6a927c42020-01-21 02:03:43 +0900254 }
Spandan Das50885c02023-02-23 21:31:33 +0000255 // SDK version flags
256 sdkVersion := sdkContext.SdkVersion(ctx)
257 minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
Colin Crossa97c5d32018-03-28 14:58:31 -0700258
Colin Cross83bb3162018-06-25 15:48:06 -0700259 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000260 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
261 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700262 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700263
Colin Crossa97c5d32018-03-28 14:58:31 -0700264 // Version code
265 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700266 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700267 }
268
269 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700270 var versionName string
271 if ctx.ModuleName() == "framework-res" {
272 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
273 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700274 // if it contains the build number. Use the PlatformVersionName instead.
275 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700276 } else {
277 versionName = ctx.Config().AppsDefaultVersionName()
278 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800279 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700280 linkFlags = append(linkFlags, "--version-name ", versionName)
281 }
282
Colin Crossa0ba2f52019-06-22 12:59:27 -0700283 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
284
285 // Always set --pseudo-localize, it will be stripped out later for release
286 // builds that don't want it.
287 compileFlags = append(compileFlags, "--pseudo-localize")
288
289 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700290}
291
Paul Duffin250e6192019-06-07 10:44:37 +0100292func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800293 if sdkDep.frameworkResModule != "" {
294 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700295 }
296}
297
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800298var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
299 blueprint.RuleParams{
300 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
301 CommandDeps: []string{"${config.Zip2ZipCmd}"},
302 })
303
Jiyong Parkf1691d22021-03-29 20:11:58 +0900304func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000305 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000306 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700307
Colin Crossab8d1382023-07-14 17:23:41 +0000308 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100309 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100310
Paul Duffin06530572022-02-03 17:54:15 +0000311 // Exclude any libraries from the supplied list.
312 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
313
Colin Cross31656952018-05-24 16:11:20 -0700314 // App manifest file
315 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
316 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
317
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000318 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000319 SdkContext: sdkContext,
320 ClassLoaderContexts: classLoaderContexts,
321 IsLibrary: a.isLibrary,
322 DefaultManifestVersion: a.defaultManifestVersion,
323 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
324 UsesNonSdkApis: a.usesNonSdkApis,
325 UseEmbeddedDex: a.useEmbeddedDex,
326 HasNoCode: a.hasNoCode,
327 LoggingParent: a.LoggingParent,
328 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000329 })
Colin Cross90c25c62019-04-19 16:22:57 -0700330
Colin Crossab8d1382023-07-14 17:23:41 +0000331 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
332
Luca Stefanifd898822019-09-10 22:13:31 +0200333 // Add additional manifest files to transitive manifests.
334 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
Colin Crossab8d1382023-07-14 17:23:41 +0000335 transitiveManifestPaths := append(android.Paths{manifestPath}, additionalManifests...)
336 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
337 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
338 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
339 // android_library_import modules. If this is fixed, staticManifestsDepSet can be dropped completely in favor of
340 // staticResourcesNodesDepSet.manifests()
341 transitiveManifestPaths = append(transitiveManifestPaths, staticManifestsDepSet.ToList()...)
Colin Cross90c25c62019-04-19 16:22:57 -0700342
Colin Crossab8d1382023-07-14 17:23:41 +0000343 if len(transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
344 a.mergedManifestFile = manifestMerger(ctx, transitiveManifestPaths[0], transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700345 if !a.isLibrary {
346 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
347 // will be propagated to the final application and merged there. The merged manifest for libraries is
348 // only passed to Make, which can't handle transitive dependencies.
349 manifestPath = a.mergedManifestFile
350 }
351 } else {
352 a.mergedManifestFile = manifestPath
353 }
Colin Cross31656952018-05-24 16:11:20 -0700354
Colin Crossa0ba2f52019-06-22 12:59:27 -0700355 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700356
357 linkFlags = append(linkFlags, libFlags...)
Colin Crossab8d1382023-07-14 17:23:41 +0000358 linkDeps = append(linkDeps, sharedDeps...)
359 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700360 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700361 if a.isLibrary {
362 linkFlags = append(linkFlags, "--static-lib")
363 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700364
Colin Cross4eae06d2023-06-20 22:40:02 -0700365 if a.isLibrary && a.useResourceProcessorBusyBox() {
366 // When building an android_library using ResourceProcessorBusyBox the resources are merged into
367 // package-res.apk with --merge-only, but --no-static-lib-packages is not used so that R.txt only
368 // contains resources from this library.
369 linkFlags = append(linkFlags, "--merge-only")
370 } else {
371 // When building and app or when building an android_library without ResourceProcessorBusyBox
372 // --no-static-lib-packages is used to put all the resources into the app. If ResourceProcessorBusyBox
373 // is used then the app's R.txt will be post-processed along with the R.txt files from dependencies to
374 // sort resources into the right packages in R.class.
375 linkFlags = append(linkFlags, "--no-static-lib-packages")
376 }
377
Colin Crossa97c5d32018-03-28 14:58:31 -0700378 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossa97c5d32018-03-28 14:58:31 -0700379 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
380 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700381 // This file isn't used by Soong, but is generated for exporting
382 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Cross4eae06d2023-06-20 22:40:02 -0700383 var transitiveRJars android.Paths
Colin Crossf3b7bad2023-08-02 15:49:00 -0700384 var srcJar android.WritablePath
Colin Crossa97c5d32018-03-28 14:58:31 -0700385
Colin Cross4aaa84a2018-08-21 15:14:37 -0700386 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700387 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700388 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700389 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700390 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700391
Colin Crossa592e3e2019-02-19 16:59:53 -0800392 for i, zip := range resZips {
393 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700394 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800395 compiledResDirs = append(compiledResDirs, android.Paths{flata})
396 }
397
Colin Cross4aaa84a2018-08-21 15:14:37 -0700398 var compiledRes, compiledOverlay android.Paths
399
Colin Crossab8d1382023-07-14 17:23:41 +0000400 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
401 // of transitiveStaticLibs.
402 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
403
Colin Cross4eae06d2023-06-20 22:40:02 -0700404 if a.isLibrary && a.useResourceProcessorBusyBox() {
405 // When building an android_library with ResourceProcessorBusyBox enabled treat static library dependencies
406 // as imports. The resources from dependencies will not be merged into this module's package-res.apk, and
407 // instead modules depending on this module will reference package-res.apk from all transitive static
408 // dependencies.
409 for _, staticDep := range staticDeps {
410 linkDeps = append(linkDeps, staticDep.resPackage)
411 linkFlags = append(linkFlags, "-I "+staticDep.resPackage.String())
412 if staticDep.usedResourceProcessor {
413 transitiveRJars = append(transitiveRJars, staticDep.rJar)
414 }
415 }
416 } else {
417 // When building an app or building a library without ResourceProcessorBusyBox enabled all static
418 // dependencies are compiled into this module's package-res.apk as overlays.
419 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
420 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700421
Colin Crossbec85302019-02-13 13:15:46 -0800422 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700423 // If we are using static android libraries, every source file becomes an overlay.
424 // This is to emulate old AAPT behavior which simulated library support.
425 for _, compiledResDir := range compiledResDirs {
426 compiledOverlay = append(compiledOverlay, compiledResDir...)
427 }
Colin Crossbec85302019-02-13 13:15:46 -0800428 } else if a.isLibrary {
429 // Otherwise, for a static library we treat all the resources equally with no overlay.
430 for _, compiledResDir := range compiledResDirs {
431 compiledRes = append(compiledRes, compiledResDir...)
432 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700433 } else if len(compiledResDirs) > 0 {
434 // Without static libraries, the first directory is our directory, which can then be
435 // overlaid by the rest.
436 compiledRes = append(compiledRes, compiledResDirs[0]...)
437 for _, compiledResDir := range compiledResDirs[1:] {
438 compiledOverlay = append(compiledOverlay, compiledResDir...)
439 }
440 }
441
Colin Crossa97c5d32018-03-28 14:58:31 -0700442 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700443 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700444 }
445
Colin Crosse560c4a2019-03-19 16:03:11 -0700446 var splitPackages android.WritablePaths
447 var splits []split
448
449 for _, s := range a.splitNames {
450 suffix := strings.Replace(s, ",", "_", -1)
451 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
452 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
453 splitPackages = append(splitPackages, path)
454 splits = append(splits, split{
455 name: s,
456 suffix: suffix,
457 path: path,
458 })
459 }
460
Colin Crossf3b7bad2023-08-02 15:49:00 -0700461 if !a.useResourceProcessorBusyBox() {
462 // the subdir "android" is required to be filtered by package names
463 srcJar = android.PathForModuleGen(ctx, "android", "R.srcjar")
464 }
465
Colin Crossab8d1382023-07-14 17:23:41 +0000466 // No need to specify assets from dependencies to aapt2Link for libraries, all transitive assets will be
467 // provided to the final app aapt2Link step.
468 var transitiveAssets android.Paths
469 if !a.isLibrary {
470 transitiveAssets = android.ReverseSliceInPlace(staticDeps.assets())
471 }
Colin Crossf3b7bad2023-08-02 15:49:00 -0700472 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt,
Colin Crossab8d1382023-07-14 17:23:41 +0000473 linkFlags, linkDeps, compiledRes, compiledOverlay, transitiveAssets, splitPackages)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800474 // Extract assets from the resource package output so that they can be used later in aapt2link
475 // for modules that depend on this one.
Colin Crossab8d1382023-07-14 17:23:41 +0000476 if android.PrefixInList(linkFlags, "-A ") {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800477 assets := android.PathForModuleOut(ctx, "assets.zip")
478 ctx.Build(pctx, android.BuildParams{
479 Rule: extractAssetsRule,
480 Input: packageRes,
481 Output: assets,
482 Description: "extract assets from built resource file",
483 })
484 a.assetPackage = android.OptionalPathForPath(assets)
485 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700486
Colin Cross4eae06d2023-06-20 22:40:02 -0700487 if a.useResourceProcessorBusyBox() {
488 rJar := android.PathForModuleOut(ctx, "busybox/R.jar")
489 resourceProcessorBusyBoxGenerateBinaryR(ctx, rTxt, a.mergedManifestFile, rJar, staticDeps, a.isLibrary)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700490 aapt2ExtractExtraPackages(ctx, extraPackages, rJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700491 transitiveRJars = append(transitiveRJars, rJar)
492 a.rJar = rJar
Colin Crossf3b7bad2023-08-02 15:49:00 -0700493 } else {
494 aapt2ExtractExtraPackages(ctx, extraPackages, srcJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700495 }
496
Colin Crossa97c5d32018-03-28 14:58:31 -0700497 a.aaptSrcJar = srcJar
Colin Cross4eae06d2023-06-20 22:40:02 -0700498 a.transitiveAaptRJars = transitiveRJars
499 a.transitiveAaptResourcePackages = staticDeps.resPackages()
Colin Crossa97c5d32018-03-28 14:58:31 -0700500 a.exportPackage = packageRes
501 a.manifestPath = manifestPath
502 a.proguardOptionsFile = proguardOptionsFile
Colin Cross66f78822018-05-02 12:58:28 -0700503 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700504 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700505 a.splits = splits
Colin Crossab8d1382023-07-14 17:23:41 +0000506 a.resourcesNodesDepSet = android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL).
507 Direct(&resourcesNode{
508 resPackage: a.exportPackage,
509 manifest: a.manifestPath,
510 additionalManifests: additionalManifests,
Colin Cross4eae06d2023-06-20 22:40:02 -0700511 rTxt: a.rTxt,
512 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +0000513 assets: a.assetPackage,
Colin Cross4eae06d2023-06-20 22:40:02 -0700514
515 usedResourceProcessor: a.useResourceProcessorBusyBox(),
Colin Crossab8d1382023-07-14 17:23:41 +0000516 }).
517 Transitive(staticResourcesNodesDepSet).Build()
518 a.rroDirsDepSet = android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL).
519 Direct(rroDirs...).
520 Transitive(staticRRODirsDepSet).Build()
521 a.manifestsDepSet = android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
522 Direct(a.manifestPath).
523 DirectSlice(additionalManifests).
524 Transitive(staticManifestsDepSet).Build()
525}
526
Colin Cross4eae06d2023-06-20 22:40:02 -0700527var resourceProcessorBusyBox = pctx.AndroidStaticRule("resourceProcessorBusyBox",
528 blueprint.RuleParams{
529 Command: "${config.JavaCmd} -cp ${config.ResourceProcessorBusyBox} " +
530 "com.google.devtools.build.android.ResourceProcessorBusyBox --tool=GENERATE_BINARY_R -- @${out}.args && " +
531 "if cmp -s ${out}.tmp ${out} ; then rm ${out}.tmp ; else mv ${out}.tmp ${out}; fi",
532 CommandDeps: []string{"${config.ResourceProcessorBusyBox}"},
533 Rspfile: "${out}.args",
534 RspfileContent: "--primaryRTxt ${rTxt} --primaryManifest ${manifest} --classJarOutput ${out}.tmp ${args}",
535 Restat: true,
536 }, "rTxt", "manifest", "args")
537
538// resourceProcessorBusyBoxGenerateBinaryR converts the R.txt file produced by aapt2 into R.class files
539// using Bazel's ResourceProcessorBusyBox tool, which is faster than compiling the R.java files and
540// supports producing classes for static dependencies that only include resources from that dependency.
541func resourceProcessorBusyBoxGenerateBinaryR(ctx android.ModuleContext, rTxt, manifest android.Path,
542 rJar android.WritablePath, transitiveDeps transitiveAarDeps, isLibrary bool) {
543
544 var args []string
545 var deps android.Paths
546
547 if !isLibrary {
548 // When compiling an app, pass all R.txt and AndroidManifest.xml from transitive static library dependencies
549 // to ResourceProcessorBusyBox so that it can regenerate R.class files with the final resource IDs for each
550 // package.
551 args, deps = transitiveDeps.resourceProcessorDeps()
552 } else {
553 // When compiling a library don't pass any dependencies as it only needs to generate an R.class file for this
554 // library. Pass --finalFields=false so that the R.class file contains non-final fields so they don't get
555 // inlined into the library before the final IDs are assigned during app compilation.
556 args = append(args, "--finalFields=false")
557 }
558
559 deps = append(deps, rTxt, manifest)
560
561 ctx.Build(pctx, android.BuildParams{
562 Rule: resourceProcessorBusyBox,
563 Output: rJar,
564 Implicits: deps,
565 Description: "ResourceProcessorBusyBox",
566 Args: map[string]string{
567 "rTxt": rTxt.String(),
568 "manifest": manifest.String(),
569 "args": strings.Join(args, " "),
570 },
571 })
572}
573
Colin Crossab8d1382023-07-14 17:23:41 +0000574type resourcesNode struct {
575 resPackage android.Path
576 manifest android.Path
577 additionalManifests android.Paths
Colin Cross4eae06d2023-06-20 22:40:02 -0700578 rTxt android.Path
579 rJar android.Path
Colin Crossab8d1382023-07-14 17:23:41 +0000580 assets android.OptionalPath
Colin Cross4eae06d2023-06-20 22:40:02 -0700581
582 usedResourceProcessor bool
Colin Crossab8d1382023-07-14 17:23:41 +0000583}
584
585type transitiveAarDeps []*resourcesNode
586
587func (t transitiveAarDeps) resPackages() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700588 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000589 for _, dep := range t {
590 paths = append(paths, dep.resPackage)
591 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700592 return paths
Colin Crossab8d1382023-07-14 17:23:41 +0000593}
594
595func (t transitiveAarDeps) manifests() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700596 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000597 for _, dep := range t {
598 paths = append(paths, dep.manifest)
599 paths = append(paths, dep.additionalManifests...)
600 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700601 return paths
602}
603
604func (t transitiveAarDeps) resourceProcessorDeps() (args []string, deps android.Paths) {
605 for _, dep := range t {
606 args = append(args, "--library="+dep.rTxt.String()+","+dep.manifest.String())
607 deps = append(deps, dep.rTxt, dep.manifest)
608 }
609 return args, deps
Colin Crossab8d1382023-07-14 17:23:41 +0000610}
611
612func (t transitiveAarDeps) assets() android.Paths {
Colin Cross4eae06d2023-06-20 22:40:02 -0700613 paths := make(android.Paths, 0, len(t))
Colin Crossab8d1382023-07-14 17:23:41 +0000614 for _, dep := range t {
615 if dep.assets.Valid() {
616 paths = append(paths, dep.assets.Path())
617 }
618 }
619 return paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700620}
621
622// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900623func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Colin Crossab8d1382023-07-14 17:23:41 +0000624 staticResourcesNodes *android.DepSet[*resourcesNode], staticRRODirs *android.DepSet[rroDir],
625 staticManifests *android.DepSet[android.Path], sharedLibs android.Paths, flags []string) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700626
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100627 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000628 // Not all callers need to compute class loader context, those who don't just pass nil.
629 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100630 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000631 }
632
Colin Cross83bb3162018-06-25 15:48:06 -0700633 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700634 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700635 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700636 }
637
Colin Crossab8d1382023-07-14 17:23:41 +0000638 var resourcesNodeDepSets []*android.DepSet[*resourcesNode]
639 rroDirsDepSetBuilder := android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL)
640 manifestsDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
641
Colin Crossa97c5d32018-03-28 14:58:31 -0700642 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000643 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000644
Colin Crossa97c5d32018-03-28 14:58:31 -0700645 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700646 aarDep, _ := module.(AndroidLibraryDependency)
647 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700648 exportPackage = aarDep.ExportPackage()
649 }
650
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000651 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700652 case instrumentationForTag:
653 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400654 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700655 if exportPackage != nil {
656 sharedLibs = append(sharedLibs, exportPackage)
657 }
Colin Cross5446e882019-05-22 10:46:27 -0700658 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700659 if exportPackage != nil {
660 sharedLibs = append(sharedLibs, exportPackage)
661 }
662 case staticLibTag:
663 if exportPackage != nil {
Colin Crossab8d1382023-07-14 17:23:41 +0000664 resourcesNodeDepSets = append(resourcesNodeDepSets, aarDep.ResourcesNodeDepSet())
665 rroDirsDepSetBuilder.Transitive(aarDep.RRODirsDepSet())
666 manifestsDepSetBuilder.Transitive(aarDep.ManifestsDepSet())
Colin Crossa97c5d32018-03-28 14:58:31 -0700667 }
668 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000669
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000670 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700671 })
672
Colin Crossab8d1382023-07-14 17:23:41 +0000673 // AAPT2 overlays are in lowest to highest priority order, the topological order will be reversed later.
674 // Reverse the dependency order now going into the depset so that it comes out in order after the second
675 // reverse later.
676 // NOTE: this is legacy and probably incorrect behavior, for most other cases (e.g. conflicting classes in
677 // dependencies) the highest priority dependency is listed first, but for resources the highest priority
678 // dependency has to be listed last.
679 staticResourcesNodes = android.NewDepSet(android.TOPOLOGICAL, nil,
680 android.ReverseSliceInPlace(resourcesNodeDepSets))
Colin Crossa97c5d32018-03-28 14:58:31 -0700681
Colin Crossab8d1382023-07-14 17:23:41 +0000682 staticRRODirs = rroDirsDepSetBuilder.Build()
683 staticManifests = manifestsDepSetBuilder.Build()
684
685 if len(staticResourcesNodes.ToList()) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700686 flags = append(flags, "--auto-add-overlay")
687 }
688
689 for _, sharedLib := range sharedLibs {
690 flags = append(flags, "-I "+sharedLib.String())
691 }
692
Colin Crossab8d1382023-07-14 17:23:41 +0000693 return staticResourcesNodes, staticRRODirs, staticManifests, sharedLibs, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700694}
695
696type AndroidLibrary struct {
697 Library
698 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500699 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700700
701 androidLibraryProperties androidLibraryProperties
702
703 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700704}
705
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000706var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
707
708// For OutputFileProducer interface
709func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
710 switch tag {
711 case ".aar":
712 return []android.Path{a.aarFile}, nil
713 default:
714 return a.Library.OutputFiles(tag)
715 }
716}
717
Colin Crossa97c5d32018-03-28 14:58:31 -0700718var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
719
720func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
721 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900722 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100723 if sdkDep.hasFrameworkLibs() {
724 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700725 }
Colin Cross4a80a152022-12-21 21:51:52 -0800726 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700727}
728
729func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800730 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100731 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000732 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700733
Colin Cross56a83212020-09-15 18:30:11 -0700734 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
735
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000736 a.stem = proptools.StringDefault(a.overridableDeviceProperties.Stem, ctx.ModuleName())
737
Colin Cross4eae06d2023-06-20 22:40:02 -0700738 ctx.CheckbuildFile(a.aapt.proguardOptionsFile)
739 ctx.CheckbuildFile(a.aapt.exportPackage)
Colin Cross4eae06d2023-06-20 22:40:02 -0700740 if a.useResourceProcessorBusyBox() {
741 ctx.CheckbuildFile(a.aapt.rJar)
Colin Crossf3b7bad2023-08-02 15:49:00 -0700742 } else {
743 ctx.CheckbuildFile(a.aapt.aaptSrcJar)
Colin Cross4eae06d2023-06-20 22:40:02 -0700744 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700745
746 // apps manifests are handled by aapt, don't let Module see them
747 a.properties.Manifest = nil
748
Colin Cross014489c2020-06-02 20:09:13 -0700749 a.linter.mergedManifest = a.aapt.mergedManifestFile
750 a.linter.manifest = a.aapt.manifestPath
751 a.linter.resources = a.aapt.resourceFiles
752
Colin Crossa97c5d32018-03-28 14:58:31 -0700753 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
754 a.proguardOptionsFile)
755
Colin Cross4eae06d2023-06-20 22:40:02 -0700756 var extraSrcJars android.Paths
757 var extraCombinedJars android.Paths
758 var extraClasspathJars android.Paths
759 if a.useResourceProcessorBusyBox() {
760 // When building a library with ResourceProcessorBusyBox enabled ResourceProcessorBusyBox for this
761 // library and each of the transitive static android_library dependencies has already created an
762 // R.class file for the appropriate package. Add all of those R.class files to the classpath.
763 extraClasspathJars = a.transitiveAaptRJars
764 } else {
765 // When building a library without ResourceProcessorBusyBox the aapt2 rule creates R.srcjar containing
766 // R.java files for the library's package and the packages from all transitive static android_library
767 // dependencies. Compile the srcjar alongside the rest of the sources.
768 extraSrcJars = android.Paths{a.aapt.aaptSrcJar}
769 }
770
771 a.Module.compile(ctx, extraSrcJars, extraClasspathJars, extraCombinedJars)
Colin Crossa97c5d32018-03-28 14:58:31 -0700772
Colin Crossf57c5782019-01-25 13:20:38 -0800773 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700774 var res android.Paths
775 if a.androidLibraryProperties.BuildAAR {
776 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
777 ctx.CheckbuildFile(a.aarFile)
778 }
Colin Cross89c31582018-04-30 15:55:11 -0700779
Sam Delmerico95d70942023-08-02 18:00:35 -0400780 proguardSpecInfo := a.collectProguardSpecInfo(ctx)
781 ctx.SetProvider(ProguardSpecInfoProvider, proguardSpecInfo)
782 a.exportedProguardFlagFiles = proguardSpecInfo.ProguardFlagsFiles.ToList()
Sam Delmerico82602492022-06-10 17:05:42 +0000783
784 prebuiltJniPackages := android.Paths{}
785 ctx.VisitDirectDeps(func(module android.Module) {
786 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
787 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
788 }
789 })
790 if len(prebuiltJniPackages) > 0 {
791 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
792 JniPackages: prebuiltJniPackages,
793 })
794 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700795}
796
Colin Cross1b16b0e2019-02-12 14:41:32 -0800797// android_library builds and links sources into a `.jar` file for the device along with Android resources.
798//
799// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000800// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800801// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
802// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700803func AndroidLibraryFactory() android.Module {
804 module := &AndroidLibrary{}
805
Colin Crossce6734e2020-06-15 16:09:53 -0700806 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700807 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700808 &module.aaptProperties,
809 &module.androidLibraryProperties)
810
811 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700812 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700813
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900814 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700815 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500816 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700817 return module
818}
819
Colin Crossfabb6082018-02-20 17:22:23 -0800820//
821// AAR (android library) prebuilts
822//
Colin Crossfabb6082018-02-20 17:22:23 -0800823
Vinh Trance0781f2022-04-13 01:30:44 +0000824// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800825type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000826 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800827 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000828 // If not blank, set to the version of the sdk to compile against.
829 // Defaults to private.
830 // Values are of one of the following forms:
831 // 1) numerical API level, "current", "none", or "core_platform"
832 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
833 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
834 // If the SDK kind is empty, it will be set to public
835 Sdk_version *string
836 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
837 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700838 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000839 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700840 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000841 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
842 Libs []string
843 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700844 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000845 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
846 // will be passed transitively through android_libraries to an android_app.
847 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
848 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800849}
850
851type AARImport struct {
852 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700853 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900854 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500855 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800856 prebuilt android.Prebuilt
857
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900858 // Functionality common to Module and Import.
859 embeddableInModuleAndImport
860
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500861 providesTransitiveHeaderJars
862
Colin Crossfabb6082018-02-20 17:22:23 -0800863 properties AARImportProperties
864
Colin Cross4eae06d2023-06-20 22:40:02 -0700865 classpathFile android.WritablePath
866 proguardFlags android.WritablePath
867 exportPackage android.WritablePath
868 transitiveAaptResourcePackages android.Paths
869 extraAaptPackagesFile android.WritablePath
870 manifest android.WritablePath
871 assetsPackage android.WritablePath
872 rTxt android.WritablePath
873 rJar android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700874
Colin Crossab8d1382023-07-14 17:23:41 +0000875 resourcesNodesDepSet *android.DepSet[*resourcesNode]
876 manifestsDepSet *android.DepSet[android.Path]
Colin Cross56a83212020-09-15 18:30:11 -0700877
878 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000879
Sam Delmerico82602492022-06-10 17:05:42 +0000880 aarPath android.Path
881 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900882
883 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000884 minSdkVersion android.ApiLevel
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000885}
886
887var _ android.OutputFileProducer = (*AARImport)(nil)
888
889// For OutputFileProducer interface
890func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
891 switch tag {
892 case ".aar":
893 return []android.Path{a.aarPath}, nil
894 case "":
895 return []android.Path{a.classpathFile}, nil
896 default:
897 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
898 }
Colin Crossfabb6082018-02-20 17:22:23 -0800899}
900
Jiyong Park92315372021-04-02 08:45:46 +0900901func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
902 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700903}
904
Jiyong Parkf1691d22021-03-29 20:11:58 +0900905func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100906 return ""
907}
908
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000909func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Colin Cross479884c2018-07-10 13:39:30 -0700910 if a.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000911 return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700912 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000913 return a.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -0700914}
915
Spandan Dasa26eda72023-03-02 00:56:06 +0000916func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
917 return android.SdkSpecFrom(ctx, "").ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000918}
919
Spandan Dasca70fc42023-03-01 23:38:49 +0000920func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
921 return a.SdkVersion(ctx).ApiLevel
Dan Willemsen419290a2018-10-31 15:28:47 -0700922}
923
Colin Cross1e743852019-10-28 11:37:20 -0700924func (a *AARImport) javaVersion() string {
925 return ""
926}
927
Colin Crossa97c5d32018-03-28 14:58:31 -0700928var _ AndroidLibraryDependency = (*AARImport)(nil)
929
930func (a *AARImport) ExportPackage() android.Path {
931 return a.exportPackage
932}
Colin Crossab8d1382023-07-14 17:23:41 +0000933func (a *AARImport) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
934 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800935}
936
Colin Crossab8d1382023-07-14 17:23:41 +0000937func (a *AARImport) RRODirsDepSet() *android.DepSet[rroDir] {
938 return android.NewDepSet[rroDir](android.TOPOLOGICAL, nil, nil)
Colin Cross66f78822018-05-02 12:58:28 -0700939}
940
Colin Crossab8d1382023-07-14 17:23:41 +0000941func (a *AARImport) ManifestsDepSet() *android.DepSet[android.Path] {
942 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800943}
944
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700945// RRO enforcement is not available on aar_import since its RRO dirs are not
946// exported.
947func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
948}
949
950// RRO enforcement is not available on aar_import since its RRO dirs are not
951// exported.
952func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
953 return false
954}
955
Colin Crossfabb6082018-02-20 17:22:23 -0800956func (a *AARImport) Prebuilt() *android.Prebuilt {
957 return &a.prebuilt
958}
959
960func (a *AARImport) Name() string {
961 return a.prebuilt.Name(a.ModuleBase.Name())
962}
963
Jiyong Park618922e2020-01-08 13:35:43 +0900964func (a *AARImport) JacocoReportClassesFile() android.Path {
965 return nil
966}
967
Colin Crossfabb6082018-02-20 17:22:23 -0800968func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900969 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900970 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700971 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700972 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800973 }
974 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700975
Colin Cross42d48b72018-08-29 14:10:52 -0700976 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
977 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800978}
979
Sam Delmerico82602492022-06-10 17:05:42 +0000980type JniPackageInfo struct {
981 // List of zip files containing JNI libraries
982 // Zip files should have directory structure jni/<arch>/*.so
983 JniPackages android.Paths
984}
985
986var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
987
988// Unzip an AAR and extract the JNI libs for $archString.
989var extractJNI = pctx.AndroidStaticRule("extractJNI",
990 blueprint.RuleParams{
991 Command: `rm -rf $out $outDir && touch $out && ` +
992 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
993 `jni_files=$$(find $outDir/jni -type f) && ` +
994 // print error message if there are no JNI libs for this arch
995 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
996 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
997 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
998 CommandDeps: []string{"${config.SoongZipCmd}"},
999 },
1000 "outDir", "archString")
1001
Colin Crossfabb6082018-02-20 17:22:23 -08001002// 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 -07001003// 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 -08001004var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
1005 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -07001006 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001007 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001008 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -07001009 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001010 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -08001011 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001012 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -08001013
1014func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1015 if len(a.properties.Aars) != 1 {
1016 ctx.PropertyErrorf("aars", "exactly one aar is required")
1017 return
1018 }
1019
Jiyong Park92315372021-04-02 08:45:46 +09001020 a.sdkVersion = a.SdkVersion(ctx)
1021 a.minSdkVersion = a.MinSdkVersion(ctx)
1022
Colin Cross56a83212020-09-15 18:30:11 -07001023 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
1024
Nan Zhang4c819fb2018-08-27 18:31:46 -07001025 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001026 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
1027
Colin Cross1001a792019-03-21 22:21:39 -07001028 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001029 inputFile := a.aarPath
1030 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
1031 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -07001032 }
Colin Crossfabb6082018-02-20 17:22:23 -08001033
1034 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -07001035 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Cross10f7c4a2018-05-23 10:59:28 -07001036 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Colin Cross4eae06d2023-06-20 22:40:02 -07001037 aarRTxt := extractedAARDir.Join(ctx, "R.txt")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001038 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Sam Delmerico95d70942023-08-02 18:00:35 -04001039 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
1040 ctx.SetProvider(ProguardSpecInfoProvider, ProguardSpecInfo{
1041 ProguardFlagsFiles: android.NewDepSet[android.Path](
1042 android.POSTORDER,
1043 android.Paths{a.proguardFlags},
1044 nil,
1045 ),
1046 })
Colin Crossfabb6082018-02-20 17:22:23 -08001047
1048 ctx.Build(pctx, android.BuildParams{
1049 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001050 Input: a.aarPath,
Colin Cross4eae06d2023-06-20 22:40:02 -07001051 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage, aarRTxt},
Colin Crossfabb6082018-02-20 17:22:23 -08001052 Description: "unzip AAR",
1053 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -07001054 "outDir": extractedAARDir.String(),
1055 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001056 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -08001057 },
1058 })
1059
Colin Crossa0ba2f52019-06-22 12:59:27 -07001060 // Always set --pseudo-localize, it will be stripped out later for release
1061 // builds that don't want it.
1062 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -08001063 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -08001064 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +00001065 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -08001066
1067 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Colin Crossfabb6082018-02-20 17:22:23 -08001068 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Cross4eae06d2023-06-20 22:40:02 -07001069 a.rTxt = android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -07001070 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -08001071
1072 var linkDeps android.Paths
1073
1074 linkFlags := []string{
1075 "--static-lib",
Colin Cross4eae06d2023-06-20 22:40:02 -07001076 "--merge-only",
Colin Crossfabb6082018-02-20 17:22:23 -08001077 "--auto-add-overlay",
1078 }
1079
Colin Cross10f7c4a2018-05-23 10:59:28 -07001080 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
1081 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -08001082
Colin Crossab8d1382023-07-14 17:23:41 +00001083 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedLibs, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +09001084 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -07001085
Colin Crossab8d1382023-07-14 17:23:41 +00001086 _ = staticRRODirsDepSet
1087 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
Colin Crossfabb6082018-02-20 17:22:23 -08001088
Colin Crossab8d1382023-07-14 17:23:41 +00001089 linkDeps = append(linkDeps, sharedLibs...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001090 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -07001091 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -08001092
Colin Cross4eae06d2023-06-20 22:40:02 -07001093 overlayRes := android.Paths{flata}
1094
1095 // Treat static library dependencies of static libraries as imports.
1096 transitiveStaticLibs := staticDeps.resPackages()
1097 linkDeps = append(linkDeps, transitiveStaticLibs...)
1098 for _, staticLib := range transitiveStaticLibs {
1099 linkFlags = append(linkFlags, "-I "+staticLib.String())
1100 }
Colin Crossfabb6082018-02-20 17:22:23 -08001101
Colin Crossab8d1382023-07-14 17:23:41 +00001102 transitiveAssets := android.ReverseSliceInPlace(staticDeps.assets())
Colin Crossf3b7bad2023-08-02 15:49:00 -07001103 aapt2Link(ctx, a.exportPackage, nil, proguardOptionsFile, a.rTxt,
Jaewoong Jung6431ca72020-01-15 14:15:10 -08001104 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001105
Colin Cross4eae06d2023-06-20 22:40:02 -07001106 a.rJar = android.PathForModuleOut(ctx, "busybox/R.jar")
1107 resourceProcessorBusyBoxGenerateBinaryR(ctx, a.rTxt, a.manifest, a.rJar, nil, true)
1108
Colin Crossf3b7bad2023-08-02 15:49:00 -07001109 aapt2ExtractExtraPackages(ctx, a.extraAaptPackagesFile, a.rJar)
1110
Colin Crossab8d1382023-07-14 17:23:41 +00001111 resourcesNodesDepSetBuilder := android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL)
1112 resourcesNodesDepSetBuilder.Direct(&resourcesNode{
1113 resPackage: a.exportPackage,
1114 manifest: a.manifest,
Colin Cross4eae06d2023-06-20 22:40:02 -07001115 rTxt: a.rTxt,
1116 rJar: a.rJar,
Colin Crossab8d1382023-07-14 17:23:41 +00001117 assets: android.OptionalPathForPath(a.assetsPackage),
Colin Cross4eae06d2023-06-20 22:40:02 -07001118
1119 usedResourceProcessor: true,
Colin Crossab8d1382023-07-14 17:23:41 +00001120 })
1121 resourcesNodesDepSetBuilder.Transitive(staticResourcesNodesDepSet)
1122 a.resourcesNodesDepSet = resourcesNodesDepSetBuilder.Build()
1123
1124 manifestDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(a.manifest)
1125 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
1126 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
1127 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
1128 // android_library_import modules. If this is fixed, AndroidLibraryDependency.ManifestsDepSet can be dropped
1129 // completely in favor of AndroidLibraryDependency.ResourceNodesDepSet.manifest
1130 //manifestDepSetBuilder.Transitive(transitiveStaticDeps.manifests)
1131 _ = staticManifestsDepSet
1132 a.manifestsDepSet = manifestDepSetBuilder.Build()
Michael Rosenfeld5ad15572021-12-03 13:25:10 -08001133
Colin Cross4eae06d2023-06-20 22:40:02 -07001134 a.transitiveAaptResourcePackages = staticDeps.resPackages()
1135
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001136 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -08001137 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1138 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001139 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
1140 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08001141 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
1142 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001143 // TransitiveAconfigFiles: // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08001144 })
Sam Delmerico82602492022-06-10 17:05:42 +00001145
1146 if proptools.Bool(a.properties.Extract_jni) {
1147 for _, t := range ctx.MultiTargets() {
1148 arch := t.Arch.Abi[0]
1149 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
1150 a.jniPackages = append(a.jniPackages, path)
1151
1152 outDir := android.PathForModuleOut(ctx, "aarForJni")
1153 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
1154 ctx.Build(pctx, android.BuildParams{
1155 Rule: extractJNI,
1156 Input: aarPath,
1157 Outputs: android.WritablePaths{path},
1158 Description: "extract JNI from AAR",
1159 Args: map[string]string{
1160 "outDir": outDir.String(),
1161 "archString": arch,
1162 },
1163 })
1164 }
1165
1166 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
1167 JniPackages: a.jniPackages,
1168 })
1169 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001170}
Colin Crossfabb6082018-02-20 17:22:23 -08001171
1172func (a *AARImport) HeaderJars() android.Paths {
1173 return android.Paths{a.classpathFile}
1174}
1175
Colin Cross331a1212018-08-15 20:40:52 -07001176func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
1177 return android.Paths{a.classpathFile}
1178}
1179
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +00001180func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -08001181 return nil
1182}
1183
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001184func (a *AARImport) DexJarInstallPath() android.Path {
1185 return nil
1186}
1187
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001188func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +09001189 return nil
1190}
1191
Jiyong Park45bf82e2020-12-15 22:29:02 +09001192var _ android.ApexModule = (*AARImport)(nil)
1193
1194// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001195func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1196 return a.depIsInSameApex(ctx, dep)
1197}
1198
Jiyong Park45bf82e2020-12-15 22:29:02 +09001199// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001200func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1201 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001202 return nil
1203}
1204
Sam Delmericoaf8bb702022-07-25 15:39:32 -04001205var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001206
Colin Cross1b16b0e2019-02-12 14:41:32 -08001207// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
1208//
1209// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
1210// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -08001211func AARImportFactory() android.Module {
1212 module := &AARImport{}
1213
1214 module.AddProperties(&module.properties)
1215
1216 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001217 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +00001218 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001219 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -08001220 return module
1221}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001222
1223type bazelAapt struct {
1224 Manifest bazel.Label
1225 Resource_files bazel.LabelListAttribute
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001226 Assets_dir bazel.StringAttribute
1227 Assets bazel.LabelListAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001228}
1229
1230type bazelAndroidLibrary struct {
1231 *javaLibraryAttributes
1232 *bazelAapt
1233}
1234
1235type bazelAndroidLibraryImport struct {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001236 Aar bazel.Label
1237 Deps bazel.LabelListAttribute
1238 Exports bazel.LabelListAttribute
1239 Sdk_version bazel.StringAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001240}
1241
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001242func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) (*bazelAapt, bool) {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001243 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1244
1245 resourceFiles := bazel.LabelList{
1246 Includes: []bazel.Label{},
1247 }
1248 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1249 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1250 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1251 }
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001252
1253 assetsDir := bazel.StringAttribute{}
1254 var assets bazel.LabelList
1255 for i, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets") {
1256 if i > 0 {
1257 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "multiple asset_dirs")
1258 return &bazelAapt{}, false
1259 }
1260 // Assets_dirs are relative to the module dir when specified, but if the default in used in
1261 // PathsWithOptionalDefaultForModuleSrc, then dir is relative to the top.
1262 assetsRelDir, error := filepath.Rel(ctx.ModuleDir(), dir.Rel())
1263 if error != nil {
1264 assetsRelDir = dir.Rel()
1265 }
1266 assetsDir.Value = proptools.StringPtr(assetsRelDir)
1267 assets = bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir)))
1268
1269 }
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001270 return &bazelAapt{
1271 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1272 bazel.MakeLabelListAttribute(resourceFiles),
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001273 assetsDir,
1274 bazel.MakeLabelListAttribute(assets),
1275 }, true
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001276}
1277
1278func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1279 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1280 exportableStaticLibs := []string{}
1281 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1282 for _, depName := range a.properties.Static_libs {
1283 if dep, ok := ctx.ModuleFromName(depName); ok {
1284 switch dep.(type) {
1285 case *AARImport, *Import:
1286 exportableStaticLibs = append(exportableStaticLibs, depName)
1287 }
1288 }
1289 }
1290 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1291 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1292 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1293
1294 ctx.CreateBazelTargetModule(
1295 bazel.BazelTargetModuleProperties{
1296 Rule_class: "aar_import",
Alixa381cd12023-05-10 14:49:38 +00001297 Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001298 },
1299 android.CommonAttributes{Name: name},
1300 &bazelAndroidLibraryImport{
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001301 Aar: aars.Includes[0],
1302 Deps: bazel.MakeLabelListAttribute(deps),
1303 Exports: bazel.MakeLabelListAttribute(exports),
1304 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001305 },
1306 )
1307
Alix14101de2023-01-06 03:42:07 +00001308 neverlink := true
1309 ctx.CreateBazelTargetModule(
Alix32540022023-03-16 21:06:13 +00001310 AndroidLibraryBazelTargetModuleProperties(),
Alix14101de2023-01-06 03:42:07 +00001311 android.CommonAttributes{Name: name + "-neverlink"},
1312 &bazelAndroidLibrary{
1313 javaLibraryAttributes: &javaLibraryAttributes{
1314 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1315 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001316 javaCommonAttributes: &javaCommonAttributes{
1317 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
1318 },
Alix14101de2023-01-06 03:42:07 +00001319 },
1320 },
1321 )
1322
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001323}
Alix32540022023-03-16 21:06:13 +00001324func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
1325 return bazel.BazelTargetModuleProperties{
1326 Rule_class: "android_library",
Alixa381cd12023-05-10 14:49:38 +00001327 Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
Alix32540022023-03-16 21:06:13 +00001328 }
1329}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001330
1331func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammer7f375862023-08-04 16:37:42 -04001332 commonAttrs, bp2buildInfo, supported := a.convertLibraryAttrsBp2Build(ctx)
1333 if !supported {
1334 return
1335 }
1336
Alix8062f4d2022-11-14 21:38:07 +00001337 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001338
1339 deps := depLabels.Deps
1340 if !commonAttrs.Srcs.IsEmpty() {
1341 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1342 } else if !depLabels.Deps.IsEmpty() {
1343 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1344 }
Alix82fb94e2022-10-26 20:40:18 +00001345 name := a.Name()
Alix32540022023-03-16 21:06:13 +00001346 props := AndroidLibraryBazelTargetModuleProperties()
Alix82fb94e2022-10-26 20:40:18 +00001347
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001348 aaptAttrs, supported := a.convertAaptAttrsWithBp2Build(ctx)
1349 if !supported {
1350 return
1351 }
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001352 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001353 props,
1354 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001355 &bazelAndroidLibrary{
1356 &javaLibraryAttributes{
1357 javaCommonAttributes: commonAttrs,
1358 Deps: deps,
1359 Exports: depLabels.StaticDeps,
1360 },
Romain Jobredeaux7a71e072023-08-16 17:39:12 -04001361 aaptAttrs,
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001362 },
1363 )
Alix82fb94e2022-10-26 20:40:18 +00001364
1365 neverlink := true
1366 ctx.CreateBazelTargetModule(
1367 props,
1368 android.CommonAttributes{Name: name + "-neverlink"},
1369 &bazelAndroidLibrary{
1370 javaLibraryAttributes: &javaLibraryAttributes{
1371 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1372 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001373 javaCommonAttributes: &javaCommonAttributes{
1374 Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
1375 Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
1376 },
Alix82fb94e2022-10-26 20:40:18 +00001377 },
1378 },
1379 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001380}