blob: 95b9a67bb8ff8aef3a47650e79b791a9aaf4ba03 [file] [log] [blame]
Colin Crossfabb6082018-02-20 17:22:23 -08001// Copyright 2018 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
Colin Crossa592e3e2019-02-19 16:59:53 -080018 "fmt"
Jaewoong Jung5b425e22019-06-17 17:40:56 -070019 "path/filepath"
Colin Crossc20dc852020-11-10 12:27:45 -080020 "strconv"
Colin Crossa97c5d32018-03-28 14:58:31 -070021 "strings"
Colin Crossfabb6082018-02-20 17:22:23 -080022
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080023 "android/soong/android"
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -050024 "android/soong/bazel"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010025 "android/soong/dexpreopt"
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080026
Colin Crossfabb6082018-02-20 17:22:23 -080027 "github.com/google/blueprint"
Colin Crossa97c5d32018-03-28 14:58:31 -070028 "github.com/google/blueprint/proptools"
Colin Crossfabb6082018-02-20 17:22:23 -080029)
30
Colin Crossa97c5d32018-03-28 14:58:31 -070031type AndroidLibraryDependency interface {
Jared Duke5979b302022-12-19 21:08:39 +000032 LibraryDependency
Colin Crossa97c5d32018-03-28 14:58:31 -070033 ExportPackage() android.Path
Colin Crossab8d1382023-07-14 17:23:41 +000034 ResourcesNodeDepSet() *android.DepSet[*resourcesNode]
35 RRODirsDepSet() *android.DepSet[rroDir]
36 ManifestsDepSet() *android.DepSet[android.Path]
Jaewoong Jungc779cd42020-10-06 18:56:10 -070037 SetRROEnforcedForDependent(enforce bool)
38 IsRROEnforced(ctx android.BaseModuleContext) bool
Colin Crossa97c5d32018-03-28 14:58:31 -070039}
40
41func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000042 RegisterAARBuildComponents(android.InitRegistrationContext)
43}
44
45func RegisterAARBuildComponents(ctx android.RegistrationContext) {
46 ctx.RegisterModuleType("android_library_import", AARImportFactory)
47 ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
Paul Duffin04ba70d2021-03-22 13:56:43 +000048 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
49 ctx.TopDown("propagate_rro_enforcement", propagateRROEnforcementMutator).Parallel()
50 })
Colin Crossa97c5d32018-03-28 14:58:31 -070051}
52
53//
54// AAR (android library)
55//
56
57type androidLibraryProperties struct {
58 BuildAAR bool `blueprint:"mutated"`
59}
60
61type aaptProperties struct {
62 // flags passed to aapt when creating the apk
63 Aaptflags []string
64
Dan Willemsen72be5902018-10-24 20:24:57 -070065 // include all resource configurations, not just the product-configured
66 // ones.
67 Aapt_include_all_resources *bool
68
Colin Crossa97c5d32018-03-28 14:58:31 -070069 // list of directories relative to the Blueprints file containing assets.
Colin Cross0ddae7f2019-02-07 15:30:01 -080070 // Defaults to ["assets"] if a directory called assets exists. Set to []
71 // to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070072 Asset_dirs []string
73
74 // list of directories relative to the Blueprints file containing
Colin Cross0ddae7f2019-02-07 15:30:01 -080075 // Android resources. Defaults to ["res"] if a directory called res exists.
76 // Set to [] to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070077 Resource_dirs []string
78
Colin Crossa592e3e2019-02-19 16:59:53 -080079 // list of zip files containing Android resources.
Colin Cross27b922f2019-03-04 22:35:41 -080080 Resource_zips []string `android:"path"`
Colin Crossa592e3e2019-02-19 16:59:53 -080081
Colin Crossa97c5d32018-03-28 14:58:31 -070082 // path to AndroidManifest.xml. If unset, defaults to "AndroidManifest.xml".
Colin Cross27b922f2019-03-04 22:35:41 -080083 Manifest *string `android:"path"`
changho.shinb5432b72019-08-08 18:37:17 +090084
85 // paths to additional manifest files to merge with main manifest.
86 Additional_manifests []string `android:"path"`
Sasha Smundak541056c2019-10-28 15:50:06 -070087
88 // do not include AndroidManifest from dependent libraries
89 Dont_merge_manifests *bool
Jaewoong Jungc779cd42020-10-06 18:56:10 -070090
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 Crossab8d1382023-07-14 17:23:41 +000096 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 Crossab8d1382023-07-14 17:23:41 +0000118
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 Crossab8d1382023-07-14 17:23:41 +0000145func (a *aapt) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
146 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800147}
148
Colin Crossab8d1382023-07-14 17:23:41 +0000149func (a *aapt) RRODirsDepSet() *android.DepSet[rroDir] {
150 return a.rroDirsDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800151}
152
Colin Crossab8d1382023-07-14 17:23:41 +0000153func (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")
Eric Miao40eab202023-03-30 16:57:17 +0000179 linkFlags = append(linkFlags, "--enable-compact-entries")
Colin Crossa97c5d32018-03-28 14:58:31 -0700180
181 // Find implicit or explicit asset and resource dirs
182 assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
183 resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
Colin Cross8a497952019-03-05 22:25:09 -0800184 resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
Colin Crossa97c5d32018-03-28 14:58:31 -0700185
Colin Crossa97c5d32018-03-28 14:58:31 -0700186 // Glob directories into lists of paths
187 for _, dir := range resourceDirs {
188 resDirs = append(resDirs, globbedResourceDir{
189 dir: dir,
190 files: androidResourceGlob(ctx, dir),
191 })
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700192 resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
Colin Crossa97c5d32018-03-28 14:58:31 -0700193 overlayDirs = append(overlayDirs, resOverlayDirs...)
194 rroDirs = append(rroDirs, resRRODirs...)
195 }
196
Colin Crossc20dc852020-11-10 12:27:45 -0800197 var assetDeps android.Paths
198 for i, dir := range assetDirs {
199 // Add a dependency on every file in the asset directory. This ensures the aapt2
200 // rule will be rerun if one of the files in the asset directory is modified.
201 assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
202
203 // Add a dependency on a file that contains a list of all the files in the asset directory.
204 // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
205 // or a file is added whose timestamp is older than the output of aapt2.
206 assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
207 androidResourceGlobList(ctx, dir, assetFileListFile)
208 assetDeps = append(assetDeps, assetFileListFile)
Colin Crossa97c5d32018-03-28 14:58:31 -0700209 }
210
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700211 assetDirStrings := assetDirs.Strings()
212 if a.noticeFile.Valid() {
213 assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
Colin Crossc20dc852020-11-10 12:27:45 -0800214 assetDeps = append(assetDeps, a.noticeFile.Path())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700215 }
216
Colin Crossa97c5d32018-03-28 14:58:31 -0700217 linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
218 linkDeps = append(linkDeps, manifestPath)
219
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700220 linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
Colin Crossc20dc852020-11-10 12:27:45 -0800221 linkDeps = append(linkDeps, assetDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700222
Spandan Das50885c02023-02-23 21:31:33 +0000223 // Returns the effective version for {min|target}_sdk_version
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000224 effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
Spandan Das50885c02023-02-23 21:31:33 +0000225 // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
226 // This is necessary for vendor modules.
227 // The effective version does not _only_ depend on {min|target}_sdk_version(level),
228 // but also on the sdk_version (kind+level)
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000229 if minSdkVersion.IsCurrent() {
Spandan Das50885c02023-02-23 21:31:33 +0000230 ret, err := sdkVersion.EffectiveVersionString(ctx)
231 if err != nil {
232 ctx.ModuleErrorf("invalid sdk_version: %s", err)
233 }
234 return ret
235 }
236 ret, err := minSdkVersion.EffectiveVersionString(ctx)
237 if err != nil {
238 ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
239 }
240 return ret
Jiyong Park6a927c42020-01-21 02:03:43 +0900241 }
Spandan Das50885c02023-02-23 21:31:33 +0000242 // SDK version flags
243 sdkVersion := sdkContext.SdkVersion(ctx)
244 minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
Colin Crossa97c5d32018-03-28 14:58:31 -0700245
Colin Cross83bb3162018-06-25 15:48:06 -0700246 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000247 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
248 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700249 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700250
Colin Crossa97c5d32018-03-28 14:58:31 -0700251 // Version code
252 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700253 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700254 }
255
256 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700257 var versionName string
258 if ctx.ModuleName() == "framework-res" {
259 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
260 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700261 // if it contains the build number. Use the PlatformVersionName instead.
262 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700263 } else {
264 versionName = ctx.Config().AppsDefaultVersionName()
265 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800266 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700267 linkFlags = append(linkFlags, "--version-name ", versionName)
268 }
269
Colin Crossa0ba2f52019-06-22 12:59:27 -0700270 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
271
272 // Always set --pseudo-localize, it will be stripped out later for release
273 // builds that don't want it.
274 compileFlags = append(compileFlags, "--pseudo-localize")
275
276 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700277}
278
Paul Duffin250e6192019-06-07 10:44:37 +0100279func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800280 if sdkDep.frameworkResModule != "" {
281 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700282 }
283}
284
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800285var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
286 blueprint.RuleParams{
287 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
288 CommandDeps: []string{"${config.Zip2ZipCmd}"},
289 })
290
Jiyong Parkf1691d22021-03-29 20:11:58 +0900291func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000292 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000293 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700294
Colin Crossab8d1382023-07-14 17:23:41 +0000295 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100296 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100297
Paul Duffin06530572022-02-03 17:54:15 +0000298 // Exclude any libraries from the supplied list.
299 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
300
Colin Cross31656952018-05-24 16:11:20 -0700301 // App manifest file
302 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
303 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
304
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000305 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000306 SdkContext: sdkContext,
307 ClassLoaderContexts: classLoaderContexts,
308 IsLibrary: a.isLibrary,
309 DefaultManifestVersion: a.defaultManifestVersion,
310 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
311 UsesNonSdkApis: a.usesNonSdkApis,
312 UseEmbeddedDex: a.useEmbeddedDex,
313 HasNoCode: a.hasNoCode,
314 LoggingParent: a.LoggingParent,
315 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000316 })
Colin Cross90c25c62019-04-19 16:22:57 -0700317
Colin Crossab8d1382023-07-14 17:23:41 +0000318 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
319
Luca Stefanifd898822019-09-10 22:13:31 +0200320 // Add additional manifest files to transitive manifests.
321 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
Colin Crossab8d1382023-07-14 17:23:41 +0000322 transitiveManifestPaths := append(android.Paths{manifestPath}, additionalManifests...)
323 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
324 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
325 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
326 // android_library_import modules. If this is fixed, staticManifestsDepSet can be dropped completely in favor of
327 // staticResourcesNodesDepSet.manifests()
328 transitiveManifestPaths = append(transitiveManifestPaths, staticManifestsDepSet.ToList()...)
Colin Cross90c25c62019-04-19 16:22:57 -0700329
Colin Crossab8d1382023-07-14 17:23:41 +0000330 if len(transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
331 a.mergedManifestFile = manifestMerger(ctx, transitiveManifestPaths[0], transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700332 if !a.isLibrary {
333 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
334 // will be propagated to the final application and merged there. The merged manifest for libraries is
335 // only passed to Make, which can't handle transitive dependencies.
336 manifestPath = a.mergedManifestFile
337 }
338 } else {
339 a.mergedManifestFile = manifestPath
340 }
Colin Cross31656952018-05-24 16:11:20 -0700341
Colin Crossa0ba2f52019-06-22 12:59:27 -0700342 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700343
344 linkFlags = append(linkFlags, libFlags...)
Colin Crossab8d1382023-07-14 17:23:41 +0000345 linkDeps = append(linkDeps, sharedDeps...)
346 linkDeps = append(linkDeps, staticDeps.resPackages()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700347 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700348 if a.isLibrary {
349 linkFlags = append(linkFlags, "--static-lib")
350 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700351
352 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900353 // the subdir "android" is required to be filtered by package names
354 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700355 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
356 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700357 // This file isn't used by Soong, but is generated for exporting
358 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Crossa97c5d32018-03-28 14:58:31 -0700359
Colin Cross4aaa84a2018-08-21 15:14:37 -0700360 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700361 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700362 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700363 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700364 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700365
Colin Crossa592e3e2019-02-19 16:59:53 -0800366 for i, zip := range resZips {
367 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700368 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800369 compiledResDirs = append(compiledResDirs, android.Paths{flata})
370 }
371
Colin Cross4aaa84a2018-08-21 15:14:37 -0700372 var compiledRes, compiledOverlay android.Paths
373
Colin Crossab8d1382023-07-14 17:23:41 +0000374 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
375 // of transitiveStaticLibs.
376 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
377
Colin Cross4aaa84a2018-08-21 15:14:37 -0700378 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
379
Colin Crossbec85302019-02-13 13:15:46 -0800380 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700381 // If we are using static android libraries, every source file becomes an overlay.
382 // This is to emulate old AAPT behavior which simulated library support.
383 for _, compiledResDir := range compiledResDirs {
384 compiledOverlay = append(compiledOverlay, compiledResDir...)
385 }
Colin Crossbec85302019-02-13 13:15:46 -0800386 } else if a.isLibrary {
387 // Otherwise, for a static library we treat all the resources equally with no overlay.
388 for _, compiledResDir := range compiledResDirs {
389 compiledRes = append(compiledRes, compiledResDir...)
390 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700391 } else if len(compiledResDirs) > 0 {
392 // Without static libraries, the first directory is our directory, which can then be
393 // overlaid by the rest.
394 compiledRes = append(compiledRes, compiledResDirs[0]...)
395 for _, compiledResDir := range compiledResDirs[1:] {
396 compiledOverlay = append(compiledOverlay, compiledResDir...)
397 }
398 }
399
Colin Crossa97c5d32018-03-28 14:58:31 -0700400 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700401 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700402 }
403
Colin Crosse560c4a2019-03-19 16:03:11 -0700404 var splitPackages android.WritablePaths
405 var splits []split
406
407 for _, s := range a.splitNames {
408 suffix := strings.Replace(s, ",", "_", -1)
409 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
410 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
411 splitPackages = append(splitPackages, path)
412 splits = append(splits, split{
413 name: s,
414 suffix: suffix,
415 path: path,
416 })
417 }
418
Colin Crossab8d1382023-07-14 17:23:41 +0000419 // No need to specify assets from dependencies to aapt2Link for libraries, all transitive assets will be
420 // provided to the final app aapt2Link step.
421 var transitiveAssets android.Paths
422 if !a.isLibrary {
423 transitiveAssets = android.ReverseSliceInPlace(staticDeps.assets())
424 }
Colin Cross66f78822018-05-02 12:58:28 -0700425 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt, extraPackages,
Colin Crossab8d1382023-07-14 17:23:41 +0000426 linkFlags, linkDeps, compiledRes, compiledOverlay, transitiveAssets, splitPackages)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800427
428 // Extract assets from the resource package output so that they can be used later in aapt2link
429 // for modules that depend on this one.
Colin Crossab8d1382023-07-14 17:23:41 +0000430 if android.PrefixInList(linkFlags, "-A ") {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800431 assets := android.PathForModuleOut(ctx, "assets.zip")
432 ctx.Build(pctx, android.BuildParams{
433 Rule: extractAssetsRule,
434 Input: packageRes,
435 Output: assets,
436 Description: "extract assets from built resource file",
437 })
438 a.assetPackage = android.OptionalPathForPath(assets)
439 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700440
441 a.aaptSrcJar = srcJar
442 a.exportPackage = packageRes
443 a.manifestPath = manifestPath
444 a.proguardOptionsFile = proguardOptionsFile
Colin Cross66f78822018-05-02 12:58:28 -0700445 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700446 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700447 a.splits = splits
Colin Crossab8d1382023-07-14 17:23:41 +0000448 a.resourcesNodesDepSet = android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL).
449 Direct(&resourcesNode{
450 resPackage: a.exportPackage,
451 manifest: a.manifestPath,
452 additionalManifests: additionalManifests,
453 assets: a.assetPackage,
454 }).
455 Transitive(staticResourcesNodesDepSet).Build()
456 a.rroDirsDepSet = android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL).
457 Direct(rroDirs...).
458 Transitive(staticRRODirsDepSet).Build()
459 a.manifestsDepSet = android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
460 Direct(a.manifestPath).
461 DirectSlice(additionalManifests).
462 Transitive(staticManifestsDepSet).Build()
463}
464
465type resourcesNode struct {
466 resPackage android.Path
467 manifest android.Path
468 additionalManifests android.Paths
469 assets android.OptionalPath
470}
471
472type transitiveAarDeps []*resourcesNode
473
474func (t transitiveAarDeps) resPackages() android.Paths {
475 var paths android.Paths
476 for _, dep := range t {
477 paths = append(paths, dep.resPackage)
478 }
479 return android.FirstUniquePaths(paths)
480}
481
482func (t transitiveAarDeps) manifests() android.Paths {
483 var paths android.Paths
484 for _, dep := range t {
485 paths = append(paths, dep.manifest)
486 paths = append(paths, dep.additionalManifests...)
487 }
488 return android.FirstUniquePaths(paths)
489}
490
491func (t transitiveAarDeps) assets() android.Paths {
492 var paths android.Paths
493 for _, dep := range t {
494 if dep.assets.Valid() {
495 paths = append(paths, dep.assets.Path())
496 }
497 }
498 return paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700499}
500
501// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900502func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Colin Crossab8d1382023-07-14 17:23:41 +0000503 staticResourcesNodes *android.DepSet[*resourcesNode], staticRRODirs *android.DepSet[rroDir],
504 staticManifests *android.DepSet[android.Path], sharedLibs android.Paths, flags []string) {
Colin Crossa97c5d32018-03-28 14:58:31 -0700505
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100506 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000507 // Not all callers need to compute class loader context, those who don't just pass nil.
508 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100509 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000510 }
511
Colin Cross83bb3162018-06-25 15:48:06 -0700512 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700513 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700514 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700515 }
516
Colin Crossab8d1382023-07-14 17:23:41 +0000517 var resourcesNodeDepSets []*android.DepSet[*resourcesNode]
518 rroDirsDepSetBuilder := android.NewDepSetBuilder[rroDir](android.TOPOLOGICAL)
519 manifestsDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL)
520
Colin Crossa97c5d32018-03-28 14:58:31 -0700521 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000522 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000523
Colin Crossa97c5d32018-03-28 14:58:31 -0700524 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700525 aarDep, _ := module.(AndroidLibraryDependency)
526 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700527 exportPackage = aarDep.ExportPackage()
528 }
529
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000530 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700531 case instrumentationForTag:
532 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400533 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700534 if exportPackage != nil {
535 sharedLibs = append(sharedLibs, exportPackage)
536 }
Colin Cross5446e882019-05-22 10:46:27 -0700537 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700538 if exportPackage != nil {
539 sharedLibs = append(sharedLibs, exportPackage)
540 }
541 case staticLibTag:
542 if exportPackage != nil {
Colin Crossab8d1382023-07-14 17:23:41 +0000543 resourcesNodeDepSets = append(resourcesNodeDepSets, aarDep.ResourcesNodeDepSet())
544 rroDirsDepSetBuilder.Transitive(aarDep.RRODirsDepSet())
545 manifestsDepSetBuilder.Transitive(aarDep.ManifestsDepSet())
Colin Crossa97c5d32018-03-28 14:58:31 -0700546 }
547 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000548
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000549 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700550 })
551
Colin Crossab8d1382023-07-14 17:23:41 +0000552 // AAPT2 overlays are in lowest to highest priority order, the topological order will be reversed later.
553 // Reverse the dependency order now going into the depset so that it comes out in order after the second
554 // reverse later.
555 // NOTE: this is legacy and probably incorrect behavior, for most other cases (e.g. conflicting classes in
556 // dependencies) the highest priority dependency is listed first, but for resources the highest priority
557 // dependency has to be listed last.
558 staticResourcesNodes = android.NewDepSet(android.TOPOLOGICAL, nil,
559 android.ReverseSliceInPlace(resourcesNodeDepSets))
Colin Crossa97c5d32018-03-28 14:58:31 -0700560
Colin Crossab8d1382023-07-14 17:23:41 +0000561 staticRRODirs = rroDirsDepSetBuilder.Build()
562 staticManifests = manifestsDepSetBuilder.Build()
563
564 if len(staticResourcesNodes.ToList()) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700565 flags = append(flags, "--auto-add-overlay")
566 }
567
568 for _, sharedLib := range sharedLibs {
569 flags = append(flags, "-I "+sharedLib.String())
570 }
571
Colin Crossab8d1382023-07-14 17:23:41 +0000572 return staticResourcesNodes, staticRRODirs, staticManifests, sharedLibs, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700573}
574
575type AndroidLibrary struct {
576 Library
577 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500578 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700579
580 androidLibraryProperties androidLibraryProperties
581
582 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700583}
584
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000585var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
586
587// For OutputFileProducer interface
588func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
589 switch tag {
590 case ".aar":
591 return []android.Path{a.aarFile}, nil
592 default:
593 return a.Library.OutputFiles(tag)
594 }
595}
596
Colin Crossa97c5d32018-03-28 14:58:31 -0700597var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
598
599func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
600 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900601 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100602 if sdkDep.hasFrameworkLibs() {
603 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700604 }
Colin Cross4a80a152022-12-21 21:51:52 -0800605 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700606}
607
608func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800609 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100610 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000611 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700612
Colin Cross56a83212020-09-15 18:30:11 -0700613 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
614
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000615 a.stem = proptools.StringDefault(a.overridableDeviceProperties.Stem, ctx.ModuleName())
616
Colin Crossa97c5d32018-03-28 14:58:31 -0700617 ctx.CheckbuildFile(a.proguardOptionsFile)
618 ctx.CheckbuildFile(a.exportPackage)
619 ctx.CheckbuildFile(a.aaptSrcJar)
620
621 // apps manifests are handled by aapt, don't let Module see them
622 a.properties.Manifest = nil
623
Colin Cross014489c2020-06-02 20:09:13 -0700624 a.linter.mergedManifest = a.aapt.mergedManifestFile
625 a.linter.manifest = a.aapt.manifestPath
626 a.linter.resources = a.aapt.resourceFiles
627
Colin Crossa97c5d32018-03-28 14:58:31 -0700628 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
629 a.proguardOptionsFile)
630
631 a.Module.compile(ctx, a.aaptSrcJar)
632
Colin Crossf57c5782019-01-25 13:20:38 -0800633 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700634 var res android.Paths
635 if a.androidLibraryProperties.BuildAAR {
636 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
637 ctx.CheckbuildFile(a.aarFile)
638 }
Colin Cross89c31582018-04-30 15:55:11 -0700639
Cole Faust9a631312020-10-22 21:05:24 +0000640 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
641 android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
Colin Crossab8d1382023-07-14 17:23:41 +0000642
Colin Cross89c31582018-04-30 15:55:11 -0700643 ctx.VisitDirectDeps(func(m android.Module) {
Jared Duke5979b302022-12-19 21:08:39 +0000644 if ctx.OtherModuleDependencyTag(m) == staticLibTag {
645 if lib, ok := m.(LibraryDependency); ok {
646 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
647 }
Colin Cross89c31582018-04-30 15:55:11 -0700648 }
649 })
Colin Cross89c31582018-04-30 15:55:11 -0700650 a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
Sam Delmerico82602492022-06-10 17:05:42 +0000651
652 prebuiltJniPackages := android.Paths{}
653 ctx.VisitDirectDeps(func(module android.Module) {
654 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
655 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
656 }
657 })
658 if len(prebuiltJniPackages) > 0 {
659 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
660 JniPackages: prebuiltJniPackages,
661 })
662 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700663}
664
Colin Cross1b16b0e2019-02-12 14:41:32 -0800665// android_library builds and links sources into a `.jar` file for the device along with Android resources.
666//
667// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000668// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800669// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
670// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700671func AndroidLibraryFactory() android.Module {
672 module := &AndroidLibrary{}
673
Colin Crossce6734e2020-06-15 16:09:53 -0700674 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700675 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700676 &module.aaptProperties,
677 &module.androidLibraryProperties)
678
679 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700680 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700681
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900682 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700683 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500684 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700685 return module
686}
687
Colin Crossfabb6082018-02-20 17:22:23 -0800688//
689// AAR (android library) prebuilts
690//
Colin Crossfabb6082018-02-20 17:22:23 -0800691
Vinh Trance0781f2022-04-13 01:30:44 +0000692// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800693type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000694 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800695 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000696 // If not blank, set to the version of the sdk to compile against.
697 // Defaults to private.
698 // Values are of one of the following forms:
699 // 1) numerical API level, "current", "none", or "core_platform"
700 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
701 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
702 // If the SDK kind is empty, it will be set to public
703 Sdk_version *string
704 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
705 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700706 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000707 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700708 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000709 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
710 Libs []string
711 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700712 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000713 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
714 // will be passed transitively through android_libraries to an android_app.
715 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
716 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800717}
718
719type AARImport struct {
720 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700721 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900722 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500723 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800724 prebuilt android.Prebuilt
725
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900726 // Functionality common to Module and Import.
727 embeddableInModuleAndImport
728
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500729 providesTransitiveHeaderJars
730
Colin Crossfabb6082018-02-20 17:22:23 -0800731 properties AARImportProperties
732
Colin Cross66f78822018-05-02 12:58:28 -0700733 classpathFile android.WritablePath
734 proguardFlags android.WritablePath
735 exportPackage android.WritablePath
736 extraAaptPackagesFile android.WritablePath
Colin Cross10f7c4a2018-05-23 10:59:28 -0700737 manifest android.WritablePath
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800738 assetsPackage android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700739
Colin Crossab8d1382023-07-14 17:23:41 +0000740 resourcesNodesDepSet *android.DepSet[*resourcesNode]
741 manifestsDepSet *android.DepSet[android.Path]
Colin Cross56a83212020-09-15 18:30:11 -0700742
743 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000744
Sam Delmerico82602492022-06-10 17:05:42 +0000745 aarPath android.Path
746 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900747
748 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000749 minSdkVersion android.ApiLevel
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000750}
751
752var _ android.OutputFileProducer = (*AARImport)(nil)
753
754// For OutputFileProducer interface
755func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
756 switch tag {
757 case ".aar":
758 return []android.Path{a.aarPath}, nil
759 case "":
760 return []android.Path{a.classpathFile}, nil
761 default:
762 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
763 }
Colin Crossfabb6082018-02-20 17:22:23 -0800764}
765
Jiyong Park92315372021-04-02 08:45:46 +0900766func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
767 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700768}
769
Jiyong Parkf1691d22021-03-29 20:11:58 +0900770func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100771 return ""
772}
773
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000774func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Colin Cross479884c2018-07-10 13:39:30 -0700775 if a.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000776 return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700777 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000778 return a.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -0700779}
780
Spandan Dasa26eda72023-03-02 00:56:06 +0000781func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
782 return android.SdkSpecFrom(ctx, "").ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000783}
784
Spandan Dasca70fc42023-03-01 23:38:49 +0000785func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
786 return a.SdkVersion(ctx).ApiLevel
Dan Willemsen419290a2018-10-31 15:28:47 -0700787}
788
Colin Cross1e743852019-10-28 11:37:20 -0700789func (a *AARImport) javaVersion() string {
790 return ""
791}
792
Colin Crossa97c5d32018-03-28 14:58:31 -0700793var _ AndroidLibraryDependency = (*AARImport)(nil)
794
795func (a *AARImport) ExportPackage() android.Path {
796 return a.exportPackage
797}
Colin Cross89c31582018-04-30 15:55:11 -0700798func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
799 return android.Paths{a.proguardFlags}
800}
801
Colin Crossab8d1382023-07-14 17:23:41 +0000802func (a *AARImport) ResourcesNodeDepSet() *android.DepSet[*resourcesNode] {
803 return a.resourcesNodesDepSet
Colin Crossc1c37552019-01-31 11:42:41 -0800804}
805
Colin Crossab8d1382023-07-14 17:23:41 +0000806func (a *AARImport) RRODirsDepSet() *android.DepSet[rroDir] {
807 return android.NewDepSet[rroDir](android.TOPOLOGICAL, nil, nil)
Colin Cross66f78822018-05-02 12:58:28 -0700808}
809
Colin Crossab8d1382023-07-14 17:23:41 +0000810func (a *AARImport) ManifestsDepSet() *android.DepSet[android.Path] {
811 return a.manifestsDepSet
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800812}
813
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700814// RRO enforcement is not available on aar_import since its RRO dirs are not
815// exported.
816func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
817}
818
819// RRO enforcement is not available on aar_import since its RRO dirs are not
820// exported.
821func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
822 return false
823}
824
Colin Crossfabb6082018-02-20 17:22:23 -0800825func (a *AARImport) Prebuilt() *android.Prebuilt {
826 return &a.prebuilt
827}
828
829func (a *AARImport) Name() string {
830 return a.prebuilt.Name(a.ModuleBase.Name())
831}
832
Jiyong Park618922e2020-01-08 13:35:43 +0900833func (a *AARImport) JacocoReportClassesFile() android.Path {
834 return nil
835}
836
Colin Crossfabb6082018-02-20 17:22:23 -0800837func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900838 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900839 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700840 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700841 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800842 }
843 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700844
Colin Cross42d48b72018-08-29 14:10:52 -0700845 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
846 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800847}
848
Sam Delmerico82602492022-06-10 17:05:42 +0000849type JniPackageInfo struct {
850 // List of zip files containing JNI libraries
851 // Zip files should have directory structure jni/<arch>/*.so
852 JniPackages android.Paths
853}
854
855var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
856
857// Unzip an AAR and extract the JNI libs for $archString.
858var extractJNI = pctx.AndroidStaticRule("extractJNI",
859 blueprint.RuleParams{
860 Command: `rm -rf $out $outDir && touch $out && ` +
861 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
862 `jni_files=$$(find $outDir/jni -type f) && ` +
863 // print error message if there are no JNI libs for this arch
864 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
865 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
866 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
867 CommandDeps: []string{"${config.SoongZipCmd}"},
868 },
869 "outDir", "archString")
870
Colin Crossfabb6082018-02-20 17:22:23 -0800871// 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 -0700872// 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 -0800873var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
874 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -0700875 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700876 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800877 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700878 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800879 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -0800880 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800881 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -0800882
883func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
884 if len(a.properties.Aars) != 1 {
885 ctx.PropertyErrorf("aars", "exactly one aar is required")
886 return
887 }
888
Jiyong Park92315372021-04-02 08:45:46 +0900889 a.sdkVersion = a.SdkVersion(ctx)
890 a.minSdkVersion = a.MinSdkVersion(ctx)
891
Colin Cross56a83212020-09-15 18:30:11 -0700892 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
893
Nan Zhang4c819fb2018-08-27 18:31:46 -0700894 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000895 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
896
Colin Cross1001a792019-03-21 22:21:39 -0700897 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000898 inputFile := a.aarPath
899 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
900 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -0700901 }
Colin Crossfabb6082018-02-20 17:22:23 -0800902
903 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -0700904 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Crossfabb6082018-02-20 17:22:23 -0800905 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
Colin Cross10f7c4a2018-05-23 10:59:28 -0700906 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800907 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Colin Crossfabb6082018-02-20 17:22:23 -0800908
909 ctx.Build(pctx, android.BuildParams{
910 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000911 Input: a.aarPath,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800912 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage},
Colin Crossfabb6082018-02-20 17:22:23 -0800913 Description: "unzip AAR",
914 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -0700915 "outDir": extractedAARDir.String(),
916 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800917 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -0800918 },
919 })
920
Colin Crossa0ba2f52019-06-22 12:59:27 -0700921 // Always set --pseudo-localize, it will be stripped out later for release
922 // builds that don't want it.
923 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -0800924 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -0800925 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000926 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -0800927
928 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900929 // the subdir "android" is required to be filtered by package names
930 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossfabb6082018-02-20 17:22:23 -0800931 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Crossa97c5d32018-03-28 14:58:31 -0700932 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700933 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -0800934
935 var linkDeps android.Paths
936
937 linkFlags := []string{
938 "--static-lib",
939 "--no-static-lib-packages",
940 "--auto-add-overlay",
941 }
942
Colin Cross10f7c4a2018-05-23 10:59:28 -0700943 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
944 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -0800945
Colin Crossab8d1382023-07-14 17:23:41 +0000946 staticResourcesNodesDepSet, staticRRODirsDepSet, staticManifestsDepSet, sharedLibs, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +0900947 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -0700948
Colin Crossab8d1382023-07-14 17:23:41 +0000949 _ = staticRRODirsDepSet
950 staticDeps := transitiveAarDeps(staticResourcesNodesDepSet.ToList())
Colin Crossfabb6082018-02-20 17:22:23 -0800951
Colin Crossab8d1382023-07-14 17:23:41 +0000952 // AAPT2 overlays are in lowest to highest priority order, reverse the topological order
953 // of transitiveStaticLibs.
954 transitiveStaticLibs := android.ReversePaths(staticDeps.resPackages())
955
956 linkDeps = append(linkDeps, sharedLibs...)
957 linkDeps = append(linkDeps, transitiveStaticLibs...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700958 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -0800959
Colin Cross66f78822018-05-02 12:58:28 -0700960 overlayRes := append(android.Paths{flata}, transitiveStaticLibs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800961
Colin Crossab8d1382023-07-14 17:23:41 +0000962 transitiveAssets := android.ReverseSliceInPlace(staticDeps.assets())
Colin Cross66f78822018-05-02 12:58:28 -0700963 aapt2Link(ctx, a.exportPackage, srcJar, proguardOptionsFile, rTxt, a.extraAaptPackagesFile,
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800964 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -0800965
Colin Crossab8d1382023-07-14 17:23:41 +0000966 resourcesNodesDepSetBuilder := android.NewDepSetBuilder[*resourcesNode](android.TOPOLOGICAL)
967 resourcesNodesDepSetBuilder.Direct(&resourcesNode{
968 resPackage: a.exportPackage,
969 manifest: a.manifest,
970 assets: android.OptionalPathForPath(a.assetsPackage),
971 })
972 resourcesNodesDepSetBuilder.Transitive(staticResourcesNodesDepSet)
973 a.resourcesNodesDepSet = resourcesNodesDepSetBuilder.Build()
974
975 manifestDepSetBuilder := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(a.manifest)
976 // TODO(b/288358614): Soong has historically not merged manifests from dependencies of android_library_import
977 // modules. Merging manifests from dependencies could remove the need for pom2bp to generate the "-nodeps" copies
978 // of androidx libraries, but doing so triggers errors due to errors introduced by existing dependencies of
979 // android_library_import modules. If this is fixed, AndroidLibraryDependency.ManifestsDepSet can be dropped
980 // completely in favor of AndroidLibraryDependency.ResourceNodesDepSet.manifest
981 //manifestDepSetBuilder.Transitive(transitiveStaticDeps.manifests)
982 _ = staticManifestsDepSet
983 a.manifestsDepSet = manifestDepSetBuilder.Build()
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800984
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500985 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -0800986 ctx.SetProvider(JavaInfoProvider, JavaInfo{
987 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500988 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
989 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -0800990 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
991 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
992 })
Sam Delmerico82602492022-06-10 17:05:42 +0000993
994 if proptools.Bool(a.properties.Extract_jni) {
995 for _, t := range ctx.MultiTargets() {
996 arch := t.Arch.Abi[0]
997 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
998 a.jniPackages = append(a.jniPackages, path)
999
1000 outDir := android.PathForModuleOut(ctx, "aarForJni")
1001 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
1002 ctx.Build(pctx, android.BuildParams{
1003 Rule: extractJNI,
1004 Input: aarPath,
1005 Outputs: android.WritablePaths{path},
1006 Description: "extract JNI from AAR",
1007 Args: map[string]string{
1008 "outDir": outDir.String(),
1009 "archString": arch,
1010 },
1011 })
1012 }
1013
1014 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
1015 JniPackages: a.jniPackages,
1016 })
1017 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001018}
Colin Crossfabb6082018-02-20 17:22:23 -08001019
1020func (a *AARImport) HeaderJars() android.Paths {
1021 return android.Paths{a.classpathFile}
1022}
1023
Colin Cross331a1212018-08-15 20:40:52 -07001024func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
1025 return android.Paths{a.classpathFile}
1026}
1027
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +00001028func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -08001029 return nil
1030}
1031
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001032func (a *AARImport) DexJarInstallPath() android.Path {
1033 return nil
1034}
1035
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001036func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +09001037 return nil
1038}
1039
Jiyong Park45bf82e2020-12-15 22:29:02 +09001040var _ android.ApexModule = (*AARImport)(nil)
1041
1042// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001043func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1044 return a.depIsInSameApex(ctx, dep)
1045}
1046
Jiyong Park45bf82e2020-12-15 22:29:02 +09001047// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001048func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1049 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001050 return nil
1051}
1052
Sam Delmericoaf8bb702022-07-25 15:39:32 -04001053var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -08001054
Colin Cross1b16b0e2019-02-12 14:41:32 -08001055// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
1056//
1057// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
1058// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -08001059func AARImportFactory() android.Module {
1060 module := &AARImport{}
1061
1062 module.AddProperties(&module.properties)
1063
1064 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +09001065 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +00001066 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001067 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -08001068 return module
1069}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001070
1071type bazelAapt struct {
1072 Manifest bazel.Label
1073 Resource_files bazel.LabelListAttribute
1074}
1075
1076type bazelAndroidLibrary struct {
1077 *javaLibraryAttributes
1078 *bazelAapt
1079}
1080
1081type bazelAndroidLibraryImport struct {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001082 Aar bazel.Label
1083 Deps bazel.LabelListAttribute
1084 Exports bazel.LabelListAttribute
1085 Sdk_version bazel.StringAttribute
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001086}
1087
1088func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) *bazelAapt {
1089 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1090
1091 resourceFiles := bazel.LabelList{
1092 Includes: []bazel.Label{},
1093 }
1094 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1095 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1096 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1097 }
1098 return &bazelAapt{
1099 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1100 bazel.MakeLabelListAttribute(resourceFiles),
1101 }
1102}
1103
1104func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1105 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1106 exportableStaticLibs := []string{}
1107 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1108 for _, depName := range a.properties.Static_libs {
1109 if dep, ok := ctx.ModuleFromName(depName); ok {
1110 switch dep.(type) {
1111 case *AARImport, *Import:
1112 exportableStaticLibs = append(exportableStaticLibs, depName)
1113 }
1114 }
1115 }
1116 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1117 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1118 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1119
1120 ctx.CreateBazelTargetModule(
1121 bazel.BazelTargetModuleProperties{
1122 Rule_class: "aar_import",
Alixa381cd12023-05-10 14:49:38 +00001123 Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001124 },
1125 android.CommonAttributes{Name: name},
1126 &bazelAndroidLibraryImport{
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001127 Aar: aars.Includes[0],
1128 Deps: bazel.MakeLabelListAttribute(deps),
1129 Exports: bazel.MakeLabelListAttribute(exports),
1130 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001131 },
1132 )
1133
Alix14101de2023-01-06 03:42:07 +00001134 neverlink := true
1135 ctx.CreateBazelTargetModule(
Alix32540022023-03-16 21:06:13 +00001136 AndroidLibraryBazelTargetModuleProperties(),
Alix14101de2023-01-06 03:42:07 +00001137 android.CommonAttributes{Name: name + "-neverlink"},
1138 &bazelAndroidLibrary{
1139 javaLibraryAttributes: &javaLibraryAttributes{
1140 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1141 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001142 javaCommonAttributes: &javaCommonAttributes{
1143 Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
1144 },
Alix14101de2023-01-06 03:42:07 +00001145 },
1146 },
1147 )
1148
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001149}
Alix32540022023-03-16 21:06:13 +00001150func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
1151 return bazel.BazelTargetModuleProperties{
1152 Rule_class: "android_library",
Alixa381cd12023-05-10 14:49:38 +00001153 Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
Alix32540022023-03-16 21:06:13 +00001154 }
1155}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001156
1157func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Alix8062f4d2022-11-14 21:38:07 +00001158 commonAttrs, bp2buildInfo := a.convertLibraryAttrsBp2Build(ctx)
1159 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001160
1161 deps := depLabels.Deps
1162 if !commonAttrs.Srcs.IsEmpty() {
1163 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1164 } else if !depLabels.Deps.IsEmpty() {
1165 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1166 }
Alix82fb94e2022-10-26 20:40:18 +00001167 name := a.Name()
Alix32540022023-03-16 21:06:13 +00001168 props := AndroidLibraryBazelTargetModuleProperties()
Alix82fb94e2022-10-26 20:40:18 +00001169
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001170 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001171 props,
1172 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001173 &bazelAndroidLibrary{
1174 &javaLibraryAttributes{
1175 javaCommonAttributes: commonAttrs,
1176 Deps: deps,
1177 Exports: depLabels.StaticDeps,
1178 },
1179 a.convertAaptAttrsWithBp2Build(ctx),
1180 },
1181 )
Alix82fb94e2022-10-26 20:40:18 +00001182
1183 neverlink := true
1184 ctx.CreateBazelTargetModule(
1185 props,
1186 android.CommonAttributes{Name: name + "-neverlink"},
1187 &bazelAndroidLibrary{
1188 javaLibraryAttributes: &javaLibraryAttributes{
1189 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1190 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05001191 javaCommonAttributes: &javaCommonAttributes{
1192 Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
1193 Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
1194 },
Alix82fb94e2022-10-26 20:40:18 +00001195 },
1196 },
1197 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001198}