blob: 068a9c7e81cbd795ac9f3140602805925e1d0040 [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
Anton Hansson53c88442019-03-18 15:53:16 +000034 ExportedRRODirs() []rroDir
Colin Cross66f78822018-05-02 12:58:28 -070035 ExportedStaticPackages() android.Paths
Colin Cross90c25c62019-04-19 16:22:57 -070036 ExportedManifests() android.Paths
Jaewoong Jung6431ca72020-01-15 14:15:10 -080037 ExportedAssets() android.OptionalPath
Jaewoong Jungc779cd42020-10-06 18:56:10 -070038 SetRROEnforcedForDependent(enforce bool)
39 IsRROEnforced(ctx android.BaseModuleContext) bool
Colin Crossa97c5d32018-03-28 14:58:31 -070040}
41
42func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000043 RegisterAARBuildComponents(android.InitRegistrationContext)
44}
45
46func RegisterAARBuildComponents(ctx android.RegistrationContext) {
47 ctx.RegisterModuleType("android_library_import", AARImportFactory)
48 ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
Paul Duffin04ba70d2021-03-22 13:56:43 +000049 ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
50 ctx.TopDown("propagate_rro_enforcement", propagateRROEnforcementMutator).Parallel()
51 })
Colin Crossa97c5d32018-03-28 14:58:31 -070052}
53
54//
55// AAR (android library)
56//
57
58type androidLibraryProperties struct {
59 BuildAAR bool `blueprint:"mutated"`
60}
61
62type aaptProperties struct {
63 // flags passed to aapt when creating the apk
64 Aaptflags []string
65
Dan Willemsen72be5902018-10-24 20:24:57 -070066 // include all resource configurations, not just the product-configured
67 // ones.
68 Aapt_include_all_resources *bool
69
Colin Crossa97c5d32018-03-28 14:58:31 -070070 // list of directories relative to the Blueprints file containing assets.
Colin Cross0ddae7f2019-02-07 15:30:01 -080071 // Defaults to ["assets"] if a directory called assets exists. Set to []
72 // to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070073 Asset_dirs []string
74
75 // list of directories relative to the Blueprints file containing
Colin Cross0ddae7f2019-02-07 15:30:01 -080076 // Android resources. Defaults to ["res"] if a directory called res exists.
77 // Set to [] to disable the default.
Colin Crossa97c5d32018-03-28 14:58:31 -070078 Resource_dirs []string
79
Colin Crossa592e3e2019-02-19 16:59:53 -080080 // list of zip files containing Android resources.
Colin Cross27b922f2019-03-04 22:35:41 -080081 Resource_zips []string `android:"path"`
Colin Crossa592e3e2019-02-19 16:59:53 -080082
Colin Crossa97c5d32018-03-28 14:58:31 -070083 // path to AndroidManifest.xml. If unset, defaults to "AndroidManifest.xml".
Colin Cross27b922f2019-03-04 22:35:41 -080084 Manifest *string `android:"path"`
changho.shinb5432b72019-08-08 18:37:17 +090085
86 // paths to additional manifest files to merge with main manifest.
87 Additional_manifests []string `android:"path"`
Sasha Smundak541056c2019-10-28 15:50:06 -070088
89 // do not include AndroidManifest from dependent libraries
90 Dont_merge_manifests *bool
Jaewoong Jungc779cd42020-10-06 18:56:10 -070091
92 // true if RRO is enforced for any of the dependent modules
93 RROEnforcedForDependent bool `blueprint:"mutated"`
Colin Crossa97c5d32018-03-28 14:58:31 -070094}
95
96type aapt struct {
Colin Cross90c25c62019-04-19 16:22:57 -070097 aaptSrcJar android.Path
98 exportPackage android.Path
99 manifestPath android.Path
100 transitiveManifestPaths android.Paths
101 proguardOptionsFile android.Path
102 rroDirs []rroDir
103 rTxt android.Path
104 extraAaptPackagesFile android.Path
105 mergedManifestFile android.Path
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700106 noticeFile android.OptionalPath
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800107 assetPackage android.OptionalPath
Colin Cross90c25c62019-04-19 16:22:57 -0700108 isLibrary bool
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100109 defaultManifestVersion string
Sasha Smundak6ad77252019-05-01 13:16:22 -0700110 useEmbeddedNativeLibs bool
Colin Cross90c25c62019-04-19 16:22:57 -0700111 useEmbeddedDex bool
112 usesNonSdkApis bool
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700113 hasNoCode bool
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800114 LoggingParent string
Colin Cross014489c2020-06-02 20:09:13 -0700115 resourceFiles android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700116
Colin Crosse560c4a2019-03-19 16:03:11 -0700117 splitNames []string
118 splits []split
119
Colin Crossa97c5d32018-03-28 14:58:31 -0700120 aaptProperties aaptProperties
121}
122
Colin Crosse560c4a2019-03-19 16:03:11 -0700123type split struct {
124 name string
125 suffix string
126 path android.Path
127}
128
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700129// Propagate RRO enforcement flag to static lib dependencies transitively.
130func propagateRROEnforcementMutator(ctx android.TopDownMutatorContext) {
131 m := ctx.Module()
132 if d, ok := m.(AndroidLibraryDependency); ok && d.IsRROEnforced(ctx) {
133 ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
134 if a, ok := d.(AndroidLibraryDependency); ok {
135 a.SetRROEnforcedForDependent(true)
136 }
137 })
138 }
139}
140
Colin Crossa97c5d32018-03-28 14:58:31 -0700141func (a *aapt) ExportPackage() android.Path {
142 return a.exportPackage
143}
144
Anton Hansson53c88442019-03-18 15:53:16 +0000145func (a *aapt) ExportedRRODirs() []rroDir {
Colin Crossc1c37552019-01-31 11:42:41 -0800146 return a.rroDirs
147}
148
Colin Cross90c25c62019-04-19 16:22:57 -0700149func (a *aapt) ExportedManifests() android.Paths {
150 return a.transitiveManifestPaths
Colin Crossc1c37552019-01-31 11:42:41 -0800151}
152
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800153func (a *aapt) ExportedAssets() android.OptionalPath {
154 return a.assetPackage
155}
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
Colin Crossa97c5d32018-03-28 14:58:31 -0700222 // SDK version flags
Jiyong Park92315372021-04-02 08:45:46 +0900223 minSdkVersion, err := sdkContext.MinSdkVersion(ctx).EffectiveVersionString(ctx)
Jiyong Park6a927c42020-01-21 02:03:43 +0900224 if err != nil {
225 ctx.ModuleErrorf("invalid minSdkVersion: %s", err)
226 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700227
Colin Cross83bb3162018-06-25 15:48:06 -0700228 linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
Spandan Das6450b552023-02-23 19:27:07 +0000229 // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
230 // This behavior has been copied from Make.
Colin Cross83bb3162018-06-25 15:48:06 -0700231 linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
Colin Crossa97c5d32018-03-28 14:58:31 -0700232
Colin Crossa97c5d32018-03-28 14:58:31 -0700233 // Version code
234 if !hasVersionCode {
Dan Albert4f378d72020-07-23 17:32:15 -0700235 linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
Colin Crossa97c5d32018-03-28 14:58:31 -0700236 }
237
238 if !hasVersionName {
Colin Cross402d5e02018-04-25 14:54:06 -0700239 var versionName string
240 if ctx.ModuleName() == "framework-res" {
241 // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
242 // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
Colin Crossbfd347d2018-05-09 11:11:35 -0700243 // if it contains the build number. Use the PlatformVersionName instead.
244 versionName = ctx.Config().PlatformVersionName()
Colin Cross402d5e02018-04-25 14:54:06 -0700245 } else {
246 versionName = ctx.Config().AppsDefaultVersionName()
247 }
Colin Cross0b9f31f2019-02-28 11:00:01 -0800248 versionName = proptools.NinjaEscape(versionName)
Colin Crossa97c5d32018-03-28 14:58:31 -0700249 linkFlags = append(linkFlags, "--version-name ", versionName)
250 }
251
Colin Crossa0ba2f52019-06-22 12:59:27 -0700252 linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
253
254 // Always set --pseudo-localize, it will be stripped out later for release
255 // builds that don't want it.
256 compileFlags = append(compileFlags, "--pseudo-localize")
257
258 return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
Colin Crossa97c5d32018-03-28 14:58:31 -0700259}
260
Paul Duffin250e6192019-06-07 10:44:37 +0100261func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
Colin Cross42308aa2018-11-14 21:44:17 -0800262 if sdkDep.frameworkResModule != "" {
263 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossa97c5d32018-03-28 14:58:31 -0700264 }
265}
266
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800267var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
268 blueprint.RuleParams{
269 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
270 CommandDeps: []string{"${config.Zip2ZipCmd}"},
271 })
272
Jiyong Parkf1691d22021-03-29 20:11:58 +0900273func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
Paul Duffin06530572022-02-03 17:54:15 +0000274 classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000275 enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
Colin Cross5446e882019-05-22 10:46:27 -0700276
Ulya Trafimovich18554242020-11-03 15:55:11 +0000277 transitiveStaticLibs, transitiveStaticLibManifests, staticRRODirs, assetPackages, libDeps, libFlags :=
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100278 aaptLibs(ctx, sdkContext, classLoaderContexts)
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100279
Paul Duffin06530572022-02-03 17:54:15 +0000280 // Exclude any libraries from the supplied list.
281 classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
282
Colin Cross31656952018-05-24 16:11:20 -0700283 // App manifest file
284 manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
285 manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
286
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000287 manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000288 SdkContext: sdkContext,
289 ClassLoaderContexts: classLoaderContexts,
290 IsLibrary: a.isLibrary,
291 DefaultManifestVersion: a.defaultManifestVersion,
292 UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
293 UsesNonSdkApis: a.usesNonSdkApis,
294 UseEmbeddedDex: a.useEmbeddedDex,
295 HasNoCode: a.hasNoCode,
296 LoggingParent: a.LoggingParent,
297 EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000298 })
Colin Cross90c25c62019-04-19 16:22:57 -0700299
Luca Stefanifd898822019-09-10 22:13:31 +0200300 // Add additional manifest files to transitive manifests.
301 additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
302 a.transitiveManifestPaths = append(android.Paths{manifestPath}, additionalManifests...)
303 a.transitiveManifestPaths = append(a.transitiveManifestPaths, transitiveStaticLibManifests...)
Colin Cross90c25c62019-04-19 16:22:57 -0700304
Sasha Smundak541056c2019-10-28 15:50:06 -0700305 if len(a.transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
Luca Stefanifd898822019-09-10 22:13:31 +0200306 a.mergedManifestFile = manifestMerger(ctx, a.transitiveManifestPaths[0], a.transitiveManifestPaths[1:], a.isLibrary)
Colin Cross90c25c62019-04-19 16:22:57 -0700307 if !a.isLibrary {
308 // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
309 // will be propagated to the final application and merged there. The merged manifest for libraries is
310 // only passed to Make, which can't handle transitive dependencies.
311 manifestPath = a.mergedManifestFile
312 }
313 } else {
314 a.mergedManifestFile = manifestPath
315 }
Colin Cross31656952018-05-24 16:11:20 -0700316
Colin Crossa0ba2f52019-06-22 12:59:27 -0700317 compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
Colin Cross31656952018-05-24 16:11:20 -0700318
Colin Crossc1c37552019-01-31 11:42:41 -0800319 rroDirs = append(rroDirs, staticRRODirs...)
Colin Cross31656952018-05-24 16:11:20 -0700320 linkFlags = append(linkFlags, libFlags...)
321 linkDeps = append(linkDeps, libDeps...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700322 linkFlags = append(linkFlags, extraLinkFlags...)
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700323 if a.isLibrary {
324 linkFlags = append(linkFlags, "--static-lib")
325 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700326
327 packageRes := android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900328 // the subdir "android" is required to be filtered by package names
329 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700330 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
331 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700332 // This file isn't used by Soong, but is generated for exporting
333 extraPackages := android.PathForModuleOut(ctx, "extra_packages")
Colin Crossa97c5d32018-03-28 14:58:31 -0700334
Colin Cross4aaa84a2018-08-21 15:14:37 -0700335 var compiledResDirs []android.Paths
Colin Crossa97c5d32018-03-28 14:58:31 -0700336 for _, dir := range resDirs {
Colin Cross014489c2020-06-02 20:09:13 -0700337 a.resourceFiles = append(a.resourceFiles, dir.files...)
Colin Crossa0ba2f52019-06-22 12:59:27 -0700338 compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
Colin Crossa97c5d32018-03-28 14:58:31 -0700339 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700340
Colin Crossa592e3e2019-02-19 16:59:53 -0800341 for i, zip := range resZips {
342 flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
Colin Crossa0ba2f52019-06-22 12:59:27 -0700343 aapt2CompileZip(ctx, flata, zip, "", compileFlags)
Colin Crossa592e3e2019-02-19 16:59:53 -0800344 compiledResDirs = append(compiledResDirs, android.Paths{flata})
345 }
346
Colin Cross4aaa84a2018-08-21 15:14:37 -0700347 var compiledRes, compiledOverlay android.Paths
348
349 compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
350
Colin Crossbec85302019-02-13 13:15:46 -0800351 if len(transitiveStaticLibs) > 0 {
Colin Cross4aaa84a2018-08-21 15:14:37 -0700352 // If we are using static android libraries, every source file becomes an overlay.
353 // This is to emulate old AAPT behavior which simulated library support.
354 for _, compiledResDir := range compiledResDirs {
355 compiledOverlay = append(compiledOverlay, compiledResDir...)
356 }
Colin Crossbec85302019-02-13 13:15:46 -0800357 } else if a.isLibrary {
358 // Otherwise, for a static library we treat all the resources equally with no overlay.
359 for _, compiledResDir := range compiledResDirs {
360 compiledRes = append(compiledRes, compiledResDir...)
361 }
Colin Cross4aaa84a2018-08-21 15:14:37 -0700362 } else if len(compiledResDirs) > 0 {
363 // Without static libraries, the first directory is our directory, which can then be
364 // overlaid by the rest.
365 compiledRes = append(compiledRes, compiledResDirs[0]...)
366 for _, compiledResDir := range compiledResDirs[1:] {
367 compiledOverlay = append(compiledOverlay, compiledResDir...)
368 }
369 }
370
Colin Crossa97c5d32018-03-28 14:58:31 -0700371 for _, dir := range overlayDirs {
Colin Crossa0ba2f52019-06-22 12:59:27 -0700372 compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700373 }
374
Colin Crosse560c4a2019-03-19 16:03:11 -0700375 var splitPackages android.WritablePaths
376 var splits []split
377
378 for _, s := range a.splitNames {
379 suffix := strings.Replace(s, ",", "_", -1)
380 path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
381 linkFlags = append(linkFlags, "--split", path.String()+":"+s)
382 splitPackages = append(splitPackages, path)
383 splits = append(splits, split{
384 name: s,
385 suffix: suffix,
386 path: path,
387 })
388 }
389
Colin Cross66f78822018-05-02 12:58:28 -0700390 aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt, extraPackages,
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800391 linkFlags, linkDeps, compiledRes, compiledOverlay, assetPackages, splitPackages)
392
393 // Extract assets from the resource package output so that they can be used later in aapt2link
394 // for modules that depend on this one.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800395 if android.PrefixInList(linkFlags, "-A ") || len(assetPackages) > 0 {
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800396 assets := android.PathForModuleOut(ctx, "assets.zip")
397 ctx.Build(pctx, android.BuildParams{
398 Rule: extractAssetsRule,
399 Input: packageRes,
400 Output: assets,
401 Description: "extract assets from built resource file",
402 })
403 a.assetPackage = android.OptionalPathForPath(assets)
404 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700405
406 a.aaptSrcJar = srcJar
407 a.exportPackage = packageRes
408 a.manifestPath = manifestPath
409 a.proguardOptionsFile = proguardOptionsFile
410 a.rroDirs = rroDirs
Colin Cross66f78822018-05-02 12:58:28 -0700411 a.extraAaptPackagesFile = extraPackages
Colin Crossa97c5d32018-03-28 14:58:31 -0700412 a.rTxt = rTxt
Colin Crosse560c4a2019-03-19 16:03:11 -0700413 a.splits = splits
Colin Crossa97c5d32018-03-28 14:58:31 -0700414}
415
416// aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
Jiyong Parkf1691d22021-03-29 20:11:58 +0900417func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
Ulya Trafimovich18554242020-11-03 15:55:11 +0000418 transitiveStaticLibs, transitiveStaticLibManifests android.Paths, staticRRODirs []rroDir, assets, deps android.Paths, flags []string) {
Colin Cross66f78822018-05-02 12:58:28 -0700419
Colin Crossa97c5d32018-03-28 14:58:31 -0700420 var sharedLibs android.Paths
421
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100422 if classLoaderContexts == nil {
Ulya Trafimovich18554242020-11-03 15:55:11 +0000423 // Not all callers need to compute class loader context, those who don't just pass nil.
424 // Create a temporary class loader context here (it will be computed, but not used).
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100425 classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000426 }
427
Colin Cross83bb3162018-06-25 15:48:06 -0700428 sdkDep := decodeSdkDep(ctx, sdkContext)
Colin Crossa97c5d32018-03-28 14:58:31 -0700429 if sdkDep.useFiles {
Colin Cross86a60ae2018-05-29 14:44:55 -0700430 sharedLibs = append(sharedLibs, sdkDep.jars...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700431 }
432
433 ctx.VisitDirectDeps(func(module android.Module) {
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000434 depTag := ctx.OtherModuleDependencyTag(module)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000435
Colin Crossa97c5d32018-03-28 14:58:31 -0700436 var exportPackage android.Path
Colin Cross66f78822018-05-02 12:58:28 -0700437 aarDep, _ := module.(AndroidLibraryDependency)
438 if aarDep != nil {
Colin Crossa97c5d32018-03-28 14:58:31 -0700439 exportPackage = aarDep.ExportPackage()
440 }
441
Ulya Trafimovich65b03192020-12-03 16:50:22 +0000442 switch depTag {
Colin Cross4b964c02018-10-15 16:18:06 -0700443 case instrumentationForTag:
444 // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
Liz Kammeref28a4c2022-09-23 16:50:56 -0400445 case sdkLibTag, libTag:
Colin Cross5446e882019-05-22 10:46:27 -0700446 if exportPackage != nil {
447 sharedLibs = append(sharedLibs, exportPackage)
448 }
Colin Cross5446e882019-05-22 10:46:27 -0700449 case frameworkResTag:
Colin Crossa97c5d32018-03-28 14:58:31 -0700450 if exportPackage != nil {
451 sharedLibs = append(sharedLibs, exportPackage)
452 }
453 case staticLibTag:
454 if exportPackage != nil {
Colin Cross66f78822018-05-02 12:58:28 -0700455 transitiveStaticLibs = append(transitiveStaticLibs, aarDep.ExportedStaticPackages()...)
Colin Crossbec85302019-02-13 13:15:46 -0800456 transitiveStaticLibs = append(transitiveStaticLibs, exportPackage)
Colin Cross90c25c62019-04-19 16:22:57 -0700457 transitiveStaticLibManifests = append(transitiveStaticLibManifests, aarDep.ExportedManifests()...)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800458 if aarDep.ExportedAssets().Valid() {
459 assets = append(assets, aarDep.ExportedAssets().Path())
460 }
Anton Hansson53c88442019-03-18 15:53:16 +0000461
Jeongik Chacee5ba92021-02-19 12:11:51 +0900462 outer:
463 for _, d := range aarDep.ExportedRRODirs() {
464 for _, e := range staticRRODirs {
465 if d.path == e.path {
466 continue outer
Anton Hansson53c88442019-03-18 15:53:16 +0000467 }
468 }
Jeongik Chacee5ba92021-02-19 12:11:51 +0900469 staticRRODirs = append(staticRRODirs, d)
Anton Hansson53c88442019-03-18 15:53:16 +0000470 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700471 }
472 }
Ulya Trafimovich18554242020-11-03 15:55:11 +0000473
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000474 addCLCFromDep(ctx, module, classLoaderContexts)
Colin Crossa97c5d32018-03-28 14:58:31 -0700475 })
476
477 deps = append(deps, sharedLibs...)
Colin Cross66f78822018-05-02 12:58:28 -0700478 deps = append(deps, transitiveStaticLibs...)
Colin Crossa97c5d32018-03-28 14:58:31 -0700479
Colin Cross66f78822018-05-02 12:58:28 -0700480 if len(transitiveStaticLibs) > 0 {
Colin Crossa97c5d32018-03-28 14:58:31 -0700481 flags = append(flags, "--auto-add-overlay")
482 }
483
484 for _, sharedLib := range sharedLibs {
485 flags = append(flags, "-I "+sharedLib.String())
486 }
487
Colin Cross66f78822018-05-02 12:58:28 -0700488 transitiveStaticLibs = android.FirstUniquePaths(transitiveStaticLibs)
Colin Cross90c25c62019-04-19 16:22:57 -0700489 transitiveStaticLibManifests = android.FirstUniquePaths(transitiveStaticLibManifests)
Colin Cross66f78822018-05-02 12:58:28 -0700490
Ulya Trafimovich18554242020-11-03 15:55:11 +0000491 return transitiveStaticLibs, transitiveStaticLibManifests, staticRRODirs, assets, deps, flags
Colin Crossa97c5d32018-03-28 14:58:31 -0700492}
493
494type AndroidLibrary struct {
495 Library
496 aapt
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500497 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700498
499 androidLibraryProperties androidLibraryProperties
500
501 aarFile android.WritablePath
Colin Cross89c31582018-04-30 15:55:11 -0700502
Jared Duke5979b302022-12-19 21:08:39 +0000503 exportedStaticPackages android.Paths
Colin Cross89c31582018-04-30 15:55:11 -0700504}
505
Saeid Farivar Asanjan1fca3012021-09-14 18:40:19 +0000506var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
507
508// For OutputFileProducer interface
509func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
510 switch tag {
511 case ".aar":
512 return []android.Path{a.aarFile}, nil
513 default:
514 return a.Library.OutputFiles(tag)
515 }
516}
517
Colin Cross66f78822018-05-02 12:58:28 -0700518func (a *AndroidLibrary) ExportedStaticPackages() android.Paths {
519 return a.exportedStaticPackages
520}
521
Colin Crossa97c5d32018-03-28 14:58:31 -0700522var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
523
524func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
525 a.Module.deps(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900526 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100527 if sdkDep.hasFrameworkLibs() {
528 a.aapt.deps(ctx, sdkDep)
Colin Crossa97c5d32018-03-28 14:58:31 -0700529 }
Colin Cross4a80a152022-12-21 21:51:52 -0800530 a.usesLibrary.deps(ctx, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700531}
532
533func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Crosse4246ab2019-02-05 21:55:21 -0800534 a.aapt.isLibrary = true
Ulya Trafimovich42c7f0d2021-08-17 16:20:29 +0100535 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Harshit Mahajan5b8b7302022-06-10 11:24:05 +0000536 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
Colin Crossa97c5d32018-03-28 14:58:31 -0700537
Colin Cross56a83212020-09-15 18:30:11 -0700538 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
539
Colin Crossa97c5d32018-03-28 14:58:31 -0700540 ctx.CheckbuildFile(a.proguardOptionsFile)
541 ctx.CheckbuildFile(a.exportPackage)
542 ctx.CheckbuildFile(a.aaptSrcJar)
543
544 // apps manifests are handled by aapt, don't let Module see them
545 a.properties.Manifest = nil
546
Colin Cross014489c2020-06-02 20:09:13 -0700547 a.linter.mergedManifest = a.aapt.mergedManifestFile
548 a.linter.manifest = a.aapt.manifestPath
549 a.linter.resources = a.aapt.resourceFiles
550
Colin Crossa97c5d32018-03-28 14:58:31 -0700551 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
552 a.proguardOptionsFile)
553
554 a.Module.compile(ctx, a.aaptSrcJar)
555
Colin Crossf57c5782019-01-25 13:20:38 -0800556 a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
Colin Crossa97c5d32018-03-28 14:58:31 -0700557 var res android.Paths
558 if a.androidLibraryProperties.BuildAAR {
559 BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
560 ctx.CheckbuildFile(a.aarFile)
561 }
Colin Cross89c31582018-04-30 15:55:11 -0700562
Cole Faust9a631312020-10-22 21:05:24 +0000563 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
564 android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
Colin Cross89c31582018-04-30 15:55:11 -0700565 ctx.VisitDirectDeps(func(m android.Module) {
Jared Duke5979b302022-12-19 21:08:39 +0000566 if ctx.OtherModuleDependencyTag(m) == staticLibTag {
567 if lib, ok := m.(LibraryDependency); ok {
568 a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
569 }
570 if alib, ok := m.(AndroidLibraryDependency); ok {
571 a.exportedStaticPackages = append(a.exportedStaticPackages, alib.ExportPackage())
572 a.exportedStaticPackages = append(a.exportedStaticPackages, alib.ExportedStaticPackages()...)
573 }
Colin Cross89c31582018-04-30 15:55:11 -0700574 }
575 })
Colin Cross89c31582018-04-30 15:55:11 -0700576 a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
Colin Cross66f78822018-05-02 12:58:28 -0700577 a.exportedStaticPackages = android.FirstUniquePaths(a.exportedStaticPackages)
Sam Delmerico82602492022-06-10 17:05:42 +0000578
579 prebuiltJniPackages := android.Paths{}
580 ctx.VisitDirectDeps(func(module android.Module) {
581 if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
582 prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
583 }
584 })
585 if len(prebuiltJniPackages) > 0 {
586 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
587 JniPackages: prebuiltJniPackages,
588 })
589 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700590}
591
Colin Cross1b16b0e2019-02-12 14:41:32 -0800592// android_library builds and links sources into a `.jar` file for the device along with Android resources.
593//
594// An android_library has a single variant that produces a `.jar` file containing `.class` files that were
Sam Delmerico82602492022-06-10 17:05:42 +0000595// compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
Colin Cross1b16b0e2019-02-12 14:41:32 -0800596// with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
597// an android_app module.
Colin Crossa97c5d32018-03-28 14:58:31 -0700598func AndroidLibraryFactory() android.Module {
599 module := &AndroidLibrary{}
600
Colin Crossce6734e2020-06-15 16:09:53 -0700601 module.Module.addHostAndDeviceProperties()
Colin Crossa97c5d32018-03-28 14:58:31 -0700602 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700603 &module.aaptProperties,
604 &module.androidLibraryProperties)
605
606 module.androidLibraryProperties.BuildAAR = true
Colin Cross014489c2020-06-02 20:09:13 -0700607 module.Module.linter.library = true
Colin Crossa97c5d32018-03-28 14:58:31 -0700608
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900609 android.InitApexModule(module)
Colin Cross48de9a42018-10-02 13:53:33 -0700610 InitJavaModule(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500611 android.InitBazelModule(module)
Colin Crossa97c5d32018-03-28 14:58:31 -0700612 return module
613}
614
Colin Crossfabb6082018-02-20 17:22:23 -0800615//
616// AAR (android library) prebuilts
617//
Colin Crossfabb6082018-02-20 17:22:23 -0800618
Vinh Trance0781f2022-04-13 01:30:44 +0000619// Properties for android_library_import
Colin Crossfabb6082018-02-20 17:22:23 -0800620type AARImportProperties struct {
Vinh Trance0781f2022-04-13 01:30:44 +0000621 // ARR (android library prebuilt) filepath. Exactly one ARR is required.
Colin Cross27b922f2019-03-04 22:35:41 -0800622 Aars []string `android:"path"`
Vinh Trance0781f2022-04-13 01:30:44 +0000623 // If not blank, set to the version of the sdk to compile against.
624 // Defaults to private.
625 // Values are of one of the following forms:
626 // 1) numerical API level, "current", "none", or "core_platform"
627 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
628 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
629 // If the SDK kind is empty, it will be set to public
630 Sdk_version *string
631 // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
632 // Defaults to sdk_version if not set. See sdk_version for possible values.
Colin Cross479884c2018-07-10 13:39:30 -0700633 Min_sdk_version *string
Vinh Trance0781f2022-04-13 01:30:44 +0000634 // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
Colin Crossa97c5d32018-03-28 14:58:31 -0700635 Static_libs []string
Vinh Trance0781f2022-04-13 01:30:44 +0000636 // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
637 Libs []string
638 // If set to true, run Jetifier against .aar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -0700639 Jetifier *bool
Sam Delmerico82602492022-06-10 17:05:42 +0000640 // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
641 // will be passed transitively through android_libraries to an android_app.
642 //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
643 Extract_jni *bool
Colin Crossfabb6082018-02-20 17:22:23 -0800644}
645
646type AARImport struct {
647 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -0700648 android.DefaultableModuleBase
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900649 android.ApexModuleBase
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500650 android.BazelModuleBase
Colin Crossfabb6082018-02-20 17:22:23 -0800651 prebuilt android.Prebuilt
652
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900653 // Functionality common to Module and Import.
654 embeddableInModuleAndImport
655
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500656 providesTransitiveHeaderJars
657
Colin Crossfabb6082018-02-20 17:22:23 -0800658 properties AARImportProperties
659
Colin Cross66f78822018-05-02 12:58:28 -0700660 classpathFile android.WritablePath
661 proguardFlags android.WritablePath
662 exportPackage android.WritablePath
663 extraAaptPackagesFile android.WritablePath
Colin Cross10f7c4a2018-05-23 10:59:28 -0700664 manifest android.WritablePath
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800665 assetsPackage android.WritablePath
Colin Cross66f78822018-05-02 12:58:28 -0700666
667 exportedStaticPackages android.Paths
Colin Cross56a83212020-09-15 18:30:11 -0700668
669 hideApexVariantFromMake bool
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000670
Sam Delmerico82602492022-06-10 17:05:42 +0000671 aarPath android.Path
672 jniPackages android.Paths
Jiyong Park92315372021-04-02 08:45:46 +0900673
674 sdkVersion android.SdkSpec
675 minSdkVersion android.SdkSpec
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000676}
677
678var _ android.OutputFileProducer = (*AARImport)(nil)
679
680// For OutputFileProducer interface
681func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
682 switch tag {
683 case ".aar":
684 return []android.Path{a.aarPath}, nil
685 case "":
686 return []android.Path{a.classpathFile}, nil
687 default:
688 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
689 }
Colin Crossfabb6082018-02-20 17:22:23 -0800690}
691
Jiyong Park92315372021-04-02 08:45:46 +0900692func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
693 return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
Colin Cross83bb3162018-06-25 15:48:06 -0700694}
695
Jiyong Parkf1691d22021-03-29 20:11:58 +0900696func (a *AARImport) SystemModules() string {
Paul Duffine25c6442019-10-11 13:50:28 +0100697 return ""
698}
699
Jiyong Park92315372021-04-02 08:45:46 +0900700func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Colin Cross479884c2018-07-10 13:39:30 -0700701 if a.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900702 return android.SdkSpecFrom(ctx, *a.properties.Min_sdk_version)
Colin Cross479884c2018-07-10 13:39:30 -0700703 }
Jiyong Park92315372021-04-02 08:45:46 +0900704 return a.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -0700705}
706
William Loh5a082f92022-05-17 20:21:50 +0000707func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
708 return android.SdkSpecFrom(ctx, "")
709}
710
Jiyong Park92315372021-04-02 08:45:46 +0900711func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
712 return a.SdkVersion(ctx)
Dan Willemsen419290a2018-10-31 15:28:47 -0700713}
714
Colin Cross1e743852019-10-28 11:37:20 -0700715func (a *AARImport) javaVersion() string {
716 return ""
717}
718
Colin Crossa97c5d32018-03-28 14:58:31 -0700719var _ AndroidLibraryDependency = (*AARImport)(nil)
720
721func (a *AARImport) ExportPackage() android.Path {
722 return a.exportPackage
723}
724
Colin Cross89c31582018-04-30 15:55:11 -0700725func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
726 return android.Paths{a.proguardFlags}
727}
728
Anton Hansson53c88442019-03-18 15:53:16 +0000729func (a *AARImport) ExportedRRODirs() []rroDir {
Colin Crossc1c37552019-01-31 11:42:41 -0800730 return nil
731}
732
Colin Cross66f78822018-05-02 12:58:28 -0700733func (a *AARImport) ExportedStaticPackages() android.Paths {
734 return a.exportedStaticPackages
735}
736
Colin Cross90c25c62019-04-19 16:22:57 -0700737func (a *AARImport) ExportedManifests() android.Paths {
738 return android.Paths{a.manifest}
Colin Cross31656952018-05-24 16:11:20 -0700739}
740
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800741func (a *AARImport) ExportedAssets() android.OptionalPath {
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800742 return android.OptionalPathForPath(a.assetsPackage)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800743}
744
Jaewoong Jungc779cd42020-10-06 18:56:10 -0700745// RRO enforcement is not available on aar_import since its RRO dirs are not
746// exported.
747func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
748}
749
750// RRO enforcement is not available on aar_import since its RRO dirs are not
751// exported.
752func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
753 return false
754}
755
Colin Crossfabb6082018-02-20 17:22:23 -0800756func (a *AARImport) Prebuilt() *android.Prebuilt {
757 return &a.prebuilt
758}
759
760func (a *AARImport) Name() string {
761 return a.prebuilt.Name(a.ModuleBase.Name())
762}
763
Jiyong Park618922e2020-01-08 13:35:43 +0900764func (a *AARImport) JacocoReportClassesFile() android.Path {
765 return nil
766}
767
Colin Crossfabb6082018-02-20 17:22:23 -0800768func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Jeongik Cha816a23a2020-07-08 01:09:23 +0900769 if !ctx.Config().AlwaysUsePrebuiltSdks() {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900770 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Colin Crossa97c5d32018-03-28 14:58:31 -0700771 if sdkDep.useModule && sdkDep.frameworkResModule != "" {
Colin Cross42d48b72018-08-29 14:10:52 -0700772 ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
Colin Crossfabb6082018-02-20 17:22:23 -0800773 }
774 }
Colin Crossa97c5d32018-03-28 14:58:31 -0700775
Colin Cross42d48b72018-08-29 14:10:52 -0700776 ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
777 ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800778}
779
Sam Delmerico82602492022-06-10 17:05:42 +0000780type JniPackageInfo struct {
781 // List of zip files containing JNI libraries
782 // Zip files should have directory structure jni/<arch>/*.so
783 JniPackages android.Paths
784}
785
786var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
787
788// Unzip an AAR and extract the JNI libs for $archString.
789var extractJNI = pctx.AndroidStaticRule("extractJNI",
790 blueprint.RuleParams{
791 Command: `rm -rf $out $outDir && touch $out && ` +
792 `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
793 `jni_files=$$(find $outDir/jni -type f) && ` +
794 // print error message if there are no JNI libs for this arch
795 `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
796 `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
797 `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
798 CommandDeps: []string{"${config.SoongZipCmd}"},
799 },
800 "outDir", "archString")
801
Colin Crossfabb6082018-02-20 17:22:23 -0800802// 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 -0700803// 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 -0800804var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
805 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -0700806 Command: `rm -rf $outDir && mkdir -p $outDir && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700807 `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800808 `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
Colin Cross205e9112020-08-06 13:20:17 -0700809 `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800810 CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
Colin Crossfabb6082018-02-20 17:22:23 -0800811 },
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800812 "outDir", "combinedClassesJar", "assetsPackage")
Colin Crossfabb6082018-02-20 17:22:23 -0800813
814func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
815 if len(a.properties.Aars) != 1 {
816 ctx.PropertyErrorf("aars", "exactly one aar is required")
817 return
818 }
819
Jiyong Park92315372021-04-02 08:45:46 +0900820 a.sdkVersion = a.SdkVersion(ctx)
821 a.minSdkVersion = a.MinSdkVersion(ctx)
822
Colin Cross56a83212020-09-15 18:30:11 -0700823 a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
824
Nan Zhang4c819fb2018-08-27 18:31:46 -0700825 aarName := ctx.ModuleName() + ".aar"
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000826 a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
827
Colin Cross1001a792019-03-21 22:21:39 -0700828 if Bool(a.properties.Jetifier) {
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000829 inputFile := a.aarPath
830 a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
831 TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
Nan Zhang4c819fb2018-08-27 18:31:46 -0700832 }
Colin Crossfabb6082018-02-20 17:22:23 -0800833
834 extractedAARDir := android.PathForModuleOut(ctx, "aar")
Colin Cross205e9112020-08-06 13:20:17 -0700835 a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
Colin Crossfabb6082018-02-20 17:22:23 -0800836 a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
Colin Cross10f7c4a2018-05-23 10:59:28 -0700837 a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800838 a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
Colin Crossfabb6082018-02-20 17:22:23 -0800839
840 ctx.Build(pctx, android.BuildParams{
841 Rule: unzipAAR,
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000842 Input: a.aarPath,
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800843 Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage},
Colin Crossfabb6082018-02-20 17:22:23 -0800844 Description: "unzip AAR",
845 Args: map[string]string{
Colin Cross205e9112020-08-06 13:20:17 -0700846 "outDir": extractedAARDir.String(),
847 "combinedClassesJar": a.classpathFile.String(),
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800848 "assetsPackage": a.assetsPackage.String(),
Colin Crossfabb6082018-02-20 17:22:23 -0800849 },
850 })
851
Colin Crossa0ba2f52019-06-22 12:59:27 -0700852 // Always set --pseudo-localize, it will be stripped out later for release
853 // builds that don't want it.
854 compileFlags := []string{"--pseudo-localize"}
Colin Crossfabb6082018-02-20 17:22:23 -0800855 compiledResDir := android.PathForModuleOut(ctx, "flat-res")
Colin Crossfabb6082018-02-20 17:22:23 -0800856 flata := compiledResDir.Join(ctx, "gen_res.flata")
Saeid Farivar Asanjanf0436962020-10-05 19:09:09 +0000857 aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
Colin Crossfabb6082018-02-20 17:22:23 -0800858
859 a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900860 // the subdir "android" is required to be filtered by package names
861 srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
Colin Crossfabb6082018-02-20 17:22:23 -0800862 proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
Colin Crossa97c5d32018-03-28 14:58:31 -0700863 rTxt := android.PathForModuleOut(ctx, "R.txt")
Colin Cross66f78822018-05-02 12:58:28 -0700864 a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
Colin Crossfabb6082018-02-20 17:22:23 -0800865
866 var linkDeps android.Paths
867
868 linkFlags := []string{
869 "--static-lib",
870 "--no-static-lib-packages",
871 "--auto-add-overlay",
872 }
873
Colin Cross10f7c4a2018-05-23 10:59:28 -0700874 linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
875 linkDeps = append(linkDeps, a.manifest)
Colin Crossfabb6082018-02-20 17:22:23 -0800876
Ulya Trafimovich18554242020-11-03 15:55:11 +0000877 transitiveStaticLibs, staticLibManifests, staticRRODirs, transitiveAssets, libDeps, libFlags :=
Jiyong Parkf1691d22021-03-29 20:11:58 +0900878 aaptLibs(ctx, android.SdkContext(a), nil)
Colin Cross31656952018-05-24 16:11:20 -0700879
880 _ = staticLibManifests
Colin Crossc1c37552019-01-31 11:42:41 -0800881 _ = staticRRODirs
Colin Crossfabb6082018-02-20 17:22:23 -0800882
Colin Crossa97c5d32018-03-28 14:58:31 -0700883 linkDeps = append(linkDeps, libDeps...)
884 linkFlags = append(linkFlags, libFlags...)
Colin Crossfabb6082018-02-20 17:22:23 -0800885
Colin Cross66f78822018-05-02 12:58:28 -0700886 overlayRes := append(android.Paths{flata}, transitiveStaticLibs...)
Colin Crossfabb6082018-02-20 17:22:23 -0800887
Colin Cross66f78822018-05-02 12:58:28 -0700888 aapt2Link(ctx, a.exportPackage, srcJar, proguardOptionsFile, rTxt, a.extraAaptPackagesFile,
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800889 linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
Colin Crossfabb6082018-02-20 17:22:23 -0800890
Michael Rosenfeld5ad15572021-12-03 13:25:10 -0800891 // Merge this import's assets with its dependencies' assets (if there are any).
892 if len(transitiveAssets) > 0 {
893 mergedAssets := android.PathForModuleOut(ctx, "merged-assets.zip")
894 inputZips := append(android.Paths{a.assetsPackage}, transitiveAssets...)
895 ctx.Build(pctx, android.BuildParams{
896 Rule: mergeAssetsRule,
897 Inputs: inputZips,
898 Output: mergedAssets,
899 Description: "merge assets from dependencies and self",
900 })
901 a.assetsPackage = mergedAssets
902 }
903
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500904 a.collectTransitiveHeaderJars(ctx)
Colin Crossdcf71b22021-02-01 13:59:03 -0800905 ctx.SetProvider(JavaInfoProvider, JavaInfo{
906 HeaderJars: android.PathsIfNonNil(a.classpathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500907 TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
908 TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -0800909 ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
910 ImplementationJars: android.PathsIfNonNil(a.classpathFile),
911 })
Sam Delmerico82602492022-06-10 17:05:42 +0000912
913 if proptools.Bool(a.properties.Extract_jni) {
914 for _, t := range ctx.MultiTargets() {
915 arch := t.Arch.Abi[0]
916 path := android.PathForModuleOut(ctx, arch+"_jni.zip")
917 a.jniPackages = append(a.jniPackages, path)
918
919 outDir := android.PathForModuleOut(ctx, "aarForJni")
920 aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
921 ctx.Build(pctx, android.BuildParams{
922 Rule: extractJNI,
923 Input: aarPath,
924 Outputs: android.WritablePaths{path},
925 Description: "extract JNI from AAR",
926 Args: map[string]string{
927 "outDir": outDir.String(),
928 "archString": arch,
929 },
930 })
931 }
932
933 ctx.SetProvider(JniPackageProvider, JniPackageInfo{
934 JniPackages: a.jniPackages,
935 })
936 }
Colin Crossdcf71b22021-02-01 13:59:03 -0800937}
Colin Crossfabb6082018-02-20 17:22:23 -0800938
939func (a *AARImport) HeaderJars() android.Paths {
940 return android.Paths{a.classpathFile}
941}
942
Colin Cross331a1212018-08-15 20:40:52 -0700943func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
944 return android.Paths{a.classpathFile}
945}
946
Ulyana Trafimovich5539e7b2020-06-04 14:08:17 +0000947func (a *AARImport) DexJarBuildPath() android.Path {
Colin Crossf24a22a2019-01-31 14:12:44 -0800948 return nil
949}
950
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100951func (a *AARImport) DexJarInstallPath() android.Path {
952 return nil
953}
954
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100955func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
Jiyong Park1be96912018-05-28 18:02:19 +0900956 return nil
957}
958
Jiyong Park45bf82e2020-12-15 22:29:02 +0900959var _ android.ApexModule = (*AARImport)(nil)
960
961// Implements android.ApexModule
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900962func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
963 return a.depIsInSameApex(ctx, dep)
964}
965
Jiyong Park45bf82e2020-12-15 22:29:02 +0900966// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -0700967func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
968 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +0900969 return nil
970}
971
Sam Delmericoaf8bb702022-07-25 15:39:32 -0400972var _ android.PrebuiltInterface = (*AARImport)(nil)
Colin Crossfabb6082018-02-20 17:22:23 -0800973
Colin Cross1b16b0e2019-02-12 14:41:32 -0800974// android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
975//
976// This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
977// an android_app module.
Colin Crossfabb6082018-02-20 17:22:23 -0800978func AARImportFactory() android.Module {
979 module := &AARImport{}
980
981 module.AddProperties(&module.properties)
982
983 android.InitPrebuiltModule(module, &module.properties.Aars)
Jooyung Hanacc7bbe2020-05-20 09:06:00 +0900984 android.InitApexModule(module)
Sam Delmerico82602492022-06-10 17:05:42 +0000985 InitJavaModuleMultiTargets(module, android.DeviceSupported)
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500986 android.InitBazelModule(module)
Colin Crossfabb6082018-02-20 17:22:23 -0800987 return module
988}
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -0500989
990type bazelAapt struct {
991 Manifest bazel.Label
992 Resource_files bazel.LabelListAttribute
993}
994
995type bazelAndroidLibrary struct {
996 *javaLibraryAttributes
997 *bazelAapt
998}
999
1000type bazelAndroidLibraryImport struct {
1001 Aar bazel.Label
1002 Deps bazel.LabelListAttribute
1003 Exports bazel.LabelListAttribute
1004}
1005
1006func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) *bazelAapt {
1007 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1008
1009 resourceFiles := bazel.LabelList{
1010 Includes: []bazel.Label{},
1011 }
1012 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1013 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1014 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1015 }
1016 return &bazelAapt{
1017 android.BazelLabelForModuleSrcSingle(ctx, manifest),
1018 bazel.MakeLabelListAttribute(resourceFiles),
1019 }
1020}
1021
1022func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1023 aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
1024 exportableStaticLibs := []string{}
1025 // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
1026 for _, depName := range a.properties.Static_libs {
1027 if dep, ok := ctx.ModuleFromName(depName); ok {
1028 switch dep.(type) {
1029 case *AARImport, *Import:
1030 exportableStaticLibs = append(exportableStaticLibs, depName)
1031 }
1032 }
1033 }
1034 name := android.RemoveOptionalPrebuiltPrefix(a.Name())
1035 deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
1036 exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
1037
1038 ctx.CreateBazelTargetModule(
1039 bazel.BazelTargetModuleProperties{
1040 Rule_class: "aar_import",
Romain Jobredeaux5ccb4602022-12-19 11:17:16 -05001041 Bzl_load_location: "//build/bazel/rules/android:rules.bzl",
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001042 },
1043 android.CommonAttributes{Name: name},
1044 &bazelAndroidLibraryImport{
1045 Aar: aars.Includes[0],
1046 Deps: bazel.MakeLabelListAttribute(deps),
1047 Exports: bazel.MakeLabelListAttribute(exports),
1048 },
1049 )
1050
Alix14101de2023-01-06 03:42:07 +00001051 neverlink := true
1052 ctx.CreateBazelTargetModule(
1053 bazel.BazelTargetModuleProperties{
1054 Rule_class: "android_library",
1055 Bzl_load_location: "//build/bazel/rules/android:rules.bzl",
1056 },
1057 android.CommonAttributes{Name: name + "-neverlink"},
1058 &bazelAndroidLibrary{
1059 javaLibraryAttributes: &javaLibraryAttributes{
1060 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1061 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
1062 },
1063 },
1064 )
1065
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001066}
1067
1068func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Alix8062f4d2022-11-14 21:38:07 +00001069 commonAttrs, bp2buildInfo := a.convertLibraryAttrsBp2Build(ctx)
1070 depLabels := bp2buildInfo.DepLabels
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001071
1072 deps := depLabels.Deps
1073 if !commonAttrs.Srcs.IsEmpty() {
1074 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1075 } else if !depLabels.Deps.IsEmpty() {
1076 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
1077 }
1078
Alix36795a72023-01-20 16:10:52 +00001079 if len(a.properties.Common_srcs) != 0 {
1080 commonAttrs.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, a.properties.Common_srcs))
1081 }
1082
Alix82fb94e2022-10-26 20:40:18 +00001083 name := a.Name()
1084 props := bazel.BazelTargetModuleProperties{
1085 Rule_class: "android_library",
Romain Jobredeaux5ccb4602022-12-19 11:17:16 -05001086 Bzl_load_location: "//build/bazel/rules/android:rules.bzl",
Alix82fb94e2022-10-26 20:40:18 +00001087 }
1088
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001089 ctx.CreateBazelTargetModule(
Alix82fb94e2022-10-26 20:40:18 +00001090 props,
1091 android.CommonAttributes{Name: name},
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001092 &bazelAndroidLibrary{
1093 &javaLibraryAttributes{
1094 javaCommonAttributes: commonAttrs,
1095 Deps: deps,
1096 Exports: depLabels.StaticDeps,
1097 },
1098 a.convertAaptAttrsWithBp2Build(ctx),
1099 },
1100 )
Alix82fb94e2022-10-26 20:40:18 +00001101
1102 neverlink := true
1103 ctx.CreateBazelTargetModule(
1104 props,
1105 android.CommonAttributes{Name: name + "-neverlink"},
1106 &bazelAndroidLibrary{
1107 javaLibraryAttributes: &javaLibraryAttributes{
1108 Neverlink: bazel.BoolAttribute{Value: &neverlink},
1109 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
1110 },
1111 },
1112 )
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05001113}