blob: a4f899b7acc709f28db210649c28ef8ecdd2c05d [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 Cross4c90f992023-06-13 16:44:58 -070034 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
91 // true if RRO is enforced for any of the dependent modules
92 RROEnforcedForDependent bool `blueprint:"mutated"`
Colin Crossa97c5d32018-03-28 14:58:31 -070093}
94
95type aapt struct {
Colin Cross4c90f992023-06-13 16:44:58 -070096 aaptSrcJar android.Path
97 exportPackage android.Path
98 manifestPath android.Path
99 proguardOptionsFile android.Path
100 rTxt android.Path
101 extraAaptPackagesFile android.Path
102 mergedManifestFile android.Path
103 noticeFile android.OptionalPath
104 assetPackage android.OptionalPath
105 isLibrary bool
106 defaultManifestVersion string
107 useEmbeddedNativeLibs bool
108 useEmbeddedDex bool
109 usesNonSdkApis bool
110 hasNoCode bool
111 LoggingParent string
112 resourceFiles android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700113
Colin Crosse560c4a2019-03-19 16:03:11 -0700114 splitNames []string
115 splits []split
116
Colin Crossa97c5d32018-03-28 14:58:31 -0700117 aaptProperties aaptProperties
Colin Cross4c90f992023-06-13 16:44:58 -0700118
119 resourcesNodesDepSet *android.DepSet[resourcesNode]
120 rroDirsDepSet *android.DepSet[rroDir]
121 manifestsDepSet *android.DepSet[android.Path]
Colin Crossa97c5d32018-03-28 14:58:31 -0700122}
123
Colin Crosse560c4a2019-03-19 16:03:11 -0700124type split struct {
125 name string
126 suffix string
127 path android.Path
128}
129
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700130// Propagate RRO enforcement flag to static lib dependencies transitively.
131func propagateRROEnforcementMutator(ctx android.TopDownMutatorContext) {
132 m := ctx.Module()
133 if d, ok := m.(AndroidLibraryDependency); ok && d.IsRROEnforced(ctx) {
134 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
135 if a, ok := d.(AndroidLibraryDependency); ok {
136 a.SetRROEnforcedForDependent(true)
137 }
138 })
139 }
140}
141
Colin Crossa97c5d32018-03-28 14:58:31 -0700142func (a *aapt) ExportPackage() android.Path {
143 return a.exportPackage
144}
Colin Cross4c90f992023-06-13 16:44:58 -0700145func (a *aapt) ResourcesNodeDepSet() *android.DepSet[resourcesNode] {
146 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800147}
148
Colin Cross4c90f992023-06-13 16:44:58 -0700149func (a *aapt) RRODirsDepSet() *android.DepSet[rroDir] {
150 return a.rroDirsDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800151}
152
Colin Cross4c90f992023-06-13 16:44:58 -0700153func (a *aapt) ManifestsDepSet() *android.DepSet[android.Path] {
154 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800155}
156
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700157func (a *aapt) SetRROEnforcedForDependent(enforce bool) {
158 a.aaptProperties.RROEnforcedForDependent = enforce
159}
160
161func (a *aapt) IsRROEnforced(ctx android.BaseModuleContext) bool {
162 // True if RRO is enforced for this module or...
163 return ctx.Config().EnforceRROForModule(ctx.ModuleName()) ||
Jeongik Chacee5ba92021-02-19 12:11:51 +0900164 // if RRO is enforced for any of its dependents.
165 a.aaptProperties.RROEnforcedForDependent
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700166}
167
Jiyong Parkf1691d22021-03-29 20:11:58 +0900168func (a *aapt) aapt2Flags(ctx android.ModuleContext, sdkContext android.SdkContext,
Colin Crossa0ba2f52019-06-22 12:59:27 -0700169 manifestPath android.Path) (compileFlags, linkFlags []string, linkDeps android.Paths,
170 resDirs, overlayDirs []globbedResourceDir, rroDirs []rroDir, resZips android.Paths) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700171
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800172 hasVersionCode := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-code")
173 hasVersionName := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-name")
Colin Crossa97c5d32018-03-28 14:58:31 -0700174
Colin Crossa97c5d32018-03-28 14:58:31 -0700175 // Flags specified in Android.bp
176 linkFlags = append(linkFlags, a.aaptProperties.Aaptflags...)
177
178 linkFlags = append(linkFlags, "--no-static-lib-packages")
179
180 // Find implicit or explicit asset and resource dirs
181 assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
182 resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
Colin Cross8a497952019-03-05 22:25:09 -0800183 resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
Colin Crossa97c5d32018-03-28 14:58:31 -0700184
Colin Crossa97c5d32018-03-28 14:58:31 -0700185 // Glob directories into lists of paths
186 for _, dir := range resourceDirs {
187 resDirs = append(resDirs, globbedResourceDir{
188 dir: dir,
189 files: androidResourceGlob(ctx, dir),
190 })
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700191 resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
Colin Crossa97c5d32018-03-28 14:58:31 -0700192 overlayDirs = append(overlayDirs, resOverlayDirs...)
193 rroDirs = append(rroDirs, resRRODirs...)
194 }
195
Colin Crossc20dc852020-11-10 12:27:45 -0800196 var assetDeps android.Paths
197 for i, dir := range assetDirs {
198 // Add a dependency on every file in the asset directory. This ensures the aapt2
199 // rule will be rerun if one of the files in the asset directory is modified.
200 assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
201
202 // Add a dependency on a file that contains a list of all the files in the asset directory.
203 // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
204 // or a file is added whose timestamp is older than the output of aapt2.
205 assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
206 androidResourceGlobList(ctx, dir, assetFileListFile)
207 assetDeps = append(assetDeps, assetFileListFile)
Colin Crossa97c5d32018-03-28 14:58:31 -0700208 }
209
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700210 assetDirStrings := assetDirs.Strings()
211 if a.noticeFile.Valid() {
212 assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
Colin Crossc20dc852020-11-10 12:27:45 -0800213 assetDeps = append(assetDeps, a.noticeFile.Path())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700214 }
215
Colin Crossa97c5d32018-03-28 14:58:31 -0700216 linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
217 linkDeps = append(linkDeps, manifestPath)
218
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700219 linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
Colin Crossc20dc852020-11-10 12:27:45 -0800220 linkDeps = append(linkDeps, assetDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700221
Spandan Das50885c02023-02-23 21:31:33 +0000222 // Returns the effective version for {min|target}_sdk_version
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000223 effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
Spandan Das50885c02023-02-23 21:31:33 +0000224 // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
225 // This is necessary for vendor modules.
226 // The effective version does not _only_ depend on {min|target}_sdk_version(level),
227 // but also on the sdk_version (kind+level)
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000228 if minSdkVersion.IsCurrent() {
Spandan Das50885c02023-02-23 21:31:33 +0000229 ret, err := sdkVersion.EffectiveVersionString(ctx)
230 if err != nil {
231 ctx.ModuleErrorf("invalid sdk_version: %s", err)
232 }
233 return ret
234 }
235 ret, err := minSdkVersion.EffectiveVersionString(ctx)
236 if err != nil {
237 ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
238 }
239 return ret
Jiyong Park6a927c42020-01-21 02:03:43 +0900240 }
Spandan Das50885c02023-02-23 21:31:33 +0000241 // SDK version flags
242 sdkVersion := sdkContext.SdkVersion(ctx)
243 minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
Colin Crossa97c5d32018-03-28 14:58:31 -0700244
Colin Cross83bb3162018-06-25 15:48:06 -0700245 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000246 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
247 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700248 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700249
Colin Crossa97c5d32018-03-28 14:58:31 -0700250 // Version code
251 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700252 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700253 }
254
255 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700256 var versionName string
257 if ctx.ModuleName() == "framework-res" {
258 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
259 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700260 // if it contains the build number. Use the PlatformVersionName instead.
261 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700262 } else {
263 versionName = ctx.Config().AppsDefaultVersionName()
264 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800265 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700266 linkFlags = append(linkFlags, "--version-name ", versionName)
267 }
268
Colin Crossa0ba2f52019-06-22 12:59:27 -0700269 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
270
271 // Always set --pseudo-localize, it will be stripped out later for release
272 // builds that don't want it.
273 compileFlags = append(compileFlags, "--pseudo-localize")
274
275 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700276}
277
Paul Duffin250e6192019-06-07 10:44:37 +0100278func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800279 if sdkDep.frameworkResModule != "" {
280 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700281 }
282}
283
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800284var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
285 blueprint.RuleParams{
286 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
287 CommandDeps: []string{"${config.Zip2ZipCmd}"},
288 })
289
Jiyong Parkf1691d22021-03-29 20:11:58 +0900290func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000291 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000292 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700293
Colin Cross4c90f992023-06-13 16:44:58 -0700294 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100295 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100296
Paul Duffin06530572022-02-03 17:54:15 +0000297 // Exclude any libraries from the supplied list.
298 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
299
Colin Cross31656952018-05-24 16:11:20 -0700300 // App manifest file
301 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
302 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
303
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000304 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000305 SdkContext: sdkContext,
306 ClassLoaderContexts: classLoaderContexts,
307 IsLibrary: a.isLibrary,
308 DefaultManifestVersion: a.defaultManifestVersion,
309 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
310 UsesNonSdkApis: a.usesNonSdkApis,
311 UseEmbeddedDex: a.useEmbeddedDex,
312 HasNoCode: a.hasNoCode,
313 LoggingParent: a.LoggingParent,
314 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000315 })
Colin Cross90c25c62019-04-19 16:22:57 -0700316
Colin Cross4c90f992023-06-13 16:44:58 -0700317 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
318
Luca Stefanifd898822019-09-10 22:13:31 +0200319 // Add additional manifest files to transitive manifests.
320 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
Colin Cross4c90f992023-06-13 16:44:58 -0700321 transitiveManifestPaths := append(android.Paths{manifestPath}, additionalManifests...)
322 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
323 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
324 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
325 // android_library_import modules. If this is fixed, staticManifestsDepSet can be dropped completely in favor of
326 // staticResourcesNodesDepSet.manifests()
327 transitiveManifestPaths = append(transitiveManifestPaths, staticManifestsDepSet.ToList()...)
Colin Cross90c25c62019-04-19 16:22:57 -0700328
Colin Cross4c90f992023-06-13 16:44:58 -0700329 if len(transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
330 a.mergedManifestFile = manifestMerger(ctx, transitiveManifestPaths[0], transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700331 if !a.isLibrary {
332 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
333 // will be propagated to the final application and merged there. The merged manifest for libraries is
334 // only passed to Make, which can't handle transitive dependencies.
335 manifestPath = a.mergedManifestFile
336 }
337 } else {
338 a.mergedManifestFile = manifestPath
339 }
Colin Cross31656952018-05-24 16:11:20 -0700340
Colin Crossa0ba2f52019-06-22 12:59:27 -0700341 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700342
343 linkFlags = append(linkFlags, libFlags...)
Colin Cross4c90f992023-06-13 16:44:58 -0700344 linkDeps = append(linkDeps, sharedDeps...)
345 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700346 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700347 if a.isLibrary {
348 linkFlags = append(linkFlags, "--static-lib")
349 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700350
351 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900352 // the subdir "android" is required to be filtered by package names
353 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700354 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
355 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700356 // This file isn't used by Soong, but is generated for exporting
357 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Crossa97c5d32018-03-28 14:58:31 -0700358
Colin Cross4aaa84a2018-08-21 15:14:37 -0700359 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700360 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700361 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700362 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700363 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700364
Colin Crossa592e3e2019-02-19 16:59:53 -0800365 for i, zip := range resZips {
366 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700367 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800368 compiledResDirs = append(compiledResDirs, android.Paths{flata})
369 }
370
Colin Cross4aaa84a2018-08-21 15:14:37 -0700371 var compiledRes, compiledOverlay android.Paths
372
Colin Cross4c90f992023-06-13 16:44:58 -0700373 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
374 // of transitiveStaticLibs.
375 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
376
Colin Cross4aaa84a2018-08-21 15:14:37 -0700377 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
378
Colin Crossbec85302019-02-13 13:15:46 -0800379 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700380 // If we are using static android libraries, every source file becomes an overlay.
381 // This is to emulate old AAPT behavior which simulated library support.
382 for _, compiledResDir := range compiledResDirs {
383 compiledOverlay = append(compiledOverlay, compiledResDir...)
384 }
Colin Crossbec85302019-02-13 13:15:46 -0800385 } else if a.isLibrary {
386 // Otherwise, for a static library we treat all the resources equally with no overlay.
387 for _, compiledResDir := range compiledResDirs {
388 compiledRes = append(compiledRes, compiledResDir...)
389 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700390 } else if len(compiledResDirs) > 0 {
391 // Without static libraries, the first directory is our directory, which can then be
392 // overlaid by the rest.
393 compiledRes = append(compiledRes, compiledResDirs[0]...)
394 for _, compiledResDir := range compiledResDirs[1:] {
395 compiledOverlay = append(compiledOverlay, compiledResDir...)
396 }
397 }
398
Colin Crossa97c5d32018-03-28 14:58:31 -0700399 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700400 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700401 }
402
Colin Crosse560c4a2019-03-19 16:03:11 -0700403 var splitPackages android.WritablePaths
404 var splits []split
405
406 for _, s := range a.splitNames {
407 suffix := strings.Replace(s, ",", "_", -1)
408 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
409 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
410 splitPackages = append(splitPackages, path)
411 splits = append(splits, split{
412 name: s,
413 suffix: suffix,
414 path: path,
415 })
416 }
417
Colin Cross4c90f992023-06-13 16:44:58 -0700418 // No need to specify assets from dependencies to aapt2Link for libraries, all transitive assets will be
419 // provided to the final app aapt2Link step.
420 var transitiveAssets android.Paths
421 if !a.isLibrary {
422 transitiveAssets = android.ReverseSliceInPlace(staticDeps.assets())
423 }
Colin Cross66f78822018-05-02 12:58:28 -0700424 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt, extraPackages,
Colin Cross4c90f992023-06-13 16:44:58 -0700425 linkFlags, linkDeps, compiledRes, compiledOverlay, transitiveAssets, splitPackages)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800426
427 // Extract assets from the resource package output so that they can be used later in aapt2link
428 // for modules that depend on this one.
Colin Cross4c90f992023-06-13 16:44:58 -0700429 if android.PrefixInList(linkFlags, "-A ") {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800430 assets := android.PathForModuleOut(ctx, "assets.zip")
431 ctx.Build(pctx, android.BuildParams{
432 Rule: extractAssetsRule,
433 Input: packageRes,
434 Output: assets,
435 Description: "extract assets from built resource file",
436 })
437 a.assetPackage = android.OptionalPathForPath(assets)
438 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700439
440 a.aaptSrcJar = srcJar
441 a.exportPackage = packageRes
442 a.manifestPath = manifestPath
443 a.proguardOptionsFile = proguardOptionsFile
Colin Cross66f78822018-05-02 12:58:28 -0700444 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700445 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700446 a.splits = splits
Colin Cross4c90f992023-06-13 16:44:58 -0700447 a.resourcesNodesDepSet = android.NewDepSetBuilder[resourcesNode](android.TOPOLOGICAL).
448 Direct(resourcesNode{
449 resPackage: a.exportPackage,
450 manifest: a.manifestPath,
451 assets: a.assetPackage,
452 }).
453 Transitive(staticResourcesNodesDepSet).Build()
454 a.rroDirsDepSet = android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL).
455 Direct(rroDirs...).
456 Transitive(staticRRODirsDepSet).Build()
457 a.manifestsDepSet = android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
458 Direct(a.manifestPath).
459 Transitive(staticManifestsDepSet).Build()
460}
461
462type resourcesNode struct {
463 resPackage android.Path
464 manifest android.Path
465 assets android.OptionalPath
466}
467
468type transitiveAarDeps []resourcesNode
469
470func (t transitiveAarDeps) resPackages() android.Paths {
471 var paths android.Paths
472 for _, dep := range t {
473 paths = append(paths, dep.resPackage)
474 }
475 return android.FirstUniquePaths(paths)
476}
477
478func (t transitiveAarDeps) manifests() android.Paths {
479 var paths android.Paths
480 for _, dep := range t {
481 paths = append(paths, dep.manifest)
482 }
483 return android.FirstUniquePaths(paths)
484}
485
486func (t transitiveAarDeps) assets() android.Paths {
487 var paths android.Paths
488 for _, dep := range t {
489 if dep.assets.Valid() {
490 paths = append(paths, dep.assets.Path())
491 }
492 }
493 return paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700494}
495
496// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900497func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Colin Cross4c90f992023-06-13 16:44:58 -0700498 staticResourcesNodes *android.DepSet[resourcesNode], staticRRODirs *android.DepSet[rroDir],
499 staticManifests *android.DepSet[android.Path], sharedLibs android.Paths, flags []string) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700500
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100501 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000502 // Not all callers need to compute class loader context, those who don't just pass nil.
503 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100504 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000505 }
506
Colin Cross83bb3162018-06-25 15:48:06 -0700507 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700508 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700509 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700510 }
511
Colin Cross4c90f992023-06-13 16:44:58 -0700512 var resourcesNodeDepSets []*android.DepSet[resourcesNode]
513 rroDirsDepSetBuilder := android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL)
514 manifestsDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
515
Colin Crossa97c5d32018-03-28 14:58:31 -0700516 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000517 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000518
Colin Crossa97c5d32018-03-28 14:58:31 -0700519 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700520 aarDep, _ := module.(AndroidLibraryDependency)
521 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700522 exportPackage = aarDep.ExportPackage()
523 }
524
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000525 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700526 case instrumentationForTag:
527 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400528 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700529 if exportPackage != nil {
530 sharedLibs = append(sharedLibs, exportPackage)
531 }
Colin Cross5446e882019-05-22 10:46:27 -0700532 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700533 if exportPackage != nil {
534 sharedLibs = append(sharedLibs, exportPackage)
535 }
536 case staticLibTag:
537 if exportPackage != nil {
Colin Cross4c90f992023-06-13 16:44:58 -0700538 resourcesNodeDepSets = append(resourcesNodeDepSets, aarDep.ResourcesNodeDepSet())
539 rroDirsDepSetBuilder.Transitive(aarDep.RRODirsDepSet())
540 manifestsDepSetBuilder.Transitive(aarDep.ManifestsDepSet())
Colin Crossa97c5d32018-03-28 14:58:31 -0700541 }
542 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000543
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000544 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700545 })
546
Colin Cross4c90f992023-06-13 16:44:58 -0700547 // AAPT2 overlays are in lowest to highest priority order, the topological order will be reversed later.
548 // Reverse the dependency order now going into the depset so that it comes out in order after the second
549 // reverse later.
550 // NOTE: this is legacy and probably incorrect behavior, for most other cases (e.g. conflicting classes in
551 // dependencies) the highest priority dependency is listed first, but for resources the highest priority
552 // dependency has to be listed last.
553 staticResourcesNodes = android.NewDepSet(android.TOPOLOGICAL, nil,
554 android.ReverseSliceInPlace(resourcesNodeDepSets))
Colin Crossa97c5d32018-03-28 14:58:31 -0700555
Colin Cross4c90f992023-06-13 16:44:58 -0700556 staticRRODirs = rroDirsDepSetBuilder.Build()
557 staticManifests = manifestsDepSetBuilder.Build()
558
559 if len(staticResourcesNodes.ToList()) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700560 flags = append(flags, "--auto-add-overlay")
561 }
562
563 for _, sharedLib := range sharedLibs {
564 flags = append(flags, "-I "+sharedLib.String())
565 }
566
Colin Cross4c90f992023-06-13 16:44:58 -0700567 return staticResourcesNodes, staticRRODirs, staticManifests, sharedLibs, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700568}
569
570type AndroidLibrary struct {
571 Library
572 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500573 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700574
575 androidLibraryProperties androidLibraryProperties
576
577 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700578}
579
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000580var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
581
582// For OutputFileProducer interface
583func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
584 switch tag {
585 case ".aar":
586 return []android.Path{a.aarFile}, nil
587 default:
588 return a.Library.OutputFiles(tag)
589 }
590}
591
Colin Crossa97c5d32018-03-28 14:58:31 -0700592var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
593
594func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
595 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900596 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100597 if sdkDep.hasFrameworkLibs() {
598 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700599 }
Colin Cross4a80a152022-12-21 21:51:52 -0800600 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700601}
602
603func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800604 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100605 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000606 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700607
Colin Cross56a83212020-09-15 18:30:11 -0700608 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
609
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000610 a.stem = proptools.StringDefault(a.overridableDeviceProperties.Stem, ctx.ModuleName())
611
Colin Crossa97c5d32018-03-28 14:58:31 -0700612 ctx.CheckbuildFile(a.proguardOptionsFile)
613 ctx.CheckbuildFile(a.exportPackage)
614 ctx.CheckbuildFile(a.aaptSrcJar)
615
616 // apps manifests are handled by aapt, don't let Module see them
617 a.properties.Manifest = nil
618
Colin Cross014489c2020-06-02 20:09:13 -0700619 a.linter.mergedManifest = a.aapt.mergedManifestFile
620 a.linter.manifest = a.aapt.manifestPath
621 a.linter.resources = a.aapt.resourceFiles
622
Colin Crossa97c5d32018-03-28 14:58:31 -0700623 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
624 a.proguardOptionsFile)
625
626 a.Module.compile(ctx, a.aaptSrcJar)
627
Colin Crossf57c5782019-01-25 13:20:38 -0800628 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700629 var res android.Paths
630 if a.androidLibraryProperties.BuildAAR {
631 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
632 ctx.CheckbuildFile(a.aarFile)
633 }
Colin Cross89c31582018-04-30 15:55:11 -0700634
Cole Faust9a631312020-10-22 21:05:24 +0000635 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
636 android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
Colin Cross4c90f992023-06-13 16:44:58 -0700637
Colin Cross89c31582018-04-30 15:55:11 -0700638 ctx.VisitDirectDeps(func(m android.Module) {
Jared Duke5979b302022-12-19 21:08:39 +0000639 if ctx.OtherModuleDependencyTag(m) == staticLibTag {
640 if lib, ok := m.(LibraryDependency); ok {
641 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
642 }
Colin Cross89c31582018-04-30 15:55:11 -0700643 }
644 })
Colin Cross89c31582018-04-30 15:55:11 -0700645 a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
Sam Delmerico82602492022-06-10 17:05:42 +0000646
647 prebuiltJniPackages := android.Paths{}
648 ctx.VisitDirectDeps(func(module android.Module) {
649 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
650 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
651 }
652 })
653 if len(prebuiltJniPackages) > 0 {
654 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
655 JniPackages: prebuiltJniPackages,
656 })
657 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700658}
659
Colin Cross1b16b0e2019-02-12 14:41:32 -0800660// android_library builds and links sources into a `.jar` file for the device along with Android resources.
661//
662// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000663// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800664// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
665// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700666func AndroidLibraryFactory() android.Module {
667 module := &AndroidLibrary{}
668
Colin Crossce6734e2020-06-15 16:09:53 -0700669 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700670 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700671 &module.aaptProperties,
672 &module.androidLibraryProperties)
673
674 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700675 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700676
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900677 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700678 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500679 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700680 return module
681}
682
Colin Crossfabb6082018-02-20 17:22:23 -0800683//
684// AAR (android library) prebuilts
685//
Colin Crossfabb6082018-02-20 17:22:23 -0800686
Vinh Trance0781f2022-04-13 01:30:44 +0000687// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800688type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000689 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800690 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000691 // If not blank, set to the version of the sdk to compile against.
692 // Defaults to private.
693 // Values are of one of the following forms:
694 // 1) numerical API level, "current", "none", or "core_platform"
695 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
696 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
697 // If the SDK kind is empty, it will be set to public
698 Sdk_version *string
699 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
700 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700701 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000702 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700703 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000704 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
705 Libs []string
706 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700707 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000708 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
709 // will be passed transitively through android_libraries to an android_app.
710 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
711 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800712}
713
714type AARImport struct {
715 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700716 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900717 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500718 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800719 prebuilt android.Prebuilt
720
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900721 // Functionality common to Module and Import.
722 embeddableInModuleAndImport
723
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500724 providesTransitiveHeaderJars
725
Colin Crossfabb6082018-02-20 17:22:23 -0800726 properties AARImportProperties
727
Colin Cross66f78822018-05-02 12:58:28 -0700728 classpathFile android.WritablePath
729 proguardFlags android.WritablePath
730 exportPackage android.WritablePath
731 extraAaptPackagesFile android.WritablePath
Colin Cross10f7c4a2018-05-23 10:59:28 -0700732 manifest android.WritablePath
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800733 assetsPackage android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700734
Colin Cross4c90f992023-06-13 16:44:58 -0700735 resourcesNodesDepSet *android.DepSet[resourcesNode]
736 manifestsDepSet *android.DepSet[android.Path]
Colin Cross56a83212020-09-15 18:30:11 -0700737
738 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000739
Sam Delmerico82602492022-06-10 17:05:42 +0000740 aarPath android.Path
741 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900742
743 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000744 minSdkVersion android.ApiLevel
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000745}
746
747var _ android.OutputFileProducer = (*AARImport)(nil)
748
749// For OutputFileProducer interface
750func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
751 switch tag {
752 case ".aar":
753 return []android.Path{a.aarPath}, nil
754 case "":
755 return []android.Path{a.classpathFile}, nil
756 default:
757 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
758 }
Colin Crossfabb6082018-02-20 17:22:23 -0800759}
760
Jiyong Park92315372021-04-02 08:45:46 +0900761func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
762 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700763}
764
Jiyong Parkf1691d22021-03-29 20:11:58 +0900765func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100766 return ""
767}
768
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000769func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Colin Cross479884c2018-07-10 13:39:30 -0700770 if a.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000771 return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700772 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000773 return a.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -0700774}
775
Spandan Dasa26eda72023-03-02 00:56:06 +0000776func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
777 return android.SdkSpecFrom(ctx, "").ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000778}
779
Spandan Dasca70fc42023-03-01 23:38:49 +0000780func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
781 return a.SdkVersion(ctx).ApiLevel
Dan Willemsen419290a2018-10-31 15:28:47 -0700782}
783
Colin Cross1e743852019-10-28 11:37:20 -0700784func (a *AARImport) javaVersion() string {
785 return ""
786}
787
Colin Crossa97c5d32018-03-28 14:58:31 -0700788var _ AndroidLibraryDependency = (*AARImport)(nil)
789
790func (a *AARImport) ExportPackage() android.Path {
791 return a.exportPackage
792}
Colin Cross89c31582018-04-30 15:55:11 -0700793func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
794 return android.Paths{a.proguardFlags}
795}
796
Colin Cross4c90f992023-06-13 16:44:58 -0700797func (a *AARImport) ResourcesNodeDepSet() *android.DepSet[resourcesNode] {
798 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800799}
800
Colin Cross4c90f992023-06-13 16:44:58 -0700801func (a *AARImport) RRODirsDepSet() *android.DepSet[rroDir] {
802 return android.NewDepSet[rroDir](android.TOPOLOGICAL, nil, nil)
Colin Cross66f78822018-05-02 12:58:28 -0700803}
804
Colin Cross4c90f992023-06-13 16:44:58 -0700805func (a *AARImport) ManifestsDepSet() *android.DepSet[android.Path] {
806 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800807}
808
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700809// RRO enforcement is not available on aar_import since its RRO dirs are not
810// exported.
811func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
812}
813
814// RRO enforcement is not available on aar_import since its RRO dirs are not
815// exported.
816func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
817 return false
818}
819
Colin Crossfabb6082018-02-20 17:22:23 -0800820func (a *AARImport) Prebuilt() *android.Prebuilt {
821 return &a.prebuilt
822}
823
824func (a *AARImport) Name() string {
825 return a.prebuilt.Name(a.ModuleBase.Name())
826}
827
Jiyong Park618922e2020-01-08 13:35:43 +0900828func (a *AARImport) JacocoReportClassesFile() android.Path {
829 return nil
830}
831
Colin Crossfabb6082018-02-20 17:22:23 -0800832func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900833 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900834 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700835 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700836 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800837 }
838 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700839
Colin Cross42d48b72018-08-29 14:10:52 -0700840 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
841 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800842}
843
Sam Delmerico82602492022-06-10 17:05:42 +0000844type JniPackageInfo struct {
845 // List of zip files containing JNI libraries
846 // Zip files should have directory structure jni/<arch>/*.so
847 JniPackages android.Paths
848}
849
850var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
851
852// Unzip an AAR and extract the JNI libs for $archString.
853var extractJNI = pctx.AndroidStaticRule("extractJNI",
854 blueprint.RuleParams{
855 Command: `rm -rf $out $outDir && touch $out && ` +
856 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
857 `jni_files=$$(find $outDir/jni -type f) && ` +
858 // print error message if there are no JNI libs for this arch
859 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
860 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
861 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
862 CommandDeps: []string{"${config.SoongZipCmd}"},
863 },
864 "outDir", "archString")
865
Colin Crossfabb6082018-02-20 17:22:23 -0800866// 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 -0700867// 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 -0800868var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
869 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -0700870 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700871 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800872 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700873 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800874 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -0800875 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800876 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -0800877
878func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
879 if len(a.properties.Aars) != 1 {
880 ctx.PropertyErrorf("aars", "exactly one aar is required")
881 return
882 }
883
Jiyong Park92315372021-04-02 08:45:46 +0900884 a.sdkVersion = a.SdkVersion(ctx)
885 a.minSdkVersion = a.MinSdkVersion(ctx)
886
Colin Cross56a83212020-09-15 18:30:11 -0700887 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
888
Nan Zhang4c819fb2018-08-27 18:31:46 -0700889 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000890 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
891
Colin Cross1001a792019-03-21 22:21:39 -0700892 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000893 inputFile := a.aarPath
894 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
895 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -0700896 }
Colin Crossfabb6082018-02-20 17:22:23 -0800897
898 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -0700899 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Crossfabb6082018-02-20 17:22:23 -0800900 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
Colin Cross10f7c4a2018-05-23 10:59:28 -0700901 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800902 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Colin Crossfabb6082018-02-20 17:22:23 -0800903
904 ctx.Build(pctx, android.BuildParams{
905 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000906 Input: a.aarPath,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800907 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage},
Colin Crossfabb6082018-02-20 17:22:23 -0800908 Description: "unzip AAR",
909 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -0700910 "outDir": extractedAARDir.String(),
911 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800912 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -0800913 },
914 })
915
Colin Crossa0ba2f52019-06-22 12:59:27 -0700916 // Always set --pseudo-localize, it will be stripped out later for release
917 // builds that don't want it.
918 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -0800919 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -0800920 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000921 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -0800922
923 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900924 // the subdir "android" is required to be filtered by package names
925 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossfabb6082018-02-20 17:22:23 -0800926 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Crossa97c5d32018-03-28 14:58:31 -0700927 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700928 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -0800929
930 var linkDeps android.Paths
931
932 linkFlags := []string{
933 "--static-lib",
934 "--no-static-lib-packages",
935 "--auto-add-overlay",
936 }
937
Colin Cross10f7c4a2018-05-23 10:59:28 -0700938 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
939 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -0800940
Colin Cross4c90f992023-06-13 16:44:58 -0700941 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedLibs, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +0900942 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -0700943
Colin Cross4c90f992023-06-13 16:44:58 -0700944 _ = staticRRODirsDepSet
945 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
Colin Crossfabb6082018-02-20 17:22:23 -0800946
Colin Cross4c90f992023-06-13 16:44:58 -0700947 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
948 // of transitiveStaticLibs.
949 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
950
951 linkDeps = append(linkDeps, sharedLibs...)
952 linkDeps = append(linkDeps, transitiveStaticLibs...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700953 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -0800954
Colin Cross66f78822018-05-02 12:58:28 -0700955 overlayRes := append(android.Paths{flata}, transitiveStaticLibs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800956
Colin Cross4c90f992023-06-13 16:44:58 -0700957 transitiveAssets := android.ReverseSliceInPlace(staticDeps.assets())
Colin Cross66f78822018-05-02 12:58:28 -0700958 aapt2Link(ctx, a.exportPackage, srcJar, proguardOptionsFile, rTxt, a.extraAaptPackagesFile,
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800959 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -0800960
Colin Cross4c90f992023-06-13 16:44:58 -0700961 resourcesNodesDepSetBuilder := android.NewDepSetBuilder[resourcesNode](android.TOPOLOGICAL)
962 resourcesNodesDepSetBuilder.Direct(resourcesNode{
963 resPackage: a.exportPackage,
964 manifest: a.manifest,
965 assets: android.OptionalPathForPath(a.assetsPackage),
966 })
967 resourcesNodesDepSetBuilder.Transitive(staticResourcesNodesDepSet)
968 a.resourcesNodesDepSet = resourcesNodesDepSetBuilder.Build()
969
970 manifestDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(a.manifest)
971 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
972 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
973 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
974 // android_library_import modules. If this is fixed, AndroidLibraryDependency.ManifestsDepSet can be dropped
975 // completely in favor of AndroidLibraryDependency.ResourceNodesDepSet.manifest
976 //manifestDepSetBuilder.Transitive(transitiveStaticDeps.manifests)
977 _ = staticManifestsDepSet
978 a.manifestsDepSet = manifestDepSetBuilder.Build()
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800979
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500980 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -0800981 ctx.SetProvider(JavaInfoProvider, JavaInfo{
982 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500983 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
984 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -0800985 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
986 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
987 })
Sam Delmerico82602492022-06-10 17:05:42 +0000988
989 if proptools.Bool(a.properties.Extract_jni) {
990 for _, t := range ctx.MultiTargets() {
991 arch := t.Arch.Abi[0]
992 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
993 a.jniPackages = append(a.jniPackages, path)
994
995 outDir := android.PathForModuleOut(ctx, "aarForJni")
996 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
997 ctx.Build(pctx, android.BuildParams{
998 Rule: extractJNI,
999 Input: aarPath,
1000 Outputs: android.WritablePaths{path},
1001 Description: "extract JNI from AAR",
1002 Args: map[string]string{
1003 "outDir": outDir.String(),
1004 "archString": arch,
1005 },
1006 })
1007 }
1008
1009 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
1010 JniPackages: a.jniPackages,
1011 })
1012 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001013}
Colin Crossfabb6082018-02-20 17:22:23 -08001014
1015func (a *AARImport) HeaderJars() android.Paths {
1016 return android.Paths{a.classpathFile}
1017}
1018
Colin Cross331a1212018-08-15 20:40:52 -07001019func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
1020 return android.Paths{a.classpathFile}
1021}
1022
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +00001023func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -08001024 return nil
1025}
1026
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001027func (a *AARImport) DexJarInstallPath() android.Path {
1028 return nil
1029}
1030
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001031func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +09001032 return nil
1033}
1034
Jiyong Park45bf82e2020-12-15 22:29:02 +09001035var _ android.ApexModule = (*AARImport)(nil)
1036
1037// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001038func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1039 return a.depIsInSameApex(ctx, dep)
1040}
1041
Jiyong Park45bf82e2020-12-15 22:29:02 +09001042// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001043func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1044 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001045 return nil
1046}
1047
Sam Delmericoaf8bb702022-07-25 15:39:32 -04001048var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001049
Colin Cross1b16b0e2019-02-12 14:41:32 -08001050// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
1051//
1052// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
1053// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -08001054func AARImportFactory() android.Module {
1055 module := &AARImport{}
1056
1057 module.AddProperties(&module.properties)
1058
1059 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001060 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +00001061 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001062 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -08001063 return module
1064}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001065
1066type bazelAapt struct {
1067 Manifest bazel.Label
1068 Resource_files bazel.LabelListAttribute
1069}
1070
1071type bazelAndroidLibrary struct {
1072 *javaLibraryAttributes
1073 *bazelAapt
1074}
1075
1076type bazelAndroidLibraryImport struct {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001077 Aar bazel.Label
1078 Deps bazel.LabelListAttribute
1079 Exports bazel.LabelListAttribute
1080 Sdk_version bazel.StringAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001081}
1082
1083func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) *bazelAapt {
1084 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1085
1086 resourceFiles := bazel.LabelList{
1087 Includes: []bazel.Label{},
1088 }
1089 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1090 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1091 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1092 }
1093 return &bazelAapt{
1094 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1095 bazel.MakeLabelListAttribute(resourceFiles),
1096 }
1097}
1098
1099func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1100 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1101 exportableStaticLibs := []string{}
1102 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1103 for _, depName := range a.properties.Static_libs {
1104 if dep, ok := ctx.ModuleFromName(depName); ok {
1105 switch dep.(type) {
1106 case *AARImport, *Import:
1107 exportableStaticLibs = append(exportableStaticLibs, depName)
1108 }
1109 }
1110 }
1111 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1112 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1113 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1114
1115 ctx.CreateBazelTargetModule(
1116 bazel.BazelTargetModuleProperties{
1117 Rule_class: "aar_import",
Alixa381cd12023-05-10 14:49:38 +00001118 Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001119 },
1120 android.CommonAttributes{Name: name},
1121 &bazelAndroidLibraryImport{
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001122 Aar: aars.Includes[0],
1123 Deps: bazel.MakeLabelListAttribute(deps),
1124 Exports: bazel.MakeLabelListAttribute(exports),
1125 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001126 },
1127 )
1128
Alix14101de2023-01-06 03:42:07 +00001129 neverlink := true
1130 ctx.CreateBazelTargetModule(
Alix32540022023-03-16 21:06:13 +00001131 AndroidLibraryBazelTargetModuleProperties(),
Alix14101de2023-01-06 03:42:07 +00001132 android.CommonAttributes{Name: name + "-neverlink"},
1133 &bazelAndroidLibrary{
1134 javaLibraryAttributes: &javaLibraryAttributes{
1135 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1136 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001137 javaCommonAttributes: &javaCommonAttributes{
1138 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
1139 },
Alix14101de2023-01-06 03:42:07 +00001140 },
1141 },
1142 )
1143
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001144}
Alix32540022023-03-16 21:06:13 +00001145func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
1146 return bazel.BazelTargetModuleProperties{
1147 Rule_class: "android_library",
Alixa381cd12023-05-10 14:49:38 +00001148 Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
Alix32540022023-03-16 21:06:13 +00001149 }
1150}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001151
1152func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Alix8062f4d2022-11-14 21:38:07 +00001153 commonAttrs, bp2buildInfo := a.convertLibraryAttrsBp2Build(ctx)
1154 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001155
1156 deps := depLabels.Deps
1157 if !commonAttrs.Srcs.IsEmpty() {
1158 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1159 } else if !depLabels.Deps.IsEmpty() {
1160 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1161 }
Alix82fb94e2022-10-26 20:40:18 +00001162 name := a.Name()
Alix32540022023-03-16 21:06:13 +00001163 props := AndroidLibraryBazelTargetModuleProperties()
Alix82fb94e2022-10-26 20:40:18 +00001164
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001165 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001166 props,
1167 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001168 &bazelAndroidLibrary{
1169 &javaLibraryAttributes{
1170 javaCommonAttributes: commonAttrs,
1171 Deps: deps,
1172 Exports: depLabels.StaticDeps,
1173 },
1174 a.convertAaptAttrsWithBp2Build(ctx),
1175 },
1176 )
Alix82fb94e2022-10-26 20:40:18 +00001177
1178 neverlink := true
1179 ctx.CreateBazelTargetModule(
1180 props,
1181 android.CommonAttributes{Name: name + "-neverlink"},
1182 &bazelAndroidLibrary{
1183 javaLibraryAttributes: &javaLibraryAttributes{
1184 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1185 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001186 javaCommonAttributes: &javaCommonAttributes{
1187 Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
1188 Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
1189 },
Alix82fb94e2022-10-26 20:40:18 +00001190 },
1191 },
1192 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001193}