blob: 2b52eab15833517dd2af1984ddeb12af611f6bd9 [file] [log] [blame]
Colin Cross30e076a2015-04-13 13:58:27 -07001// Copyright 2015 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
Jaewoong Jungf9b44652020-12-21 12:29:12 -080017// This file contains the module implementations for android_app, android_test, and some more
18// related module types, including their override variants.
Colin Cross30e076a2015-04-13 13:58:27 -070019
20import (
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070021 "path/filepath"
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070022 "strings"
Colin Cross30e076a2015-04-13 13:58:27 -070023
Colin Cross50ddcc42019-05-16 12:28:22 -070024 "github.com/google/blueprint"
25 "github.com/google/blueprint/proptools"
26
Colin Cross635c3b02016-05-18 15:37:25 -070027 "android/soong/android"
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -040028 "android/soong/bazel"
Colin Crossa4f08812018-10-02 22:03:40 -070029 "android/soong/cc"
Ulya Trafimovichd4bcea42020-06-03 14:57:22 +010030 "android/soong/dexpreopt"
Colin Cross303e21f2018-08-07 16:49:25 -070031 "android/soong/tradefed"
Colin Cross30e076a2015-04-13 13:58:27 -070032)
33
Colin Cross3bc7ffa2017-11-22 16:19:37 -080034func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000035 RegisterAppBuildComponents(android.InitRegistrationContext)
Colin Cross3bc7ffa2017-11-22 16:19:37 -080036}
37
Paul Duffinf9b1da02019-12-18 19:51:55 +000038func RegisterAppBuildComponents(ctx android.RegistrationContext) {
39 ctx.RegisterModuleType("android_app", AndroidAppFactory)
40 ctx.RegisterModuleType("android_test", AndroidTestFactory)
41 ctx.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
42 ctx.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
43 ctx.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
44 ctx.RegisterModuleType("override_android_test", OverrideAndroidTestModuleFactory)
Paul Duffinf9b1da02019-12-18 19:51:55 +000045}
46
Colin Cross30e076a2015-04-13 13:58:27 -070047// AndroidManifest.xml merging
48// package splits
49
Colin Crossfabb6082018-02-20 17:22:23 -080050type appProperties struct {
Colin Crossbd01e2a2018-10-04 15:21:03 -070051 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
Colin Cross7d5136f2015-05-11 13:39:40 -070052 Additional_certificates []string
53
54 // If set, create package-export.apk, which other packages can
55 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
Nan Zhangea568a42017-11-08 21:20:04 -080056 Export_package_resources *bool
Colin Cross7d5136f2015-05-11 13:39:40 -070057
Colin Cross16056062017-12-13 22:46:28 -080058 // Specifies that this app should be installed to the priv-app directory,
59 // where the system will grant it additional privileges not available to
60 // normal apps.
61 Privileged *bool
Colin Crossa97c5d32018-03-28 14:58:31 -070062
63 // list of resource labels to generate individual resource packages
64 Package_splits []string
Jason Monkd4122be2018-08-10 09:33:36 -040065
66 // Names of modules to be overridden. Listed modules can only be other binaries
67 // (in Make or Soong).
68 // This does not completely prevent installation of the overridden binaries, but if both
69 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
70 // from PRODUCT_PACKAGES.
71 Overrides []string
Colin Crossa4f08812018-10-02 22:03:40 -070072
73 // list of native libraries that will be provided in or alongside the resulting jar
74 Jni_libs []string `android:"arch_variant"`
75
Colin Cross7204cf02020-05-06 17:51:39 -070076 // if true, use JNI libraries that link against platform APIs even if this module sets
Colin Crossee87c602020-02-19 16:57:15 -080077 // sdk_version.
78 Jni_uses_platform_apis *bool
79
Colin Cross7204cf02020-05-06 17:51:39 -070080 // if true, use JNI libraries that link against SDK APIs even if this module does not set
81 // sdk_version.
82 Jni_uses_sdk_apis *bool
83
Jaewoong Jungbc625cd2019-05-06 15:48:44 -070084 // STL library to use for JNI libraries.
85 Stl *string `android:"arch_variant"`
86
Colin Crosse4246ab2019-02-05 21:55:21 -080087 // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
88 // flag so that they are used from inside the APK at runtime. Defaults to true for android_test modules unless
Jiyong Park52cd06f2019-11-11 10:14:32 +090089 // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to true for
90 // android_app modules that are embedded to APEXes, defaults to false for other module types where the native
91 // libraries are generally preinstalled outside the APK.
Colin Crosse4246ab2019-02-05 21:55:21 -080092 Use_embedded_native_libs *bool
Colin Cross46abdad2019-02-07 13:07:08 -080093
94 // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
95 // they are used from inside the APK at runtime.
96 Use_embedded_dex *bool
Colin Cross47fa9d32019-03-26 10:51:39 -070097
98 // Forces native libraries to always be packaged into the APK,
99 // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
100 // True for android_test* modules.
101 AlwaysPackageNativeLibs bool `blueprint:"mutated"`
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700102
103 // If set, find and merge all NOTICE files that this module and its dependencies have and store
104 // it in the APK as an asset.
105 Embed_notices *bool
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700106
107 // cc.Coverage related properties
108 PreventInstall bool `blueprint:"mutated"`
109 HideFromMake bool `blueprint:"mutated"`
110 IsCoverageVariant bool `blueprint:"mutated"`
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100111
112 // Whether this app is considered mainline updatable or not. When set to true, this will enforce
Artur Satayevf40fc852020-04-16 13:43:02 +0100113 // additional rules to make sure an app can safely be updated. Default is false.
114 // Prefer using other specific properties if build behaviour must be changed; avoid using this
115 // flag for anything but neverallow rules (unless the behaviour change is invisible to owners).
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100116 Updatable *bool
Colin Cross7d5136f2015-05-11 13:39:40 -0700117}
118
Jaewoong Jung525443a2019-02-28 15:35:54 -0800119// android_app properties that can be overridden by override_android_app
120type overridableAppProperties struct {
121 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
122 // or an android_app_certificate module name in the form ":module".
123 Certificate *string
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700124
Jaewoong Jung1c1b6e62021-03-09 15:02:31 -0800125 // Name of the signing certificate lineage file or filegroup module.
126 Lineage *string `android:"path"`
Liz Kammere2b27f42020-05-07 13:24:05 -0700127
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700128 // the package name of this app. The package name in the manifest file is used if one was not given.
129 Package_name *string
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800130
131 // the logging parent of this app.
132 Logging_parent *string
Liz Kammer9f9fd022020-06-18 19:44:06 +0000133
134 // Whether to rename the package in resources to the override name rather than the base name. Defaults to true.
135 Rename_resources_package *bool
Jaewoong Jung525443a2019-02-28 15:35:54 -0800136}
137
Colin Cross30e076a2015-04-13 13:58:27 -0700138type AndroidApp struct {
Romain Jobredeaux1282c422021-10-29 10:52:59 -0400139 android.BazelModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700140 Library
141 aapt
Jaewoong Jung525443a2019-02-28 15:35:54 -0800142 android.OverridableModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700143
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900144 certificate Certificate
Colin Cross30e076a2015-04-13 13:58:27 -0700145
Colin Crossfabb6082018-02-20 17:22:23 -0800146 appProperties appProperties
Colin Crossae5caf52018-05-22 11:11:52 -0700147
Jaewoong Jung525443a2019-02-28 15:35:54 -0800148 overridableAppProperties overridableAppProperties
149
Colin Cross403cc152020-07-06 14:15:24 -0700150 jniLibs []jniLib
151 installPathForJNISymbols android.Path
152 embeddedJniLibs bool
153 jniCoverageOutputs android.Paths
Colin Crossf6237212018-10-29 23:14:58 -0700154
155 bundleFile android.Path
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800156
157 // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
158 installApkName string
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800159
Colin Cross70dda7e2019-10-01 22:05:35 -0700160 installDir android.InstallPath
Jaewoong Jung0949f312019-09-11 10:25:18 -0700161
Jaewoong Jung7dd4ae22019-09-27 17:13:15 -0700162 onDeviceDir string
163
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800164 additionalAaptFlags []string
Jaewoong Jung98772792019-07-01 17:15:13 -0700165
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900166 overriddenManifestPackageName string
Artur Satayev1111b842020-04-27 19:05:28 +0100167
168 android.ApexBundleDepsInfo
Colin Crosse1731a52017-12-14 11:22:55 -0800169}
170
Martin Stjernholm6d415272020-01-31 17:10:36 +0000171func (a *AndroidApp) IsInstallable() bool {
172 return Bool(a.properties.Installable)
173}
174
Colin Cross89c31582018-04-30 15:55:11 -0700175func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
176 return nil
177}
178
Colin Cross66f78822018-05-02 12:58:28 -0700179func (a *AndroidApp) ExportedStaticPackages() android.Paths {
180 return nil
181}
182
Sundong Ahne1f05aa2019-08-27 13:55:42 +0900183func (a *AndroidApp) OutputFile() android.Path {
184 return a.outputFile
185}
186
Colin Cross503c1d02020-01-28 14:00:53 -0800187func (a *AndroidApp) Certificate() Certificate {
188 return a.certificate
189}
190
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700191func (a *AndroidApp) JniCoverageOutputs() android.Paths {
192 return a.jniCoverageOutputs
193}
194
Colin Crossa97c5d32018-03-28 14:58:31 -0700195var _ AndroidLibraryDependency = (*AndroidApp)(nil)
196
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900197type Certificate struct {
Colin Cross503c1d02020-01-28 14:00:53 -0800198 Pem, Key android.Path
199 presigned bool
200}
201
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700202var PresignedCertificate = Certificate{presigned: true}
Colin Cross503c1d02020-01-28 14:00:53 -0800203
204func (c Certificate) AndroidMkString() string {
205 if c.presigned {
206 return "PRESIGNED"
207 } else {
208 return c.Pem.String()
209 }
Colin Cross30e076a2015-04-13 13:58:27 -0700210}
211
Colin Cross46c9b8b2017-06-22 16:51:17 -0700212func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
213 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700214
Jiyong Park92315372021-04-02 08:45:46 +0900215 if String(a.appProperties.Stl) == "c++_shared" && !a.SdkVersion(ctx).Specified() {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700216 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
217 }
218
Jiyong Parkf1691d22021-03-29 20:11:58 +0900219 sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
Paul Duffin250e6192019-06-07 10:44:37 +0100220 if sdkDep.hasFrameworkLibs() {
221 a.aapt.deps(ctx, sdkDep)
Colin Cross30e076a2015-04-13 13:58:27 -0700222 }
Colin Crossa4f08812018-10-02 22:03:40 -0700223
Jiyong Park92315372021-04-02 08:45:46 +0900224 usesSDK := a.SdkVersion(ctx).Specified() && a.SdkVersion(ctx).Kind != android.SdkCorePlatform
Colin Cross3c007702020-05-08 11:20:24 -0700225
226 if usesSDK && Bool(a.appProperties.Jni_uses_sdk_apis) {
227 ctx.PropertyErrorf("jni_uses_sdk_apis",
228 "can only be set for modules that do not set sdk_version")
229 } else if !usesSDK && Bool(a.appProperties.Jni_uses_platform_apis) {
230 ctx.PropertyErrorf("jni_uses_platform_apis",
231 "can only be set for modules that set sdk_version")
232 }
233
Colin Crossa4f08812018-10-02 22:03:40 -0700234 for _, jniTarget := range ctx.MultiTargets() {
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700235 variation := append(jniTarget.Variations(),
236 blueprint.Variation{Mutator: "link", Variation: "shared"})
Colin Crossc511bc52020-04-07 16:50:32 +0000237
238 // If the app builds against an Android SDK use the SDK variant of JNI dependencies
239 // unless jni_uses_platform_apis is set.
Colin Crossc2d24052020-05-13 11:05:02 -0700240 // Don't require the SDK variant for apps that are shipped on vendor, etc., as they already
241 // have stable APIs through the VNDK.
242 if (usesSDK && !a.RequiresStableAPIs(ctx) &&
243 !Bool(a.appProperties.Jni_uses_platform_apis)) ||
Colin Cross7204cf02020-05-06 17:51:39 -0700244 Bool(a.appProperties.Jni_uses_sdk_apis) {
Colin Crossc511bc52020-04-07 16:50:32 +0000245 variation = append(variation, blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
246 }
Colin Crossde78d132020-10-09 18:59:49 -0700247 ctx.AddFarVariationDependencies(variation, jniLibTag, a.appProperties.Jni_libs...)
Colin Crossa4f08812018-10-02 22:03:40 -0700248 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700249
Paul Duffin250e6192019-06-07 10:44:37 +0100250 a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700251}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700252
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700253func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800254 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700255 if cert != "" {
256 ctx.AddDependency(ctx.Module(), certificateTag, cert)
257 }
258
259 for _, cert := range a.appProperties.Additional_certificates {
260 cert = android.SrcIsModule(cert)
261 if cert != "" {
262 ctx.AddDependency(ctx.Module(), certificateTag, cert)
263 } else {
264 ctx.PropertyErrorf("additional_certificates",
265 `must be names of android_app_certificate modules in the form ":module"`)
266 }
267 }
Colin Cross30e076a2015-04-13 13:58:27 -0700268}
269
Jeongik Cha538c0d02019-07-11 15:54:27 +0900270func (a *AndroidTestHelperApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
271 a.generateAndroidBuildActions(ctx)
272}
273
Colin Cross46c9b8b2017-06-22 16:51:17 -0700274func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100275 a.checkAppSdkVersions(ctx)
Colin Crossae5caf52018-05-22 11:11:52 -0700276 a.generateAndroidBuildActions(ctx)
277}
278
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100279func (a *AndroidApp) checkAppSdkVersions(ctx android.ModuleContext) {
Artur Satayev849f8442020-04-28 14:57:42 +0100280 if a.Updatable() {
Jiyong Park92315372021-04-02 08:45:46 +0900281 if !a.SdkVersion(ctx).Stable() {
282 ctx.PropertyErrorf("sdk_version", "Updatable apps must use stable SDKs, found %v", a.SdkVersion(ctx))
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100283 }
Artur Satayevf40fc852020-04-16 13:43:02 +0100284 if String(a.deviceProperties.Min_sdk_version) == "" {
285 ctx.PropertyErrorf("updatable", "updatable apps must set min_sdk_version.")
286 }
Jooyung Han749dc692020-04-15 11:03:39 +0900287
Jiyong Park92315372021-04-02 08:45:46 +0900288 if minSdkVersion, err := a.MinSdkVersion(ctx).EffectiveVersion(ctx); err == nil {
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900289 a.checkJniLibsSdkVersion(ctx, minSdkVersion)
satayevb3fd4112021-12-02 13:59:35 +0000290 android.CheckMinSdkVersion(ctx, minSdkVersion, a.WalkPayloadDeps)
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900291 } else {
292 ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
293 }
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100294 }
295
296 a.checkPlatformAPI(ctx)
297 a.checkSdkVersions(ctx)
298}
299
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900300// If an updatable APK sets min_sdk_version, min_sdk_vesion of JNI libs should match with it.
301// This check is enforced for "updatable" APKs (including APK-in-APEX).
302// b/155209650: until min_sdk_version is properly supported, use sdk_version instead.
303// because, sdk_version is overridden by min_sdk_version (if set as smaller)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -0800304// and sdkLinkType is checked with dependencies so we can be sure that the whole dependency tree
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900305// will meet the requirements.
Jiyong Park54105c42021-03-31 18:17:53 +0900306func (a *AndroidApp) checkJniLibsSdkVersion(ctx android.ModuleContext, minSdkVersion android.ApiLevel) {
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900307 // It's enough to check direct JNI deps' sdk_version because all transitive deps from JNI deps are checked in cc.checkLinkType()
308 ctx.VisitDirectDeps(func(m android.Module) {
309 if !IsJniDepTag(ctx.OtherModuleDependencyTag(m)) {
310 return
311 }
312 dep, _ := m.(*cc.Module)
Jooyung Han652d5b32020-05-20 17:12:13 +0900313 // The domain of cc.sdk_version is "current" and <number>
Jiyong Parkf1691d22021-03-29 20:11:58 +0900314 // We can rely on android.SdkSpec to convert it to <number> so that "current" is
315 // handled properly regardless of sdk finalization.
Jiyong Park92315372021-04-02 08:45:46 +0900316 jniSdkVersion, err := android.SdkSpecFrom(ctx, dep.SdkVersion()).EffectiveVersion(ctx)
Jiyong Park54105c42021-03-31 18:17:53 +0900317 if err != nil || minSdkVersion.LessThan(jniSdkVersion) {
Jooyung Hanbbc3fb72020-04-29 14:01:06 +0900318 ctx.OtherModuleErrorf(dep, "sdk_version(%v) is higher than min_sdk_version(%v) of the containing android_app(%v)",
319 dep.SdkVersion(), minSdkVersion, ctx.ModuleName())
320 return
321 }
322
323 })
324}
325
Sasha Smundak6ad77252019-05-01 13:16:22 -0700326// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800327// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700328func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Jiyong Park92315372021-04-02 08:45:46 +0900329 minSdkVersion, err := a.MinSdkVersion(ctx).EffectiveVersion(ctx)
Colin Crosse4246ab2019-02-05 21:55:21 -0800330 if err != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900331 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.MinSdkVersion(ctx), err)
Colin Crosse4246ab2019-02-05 21:55:21 -0800332 }
333
Colin Cross56a83212020-09-15 18:30:11 -0700334 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
Jiyong Park54105c42021-03-31 18:17:53 +0900335 return (minSdkVersion.FinalOrFutureInt() >= 23 && Bool(a.appProperties.Use_embedded_native_libs)) ||
Colin Cross56a83212020-09-15 18:30:11 -0700336 !apexInfo.IsForPlatform()
Colin Crosse4246ab2019-02-05 21:55:21 -0800337}
338
Colin Cross43f08db2018-11-12 10:13:39 -0800339// Returns whether this module should have the dex file stored uncompressed in the APK.
340func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800341 if Bool(a.appProperties.Use_embedded_dex) {
342 return true
343 }
344
Colin Cross53a87f52019-06-25 13:35:30 -0700345 // Uncompress dex in APKs of privileged apps (even for unbundled builds, they may
346 // be preinstalled as prebuilts).
Jiyong Parkf7487312019-10-17 12:54:30 +0900347 if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000348 return true
349 }
350
Colin Cross53a87f52019-06-25 13:35:30 -0700351 if ctx.Config().UnbundledBuild() {
352 return false
353 }
354
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700355 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700356}
357
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700358func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
Colin Cross56a83212020-09-15 18:30:11 -0700359 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700360 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
Colin Cross56a83212020-09-15 18:30:11 -0700361 !apexInfo.IsForPlatform() || a.appProperties.AlwaysPackageNativeLibs
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700362}
363
Liz Kammer9f9fd022020-06-18 19:44:06 +0000364func generateAaptRenamePackageFlags(packageName string, renameResourcesPackage bool) []string {
365 aaptFlags := []string{"--rename-manifest-package " + packageName}
366 if renameResourcesPackage {
367 // Required to rename the package name in the resources table.
368 aaptFlags = append(aaptFlags, "--rename-resources-package "+packageName)
369 }
370 return aaptFlags
371}
372
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900373func (a *AndroidApp) OverriddenManifestPackageName() string {
374 return a.overriddenManifestPackageName
375}
376
Liz Kammer9f9fd022020-06-18 19:44:06 +0000377func (a *AndroidApp) renameResourcesPackage() bool {
378 return proptools.BoolDefault(a.overridableAppProperties.Rename_resources_package, true)
379}
380
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800381func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
Lorenzo Colittifa9b3f32021-03-30 10:38:26 +0900382 usePlatformAPI := proptools.Bool(a.Module.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900383 if ctx.Module().(android.SdkContext).SdkVersion(ctx).Kind == android.SdkModule {
Lorenzo Colittifa9b3f32021-03-30 10:38:26 +0900384 usePlatformAPI = true
385 }
386 a.aapt.usesNonSdkApis = usePlatformAPI
David Brazdild25060a2019-02-18 18:24:16 +0000387
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700388 // Ask manifest_fixer to add or update the application element indicating this app has no code.
389 a.aapt.hasNoCode = !a.hasCode(ctx)
390
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800391 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800392
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800393 // Add TARGET_AAPT_CHARACTERISTICS values to AAPT link flags if they exist and --product flags were not provided.
Jaewoong Jung3aff5782020-02-11 07:54:35 -0800394 hasProduct := android.PrefixInList(a.aaptProperties.Aaptflags, "--product")
Colin Crosse78dcd32018-04-19 15:25:19 -0700395 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800396 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700397 }
398
Dan Willemsen72be5902018-10-24 20:24:57 -0700399 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
400 // Product AAPT config
401 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800402 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700403 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700404
Dan Willemsen72be5902018-10-24 20:24:57 -0700405 // Product AAPT preferred config
406 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800407 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700408 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700409 }
410
Jiyong Park7f67f482019-01-05 12:57:48 +0900411 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700412 if overridden || a.overridableAppProperties.Package_name != nil {
413 // The product override variable has a priority over the package_name property.
414 if !overridden {
415 manifestPackageName = *a.overridableAppProperties.Package_name
416 }
Liz Kammer9f9fd022020-06-18 19:44:06 +0000417 aaptLinkFlags = append(aaptLinkFlags, generateAaptRenamePackageFlags(manifestPackageName, a.renameResourcesPackage())...)
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900418 a.overriddenManifestPackageName = manifestPackageName
Jiyong Park7f67f482019-01-05 12:57:48 +0900419 }
420
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800421 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
422
Colin Crosse560c4a2019-03-19 16:03:11 -0700423 a.aapt.splitNames = a.appProperties.Package_splits
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800424 a.aapt.LoggingParent = String(a.overridableAppProperties.Logging_parent)
Paul Duffin06530572022-02-03 17:54:15 +0000425 a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts,
426 a.usesLibraryProperties.Exclude_uses_libs, aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700427
Colin Cross46c9b8b2017-06-22 16:51:17 -0700428 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700429 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800430}
Colin Cross30e076a2015-04-13 13:58:27 -0700431
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800432func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700433 var staticLibProguardFlagFiles android.Paths
434 ctx.VisitDirectDeps(func(m android.Module) {
435 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
436 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
437 }
438 })
439
440 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
441
442 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
443 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800444}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800445
Colin Cross403cc152020-07-06 14:15:24 -0700446func (a *AndroidApp) installPath(ctx android.ModuleContext) android.InstallPath {
Colin Cross43f08db2018-11-12 10:13:39 -0800447 var installDir string
448 if ctx.ModuleName() == "framework-res" {
449 // framework-res.apk is installed as system/framework/framework-res.apk
450 installDir = "framework"
Jiyong Parkf7487312019-10-17 12:54:30 +0900451 } else if a.Privileged() {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800452 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800453 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800454 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800455 }
Colin Cross403cc152020-07-06 14:15:24 -0700456
457 return android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
458}
459
Ulya Trafimovich18554242020-11-03 15:55:11 +0000460func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross403cc152020-07-06 14:15:24 -0700461 a.dexpreopter.installPath = a.installPath(ctx)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000462 a.dexpreopter.isApp = true
Liz Kammera7a64f32020-07-09 15:16:41 -0700463 if a.dexProperties.Uncompress_dex == nil {
David Srbeckye033cba2020-05-20 22:20:28 +0100464 // If the value was not force-set by the user, use reasonable default based on the module.
Liz Kammera7a64f32020-07-09 15:16:41 -0700465 a.dexProperties.Uncompress_dex = proptools.BoolPtr(a.shouldUncompressDex(ctx))
David Srbeckye033cba2020-05-20 22:20:28 +0100466 }
Liz Kammera7a64f32020-07-09 15:16:41 -0700467 a.dexpreopter.uncompressedDex = *a.dexProperties.Uncompress_dex
Colin Cross50ddcc42019-05-16 12:28:22 -0700468 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100469 a.dexpreopter.classLoaderContexts = a.classLoaderContexts
Colin Cross50ddcc42019-05-16 12:28:22 -0700470 a.dexpreopter.manifestFile = a.mergedManifestFile
Colin Crossfa9bfcd2021-11-10 16:42:38 -0800471 a.dexpreopter.preventInstall = a.appProperties.PreventInstall
Colin Cross50ddcc42019-05-16 12:28:22 -0700472
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800473 if ctx.ModuleName() != "framework-res" {
474 a.Module.compile(ctx, a.aaptSrcJar)
475 }
Colin Cross30e076a2015-04-13 13:58:27 -0700476
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100477 return a.dexJarFile.PathOrNil()
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800478}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800479
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800480func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700481 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700482 if len(jniLibs) > 0 {
Colin Cross403cc152020-07-06 14:15:24 -0700483 a.jniLibs = jniLibs
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700484 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700485 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Colin Crossc68db4b2021-11-11 18:59:15 -0800486 a.installPathForJNISymbols = a.installPath(ctx)
Sasha Smundak6ad77252019-05-01 13:16:22 -0700487 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700488 for _, jni := range jniLibs {
489 if jni.coverageFile.Valid() {
Jaewoong Jung46984ee2020-04-07 13:07:55 -0700490 // Only collect coverage for the first target arch if this is a multilib target.
491 // TODO(jungjw): Ideally, we want to collect both reports, but that would cause coverage
492 // data file path collisions since the current coverage file path format doesn't contain
493 // arch-related strings. This is fine for now though; the code coverage team doesn't use
494 // multi-arch targets such as test_suite_* for coverage collections yet.
495 //
496 // Work with the team to come up with a new format that handles multilib modules properly
497 // and change this.
498 if len(ctx.Config().Targets[android.Android]) == 1 ||
Jaewoong Jung642916f2020-10-09 17:25:15 -0700499 ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType == jni.target.Arch.ArchType {
Jaewoong Jung46984ee2020-04-07 13:07:55 -0700500 a.jniCoverageOutputs = append(a.jniCoverageOutputs, jni.coverageFile.Path())
501 }
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700502 }
503 }
Colin Cross403cc152020-07-06 14:15:24 -0700504 a.embeddedJniLibs = true
Colin Crossa4f08812018-10-02 22:03:40 -0700505 }
506 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800507 return jniJarFile
508}
Colin Crossa4f08812018-10-02 22:03:40 -0700509
Colin Cross403cc152020-07-06 14:15:24 -0700510func (a *AndroidApp) JNISymbolsInstalls(installPath string) android.RuleBuilderInstalls {
511 var jniSymbols android.RuleBuilderInstalls
512 for _, jniLib := range a.jniLibs {
513 if jniLib.unstrippedFile != nil {
514 jniSymbols = append(jniSymbols, android.RuleBuilderInstall{
515 From: jniLib.unstrippedFile,
516 To: filepath.Join(installPath, targetToJniDir(jniLib.target), jniLib.unstrippedFile.Base()),
517 })
518 }
519 }
520 return jniSymbols
521}
522
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700523// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
524// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
525func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
526 if android.SrcIsModule(certPropValue) == "" {
527 var mainCert Certificate
528 if certPropValue != "" {
529 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
530 mainCert = Certificate{
Colin Cross503c1d02020-01-28 14:00:53 -0800531 Pem: defaultDir.Join(ctx, certPropValue+".x509.pem"),
532 Key: defaultDir.Join(ctx, certPropValue+".pk8"),
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700533 }
534 } else {
535 pem, key := ctx.Config().DefaultAppCertificate(ctx)
Colin Cross503c1d02020-01-28 14:00:53 -0800536 mainCert = Certificate{
537 Pem: pem,
538 Key: key,
539 }
Colin Crossbd01e2a2018-10-04 15:21:03 -0700540 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700541 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700542 }
543
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700544 if !m.Platform() {
545 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900546 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
547 if strings.HasPrefix(certPath, systemCertPath) {
548 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
Colin Cross440e0d02020-06-11 11:32:11 -0700549 allowed := ctx.Config().EnforceSystemCertificateAllowList()
Jeongik Chac9464142019-01-07 12:07:27 +0900550
Colin Cross440e0d02020-06-11 11:32:11 -0700551 if enforceSystemCert && !inList(m.Name(), allowed) {
Jeongik Chac9464142019-01-07 12:07:27 +0900552 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
553 }
554 }
555 }
556
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700557 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800558}
559
Jooyung Han39ee1192020-03-23 20:21:11 +0900560func (a *AndroidApp) InstallApkName() string {
561 return a.installApkName
562}
563
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800564func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700565 var apkDeps android.Paths
566
Colin Cross56a83212020-09-15 18:30:11 -0700567 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
568 a.hideApexVariantFromMake = true
569 }
570
Jeongik Cha538c0d02019-07-11 15:54:27 +0900571 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
572 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
573
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800574 // Check if the install APK name needs to be overridden.
Jooyung Han29e2f6d2022-01-08 12:13:59 +0900575 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Stem())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800576
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700577 if ctx.ModuleName() == "framework-res" {
578 // framework-res.apk is installed as system/framework/framework-res.apk
Jaewoong Jung0949f312019-09-11 10:25:18 -0700579 a.installDir = android.PathForModuleInstall(ctx, "framework")
Jiyong Parkf7487312019-10-17 12:54:30 +0900580 } else if a.Privileged() {
Jaewoong Jung0949f312019-09-11 10:25:18 -0700581 a.installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
582 } else if ctx.InstallInTestcases() {
Jaewoong Jung326a9412019-11-21 10:41:00 -0800583 a.installDir = android.PathForModuleInstall(ctx, a.installApkName, ctx.DeviceConfig().DeviceArch())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700584 } else {
Jaewoong Jung0949f312019-09-11 10:25:18 -0700585 a.installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700586 }
Jaewoong Jung7dd4ae22019-09-27 17:13:15 -0700587 a.onDeviceDir = android.InstallPathToOnDevicePath(ctx, a.installDir)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700588
Jaewoong Jung98772792019-07-01 17:15:13 -0700589 if Bool(a.appProperties.Embed_notices) || ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
Bob Badour2c8888e2022-04-04 16:12:21 -0700590 noticeFile := android.PathForModuleOut(ctx, "NOTICE.html.gz")
591 android.BuildNoticeHtmlOutputFromLicenseMetadata(ctx, noticeFile)
592 noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
593 builder := android.NewRuleBuilder(pctx, ctx)
594 builder.Command().Text("cp").
595 Input(noticeFile).
596 Output(noticeAssetPath)
597 builder.Build("notice_dir", "Building notice dir")
598 a.aapt.noticeFile = android.OptionalPathForPath(noticeAssetPath)
Jaewoong Jung98772792019-07-01 17:15:13 -0700599 }
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700600
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +0100601 a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Ulya Trafimovich18554242020-11-03 15:55:11 +0000602
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800603 // Process all building blocks, from AAPT to certificates.
604 a.aaptBuildActions(ctx)
605
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100606 // The decision to enforce <uses-library> checks is made before adding implicit SDK libraries.
607 a.usesLibrary.freezeEnforceUsesLibraries()
608
609 // Add implicit SDK libraries to <uses-library> list.
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100610 requiredUsesLibs, optionalUsesLibs := a.classLoaderContexts.UsesLibs()
611 for _, usesLib := range requiredUsesLibs {
612 a.usesLibrary.addLib(usesLib, false)
613 }
614 for _, usesLib := range optionalUsesLibs {
615 a.usesLibrary.addLib(usesLib, true)
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +0100616 }
617
618 // Check that the <uses-library> list is coherent with the manifest.
Colin Cross50ddcc42019-05-16 12:28:22 -0700619 if a.usesLibrary.enforceUsesLibraries() {
620 manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
621 apkDeps = append(apkDeps, manifestCheckFile)
622 }
623
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800624 a.proguardBuildActions(ctx)
625
Colin Cross014489c2020-06-02 20:09:13 -0700626 a.linter.mergedManifest = a.aapt.mergedManifestFile
627 a.linter.manifest = a.aapt.manifestPath
628 a.linter.resources = a.aapt.resourceFiles
Colin Crossc0efd1d2020-07-03 11:56:24 -0700629 a.linter.buildModuleReportZip = ctx.Config().UnbundledBuildApps()
Colin Cross014489c2020-06-02 20:09:13 -0700630
Ulya Trafimovich18554242020-11-03 15:55:11 +0000631 dexJarFile := a.dexBuildActions(ctx)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800632
Colin Crossc2d24052020-05-13 11:05:02 -0700633 jniLibs, certificateDeps := collectAppDeps(ctx, a, a.shouldEmbedJnis(ctx), !Bool(a.appProperties.Jni_uses_platform_apis))
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800634 jniJarFile := a.jniBuildActions(jniLibs, ctx)
635
636 if ctx.Failed() {
637 return
638 }
639
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700640 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
Colin Cross412436f2022-04-07 17:40:07 -0700641
642 // This can be reached with an empty certificate list if AllowMissingDependencies is set
643 // and the certificate property for this module is a module reference to a missing module.
644 if len(certificates) > 0 {
645 a.certificate = certificates[0]
646 } else {
647 if !ctx.Config().AllowMissingDependencies() && len(ctx.GetMissingDependencies()) > 0 {
648 panic("Should only get here if AllowMissingDependencies set and there are missing dependencies")
649 }
650 // Set a certificate to avoid panics later when accessing it.
651 a.certificate = Certificate{
652 Key: android.PathForModuleOut(ctx, "missing.pk8"),
653 Pem: android.PathForModuleOut(ctx, "missing.pem"),
654 }
655 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800656
657 // Build a final signed app package.
Jaewoong Jung5a498812019-11-07 14:14:38 -0800658 packageFile := android.PathForModuleOut(ctx, a.installApkName+".apk")
Songchun Fan17d69e32020-03-24 20:32:24 -0700659 v4SigningRequested := Bool(a.Module.deviceProperties.V4_signature)
660 var v4SignatureFile android.WritablePath = nil
661 if v4SigningRequested {
662 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+".apk.idsig")
663 }
Liz Kammere2b27f42020-05-07 13:24:05 -0700664 var lineageFile android.Path
665 if lineage := String(a.overridableAppProperties.Lineage); lineage != "" {
666 lineageFile = android.PathForModuleSrc(ctx, lineage)
667 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700668 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800669 a.outputFile = packageFile
Songchun Fan17d69e32020-03-24 20:32:24 -0700670 if v4SigningRequested {
671 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
672 }
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800673
Colin Crosse560c4a2019-03-19 16:03:11 -0700674 for _, split := range a.aapt.splits {
675 // Sign the split APKs
Jaewoong Jung5a498812019-11-07 14:14:38 -0800676 packageFile := android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk")
Songchun Fan17d69e32020-03-24 20:32:24 -0700677 if v4SigningRequested {
678 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk.idsig")
679 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700680 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Crosse560c4a2019-03-19 16:03:11 -0700681 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
Songchun Fan17d69e32020-03-24 20:32:24 -0700682 if v4SigningRequested {
683 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
684 }
Colin Crosse560c4a2019-03-19 16:03:11 -0700685 }
686
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800687 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700688 bundleFile := android.PathForModuleOut(ctx, "base.zip")
689 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
690 a.bundleFile = bundleFile
691
Colin Cross56a83212020-09-15 18:30:11 -0700692 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
693
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800694 // Install the app package.
Colin Crossfa9bfcd2021-11-10 16:42:38 -0800695 if (Bool(a.Module.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() &&
696 !a.appProperties.PreventInstall {
697
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700698 var extraInstalledPaths android.Paths
Jiyong Park8ba50f92019-11-13 15:01:01 +0900699 for _, extra := range a.extraOutputFiles {
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700700 installed := ctx.InstallFile(a.installDir, extra.Base(), extra)
701 extraInstalledPaths = append(extraInstalledPaths, installed)
Jiyong Park8ba50f92019-11-13 15:01:01 +0900702 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700703 ctx.InstallFile(a.installDir, a.outputFile.Base(), a.outputFile, extraInstalledPaths...)
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800704 }
Artur Satayev1111b842020-04-27 19:05:28 +0100705
706 a.buildAppDependencyInfo(ctx)
Colin Cross30e076a2015-04-13 13:58:27 -0700707}
708
Colin Crossc2d24052020-05-13 11:05:02 -0700709type appDepsInterface interface {
Jiyong Park92315372021-04-02 08:45:46 +0900710 SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
711 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
Colin Crossc2d24052020-05-13 11:05:02 -0700712 RequiresStableAPIs(ctx android.BaseModuleContext) bool
713}
714
715func collectAppDeps(ctx android.ModuleContext, app appDepsInterface,
716 shouldCollectRecursiveNativeDeps bool,
Colin Cross094cde42020-02-15 10:38:00 -0800717 checkNativeSdkVersion bool) ([]jniLib, []Certificate) {
Colin Crossc2d24052020-05-13 11:05:02 -0700718
Colin Crossa4f08812018-10-02 22:03:40 -0700719 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900720 var certificates []Certificate
Peter Collingbournead84f972019-12-17 16:46:18 -0800721 seenModulePaths := make(map[string]bool)
Colin Crossa4f08812018-10-02 22:03:40 -0700722
Colin Crossc2d24052020-05-13 11:05:02 -0700723 if checkNativeSdkVersion {
Jiyong Park92315372021-04-02 08:45:46 +0900724 checkNativeSdkVersion = app.SdkVersion(ctx).Specified() &&
725 app.SdkVersion(ctx).Kind != android.SdkCorePlatform && !app.RequiresStableAPIs(ctx)
Colin Crossc2d24052020-05-13 11:05:02 -0700726 }
727
Peter Collingbournead84f972019-12-17 16:46:18 -0800728 ctx.WalkDeps(func(module android.Module, parent android.Module) bool {
Colin Crossa4f08812018-10-02 22:03:40 -0700729 otherName := ctx.OtherModuleName(module)
730 tag := ctx.OtherModuleDependencyTag(module)
731
Colin Crossf0913fb2020-07-29 12:59:39 -0700732 if IsJniDepTag(tag) || cc.IsSharedDepTag(tag) {
Colin Crossa4f08812018-10-02 22:03:40 -0700733 if dep, ok := module.(*cc.Module); ok {
Colin Cross95f1ca02020-10-29 20:47:22 -0700734 if dep.IsNdk(ctx.Config()) || dep.IsStubs() {
Peter Collingbournead84f972019-12-17 16:46:18 -0800735 return false
736 }
737
Colin Crossa4f08812018-10-02 22:03:40 -0700738 lib := dep.OutputFile()
739 if lib.Valid() {
Cole Faust64cb7c92021-09-14 17:32:49 -0700740 path := lib.Path()
741 if seenModulePaths[path.String()] {
742 return false
743 }
744 seenModulePaths[path.String()] = true
745
746 if checkNativeSdkVersion && dep.SdkVersion() == "" {
747 ctx.PropertyErrorf("jni_libs", "JNI dependency %q uses platform APIs, but this module does not",
748 otherName)
749 }
750
Colin Crossa4f08812018-10-02 22:03:40 -0700751 jniLibs = append(jniLibs, jniLib{
Colin Cross403cc152020-07-06 14:15:24 -0700752 name: ctx.OtherModuleName(module),
753 path: path,
754 target: module.Target(),
755 coverageFile: dep.CoverageOutputFile(),
756 unstrippedFile: dep.UnstrippedOutputFile(),
Colin Crossa4f08812018-10-02 22:03:40 -0700757 })
758 } else {
759 ctx.ModuleErrorf("dependency %q missing output file", otherName)
760 }
761 } else {
762 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700763 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800764
765 return shouldCollectRecursiveNativeDeps
766 }
767
768 if tag == certificateTag {
Colin Crossbd01e2a2018-10-04 15:21:03 -0700769 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900770 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700771 } else {
772 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
773 }
Colin Crossa4f08812018-10-02 22:03:40 -0700774 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800775
776 return false
Colin Crossa4f08812018-10-02 22:03:40 -0700777 })
778
Colin Crossbd01e2a2018-10-04 15:21:03 -0700779 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700780}
781
Jooyung Han749dc692020-04-15 11:03:39 +0900782func (a *AndroidApp) WalkPayloadDeps(ctx android.ModuleContext, do android.PayloadDepsCallback) {
Artur Satayev1111b842020-04-27 19:05:28 +0100783 ctx.WalkDeps(func(child, parent android.Module) bool {
784 isExternal := !a.DepIsInSameApex(ctx, child)
785 if am, ok := child.(android.ApexModule); ok {
Jooyung Han749dc692020-04-15 11:03:39 +0900786 if !do(ctx, parent, am, isExternal) {
787 return false
788 }
Artur Satayev1111b842020-04-27 19:05:28 +0100789 }
790 return !isExternal
791 })
792}
793
794func (a *AndroidApp) buildAppDependencyInfo(ctx android.ModuleContext) {
795 if ctx.Host() {
796 return
797 }
798
799 depsInfo := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900800 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev1111b842020-04-27 19:05:28 +0100801 depName := to.Name()
Artur Satayev533b98c2021-03-11 18:03:42 +0000802
803 // Skip dependencies that are only available to APEXes; they are developed with updatability
804 // in mind and don't need manual approval.
805 if to.(android.ApexModule).NotAvailableForPlatform() {
806 return true
807 }
808
Artur Satayev1111b842020-04-27 19:05:28 +0100809 if info, exist := depsInfo[depName]; exist {
810 info.From = append(info.From, from.Name())
811 info.IsExternal = info.IsExternal && externalDep
812 depsInfo[depName] = info
813 } else {
814 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900815 if m, ok := to.(interface {
816 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
817 }); ok {
818 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
819 toMinSdkVersion = v.ApiLevel.String()
Artur Satayev1111b842020-04-27 19:05:28 +0100820 }
Jiyong Park92315372021-04-02 08:45:46 +0900821 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
822 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
823 // string
824 if v := m.MinSdkVersion(); v != "" {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900825 toMinSdkVersion = v
826 }
Artur Satayev1111b842020-04-27 19:05:28 +0100827 }
828 depsInfo[depName] = android.ApexModuleDepInfo{
829 To: depName,
830 From: []string{from.Name()},
831 IsExternal: externalDep,
832 MinSdkVersion: toMinSdkVersion,
833 }
834 }
Jooyung Han749dc692020-04-15 11:03:39 +0900835 return true
Artur Satayev1111b842020-04-27 19:05:28 +0100836 })
837
Jiyong Park92315372021-04-02 08:45:46 +0900838 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).String(), depsInfo)
Artur Satayev1111b842020-04-27 19:05:28 +0100839}
840
Artur Satayev849f8442020-04-28 14:57:42 +0100841func (a *AndroidApp) Updatable() bool {
Colin Cross56a83212020-09-15 18:30:11 -0700842 return Bool(a.appProperties.Updatable)
Artur Satayev849f8442020-04-28 14:57:42 +0100843}
844
Colin Cross0ea8ba82019-06-06 14:33:29 -0700845func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800846 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
847 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000848 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800849 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800850 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800851}
852
Jiyong Park0f80c182020-01-31 02:49:53 +0900853func (a *AndroidApp) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
854 if IsJniDepTag(ctx.OtherModuleDependencyTag(dep)) {
855 return true
856 }
857 return a.Library.DepIsInSameApex(ctx, dep)
858}
859
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900860// For OutputFileProducer interface
861func (a *AndroidApp) OutputFiles(tag string) (android.Paths, error) {
862 switch tag {
863 case ".aapt.srcjar":
864 return []android.Path{a.aaptSrcJar}, nil
Anton Hansson092aca42020-08-13 19:37:22 +0100865 case ".export-package.apk":
866 return []android.Path{a.exportPackage}, nil
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900867 }
868 return a.Library.OutputFiles(tag)
869}
870
Jiyong Parkf7487312019-10-17 12:54:30 +0900871func (a *AndroidApp) Privileged() bool {
872 return Bool(a.appProperties.Privileged)
873}
874
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700875func (a *AndroidApp) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
Colin Cross1a6acd42020-06-16 17:51:46 -0700876 return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700877}
878
Ivan Lozanod7586b62021-04-01 09:49:36 -0400879func (a *AndroidApp) SetPreventInstall() {
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700880 a.appProperties.PreventInstall = true
881}
882
883func (a *AndroidApp) HideFromMake() {
884 a.appProperties.HideFromMake = true
885}
886
887func (a *AndroidApp) MarkAsCoverageVariant(coverage bool) {
888 a.appProperties.IsCoverageVariant = coverage
889}
890
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400891func (a *AndroidApp) EnableCoverageIfNeeded() {}
892
Jaewoong Jung87a33e72020-03-26 14:01:48 -0700893var _ cc.Coverage = (*AndroidApp)(nil)
894
Colin Cross1b16b0e2019-02-12 14:41:32 -0800895// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700896func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700897 module := &AndroidApp{}
898
Liz Kammera7a64f32020-07-09 15:16:41 -0700899 module.Module.dexProperties.Optimize.EnabledByDefault = true
900 module.Module.dexProperties.Optimize.Shrink = proptools.BoolPtr(true)
Colin Cross66dbc0b2017-12-28 12:23:20 -0800901
Colin Crossae5caf52018-05-22 11:11:52 -0700902 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700903 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700904
Colin Crossce6734e2020-06-15 16:09:53 -0700905 module.addHostAndDeviceProperties()
Colin Cross36242852017-06-23 15:06:31 -0700906 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700907 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800908 &module.appProperties,
Ulya Trafimovich21a73752020-09-01 17:33:48 +0100909 &module.overridableAppProperties)
Colin Cross36242852017-06-23 15:06:31 -0700910
Ulya Trafimovich22890c42021-01-05 12:04:17 +0000911 module.usesLibrary.enforce = true
912
Colin Crossa4f08812018-10-02 22:03:40 -0700913 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
914 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800915 android.InitOverridableModule(module, &module.appProperties.Overrides)
Jiyong Park52cd06f2019-11-11 10:14:32 +0900916 android.InitApexModule(module)
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400917 android.InitBazelModule(module)
Colin Crossa4f08812018-10-02 22:03:40 -0700918
Colin Cross36242852017-06-23 15:06:31 -0700919 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700920}
Colin Crossae5caf52018-05-22 11:11:52 -0700921
922type appTestProperties struct {
Liz Kammer6b0c5522020-04-28 16:10:55 -0700923 // The name of the android_app module that the tests will run against.
Colin Crossae5caf52018-05-22 11:11:52 -0700924 Instrumentation_for *string
Jaewoong Jung26dedd32019-06-06 08:45:58 -0700925
926 // if specified, the instrumentation target package name in the manifest is overwritten by it.
927 Instrumentation_target_package *string
Colin Crossae5caf52018-05-22 11:11:52 -0700928}
929
930type AndroidTest struct {
931 AndroidApp
932
933 appTestProperties appTestProperties
934
935 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700936
Dan Shi95d19422020-08-15 12:24:26 -0700937 testConfig android.Path
938 extraTestConfigs android.Paths
939 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -0700940}
941
Jaewoong Jung0949f312019-09-11 10:25:18 -0700942func (a *AndroidTest) InstallInTestcases() bool {
943 return true
944}
945
Colin Crossae5caf52018-05-22 11:11:52 -0700946func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
easoncylee5bcff5d2020-04-30 14:57:06 +0800947 var configs []tradefed.Config
Jaewoong Jung26dedd32019-06-06 08:45:58 -0700948 if a.appTestProperties.Instrumentation_target_package != nil {
949 a.additionalAaptFlags = append(a.additionalAaptFlags,
950 "--rename-instrumentation-target-package "+*a.appTestProperties.Instrumentation_target_package)
951 } else if a.appTestProperties.Instrumentation_for != nil {
952 // Check if the instrumentation target package is overridden.
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800953 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
954 if overridden {
955 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
956 }
957 }
Colin Crossae5caf52018-05-22 11:11:52 -0700958 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -0700959
easoncylee5bcff5d2020-04-30 14:57:06 +0800960 for _, module := range a.testProperties.Test_mainline_modules {
961 configs = append(configs, tradefed.Option{Name: "config-descriptor:metadata", Key: "mainline-param", Value: module})
962 }
963
Jaewoong Jung39982342020-01-14 10:27:18 -0800964 testConfig := tradefed.AutoGenInstrumentationTestConfig(ctx, a.testProperties.Test_config,
easoncylee5bcff5d2020-04-30 14:57:06 +0800965 a.testProperties.Test_config_template, a.manifestPath, a.testProperties.Test_suites, a.testProperties.Auto_gen_config, configs)
Jaewoong Jung39982342020-01-14 10:27:18 -0800966 a.testConfig = a.FixTestConfig(ctx, testConfig)
Dan Shi95d19422020-08-15 12:24:26 -0700967 a.extraTestConfigs = android.PathsForModuleSrc(ctx, a.testProperties.Test_options.Extra_test_configs)
Colin Cross8a497952019-03-05 22:25:09 -0800968 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700969}
970
Jaewoong Jung39982342020-01-14 10:27:18 -0800971func (a *AndroidTest) FixTestConfig(ctx android.ModuleContext, testConfig android.Path) android.Path {
972 if testConfig == nil {
973 return nil
974 }
975
976 fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", "AndroidTest.xml")
Colin Crossf1a035e2020-11-16 17:32:30 -0800977 rule := android.NewRuleBuilder(pctx, ctx)
978 command := rule.Command().BuiltTool("test_config_fixer").Input(testConfig).Output(fixedConfig)
Jaewoong Jung39982342020-01-14 10:27:18 -0800979 fixNeeded := false
980
Jooyung Han29e2f6d2022-01-08 12:13:59 +0900981 // Auto-generated test config uses `ModuleName` as the APK name. So fix it if it is not the case.
Jaewoong Jung39982342020-01-14 10:27:18 -0800982 if ctx.ModuleName() != a.installApkName {
983 fixNeeded = true
984 command.FlagWithArg("--test-file-name ", a.installApkName+".apk")
985 }
986
987 if a.overridableAppProperties.Package_name != nil {
988 fixNeeded = true
989 command.FlagWithInput("--manifest ", a.manifestPath).
990 FlagWithArg("--package-name ", *a.overridableAppProperties.Package_name)
991 }
992
993 if fixNeeded {
Colin Crossf1a035e2020-11-16 17:32:30 -0800994 rule.Build("fix_test_config", "fix test config")
Jaewoong Jung39982342020-01-14 10:27:18 -0800995 return fixedConfig
996 }
997 return testConfig
998}
999
Colin Cross303e21f2018-08-07 16:49:25 -07001000func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -07001001 a.AndroidApp.DepsMutator(ctx)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001002}
1003
1004func (a *AndroidTest) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
1005 a.AndroidApp.OverridablePropertiesDepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -07001006 if a.appTestProperties.Instrumentation_for != nil {
1007 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
1008 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
1009 // use instrumentationForTag instead of libTag.
1010 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
1011 }
Colin Crossae5caf52018-05-22 11:11:52 -07001012}
1013
Colin Cross1b16b0e2019-02-12 14:41:32 -08001014// android_test compiles test sources and Android resources into an Android application package `.apk` file and
1015// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -07001016func AndroidTestFactory() android.Module {
1017 module := &AndroidTest{}
1018
Liz Kammera7a64f32020-07-09 15:16:41 -07001019 module.Module.dexProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -07001020
1021 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001022 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001023 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001024 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001025 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001026 module.Module.linter.test = true
Colin Crossae5caf52018-05-22 11:11:52 -07001027
Colin Crossce6734e2020-06-15 16:09:53 -07001028 module.addHostAndDeviceProperties()
Colin Crossae5caf52018-05-22 11:11:52 -07001029 module.AddProperties(
Colin Crossae5caf52018-05-22 11:11:52 -07001030 &module.aaptProperties,
1031 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001032 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001033 &module.overridableAppProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001034 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -07001035
Colin Crossa4f08812018-10-02 22:03:40 -07001036 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1037 android.InitDefaultableModule(module)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001038 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossae5caf52018-05-22 11:11:52 -07001039 return module
1040}
Colin Crossbd01e2a2018-10-04 15:21:03 -07001041
Colin Cross252fc6f2018-10-04 15:22:03 -07001042type appTestHelperAppProperties struct {
1043 // list of compatibility suites (for example "cts", "vts") that the module should be
1044 // installed into.
1045 Test_suites []string `android:"arch_variant"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001046
1047 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1048 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1049 // explicitly.
1050 Auto_gen_config *bool
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001051
1052 // Install the test into a folder named for the module in all test suites.
1053 Per_testcase_directory *bool
Colin Cross252fc6f2018-10-04 15:22:03 -07001054}
1055
1056type AndroidTestHelperApp struct {
1057 AndroidApp
1058
1059 appTestHelperAppProperties appTestHelperAppProperties
1060}
1061
Jaewoong Jung326a9412019-11-21 10:41:00 -08001062func (a *AndroidTestHelperApp) InstallInTestcases() bool {
1063 return true
1064}
1065
Colin Cross1b16b0e2019-02-12 14:41:32 -08001066// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
1067// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
1068// test.
Colin Cross252fc6f2018-10-04 15:22:03 -07001069func AndroidTestHelperAppFactory() android.Module {
1070 module := &AndroidTestHelperApp{}
1071
Liz Kammera7a64f32020-07-09 15:16:41 -07001072 module.Module.dexProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001073
1074 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001075 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001076 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001077 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001078 module.Module.linter.test = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001079
Colin Crossce6734e2020-06-15 16:09:53 -07001080 module.addHostAndDeviceProperties()
Colin Cross252fc6f2018-10-04 15:22:03 -07001081 module.AddProperties(
Colin Cross252fc6f2018-10-04 15:22:03 -07001082 &module.aaptProperties,
1083 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001084 &module.appTestHelperAppProperties,
Ulya Trafimovich21a73752020-09-01 17:33:48 +01001085 &module.overridableAppProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -07001086
1087 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1088 android.InitDefaultableModule(module)
Anton Hansson3d2b6b42020-01-10 15:06:01 +00001089 android.InitApexModule(module)
Colin Cross252fc6f2018-10-04 15:22:03 -07001090 return module
1091}
1092
Colin Crossbd01e2a2018-10-04 15:21:03 -07001093type AndroidAppCertificate struct {
1094 android.ModuleBase
Rupert Shuttleworth6e4950a2021-07-27 01:34:59 -04001095 android.BazelModuleBase
1096
Colin Crossbd01e2a2018-10-04 15:21:03 -07001097 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001098 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -07001099}
1100
1101type AndroidAppCertificateProperties struct {
1102 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
1103 Certificate *string
1104}
1105
Colin Cross1b16b0e2019-02-12 14:41:32 -08001106// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
1107// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -07001108func AndroidAppCertificateFactory() android.Module {
1109 module := &AndroidAppCertificate{}
1110 module.AddProperties(&module.properties)
1111 android.InitAndroidModule(module)
Rupert Shuttleworth6e4950a2021-07-27 01:34:59 -04001112 android.InitBazelModule(module)
Colin Crossbd01e2a2018-10-04 15:21:03 -07001113 return module
1114}
1115
Colin Crossbd01e2a2018-10-04 15:21:03 -07001116func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1117 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001118 c.Certificate = Certificate{
Colin Cross503c1d02020-01-28 14:00:53 -08001119 Pem: android.PathForModuleSrc(ctx, cert+".x509.pem"),
1120 Key: android.PathForModuleSrc(ctx, cert+".pk8"),
Colin Crossbd01e2a2018-10-04 15:21:03 -07001121 }
1122}
Jaewoong Jung525443a2019-02-28 15:35:54 -08001123
1124type OverrideAndroidApp struct {
1125 android.ModuleBase
1126 android.OverrideModuleBase
1127}
1128
Sasha Smundak613cbb12020-06-05 10:27:23 -07001129func (i *OverrideAndroidApp) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung525443a2019-02-28 15:35:54 -08001130 // All the overrides happen in the base module.
1131 // TODO(jungjw): Check the base module type.
1132}
1133
1134// override_android_app is used to create an android_app module based on another android_app by overriding
1135// some of its properties.
1136func OverrideAndroidAppModuleFactory() android.Module {
1137 m := &OverrideAndroidApp{}
Jooyung Han01d80d82022-01-08 12:16:32 +09001138 m.AddProperties(
1139 &OverridableDeviceProperties{},
1140 &overridableAppProperties{},
1141 )
Jaewoong Jung525443a2019-02-28 15:35:54 -08001142
Jaewoong Jungb639a6a2019-05-10 15:16:29 -07001143 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -08001144 android.InitOverrideModule(m)
1145 return m
1146}
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001147
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001148type OverrideAndroidTest struct {
1149 android.ModuleBase
1150 android.OverrideModuleBase
1151}
1152
Sasha Smundak613cbb12020-06-05 10:27:23 -07001153func (i *OverrideAndroidTest) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001154 // All the overrides happen in the base module.
1155 // TODO(jungjw): Check the base module type.
1156}
1157
1158// override_android_test is used to create an android_app module based on another android_test by overriding
1159// some of its properties.
1160func OverrideAndroidTestModuleFactory() android.Module {
1161 m := &OverrideAndroidTest{}
1162 m.AddProperties(&overridableAppProperties{})
1163 m.AddProperties(&appTestProperties{})
1164
1165 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
1166 android.InitOverrideModule(m)
1167 return m
1168}
1169
Colin Cross50ddcc42019-05-16 12:28:22 -07001170type UsesLibraryProperties struct {
1171 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
1172 Uses_libs []string
1173
1174 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
1175 // required=false.
1176 Optional_uses_libs []string
1177
1178 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
1179 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
1180 Enforce_uses_libs *bool
Ulya Trafimovich21a73752020-09-01 17:33:48 +01001181
Ulya Trafimovich54027b52020-09-09 14:08:23 +01001182 // Optional name of the <uses-library> provided by this module. This is needed for non-SDK
1183 // libraries, because SDK ones are automatically picked up by Soong. The <uses-library> name
1184 // normally is the same as the module name, but there are exceptions.
1185 Provides_uses_lib *string
Paul Duffin06530572022-02-03 17:54:15 +00001186
1187 // A list of shared library names to exclude from the classpath of the APK. Adding a library here
1188 // will prevent it from being used when precompiling the APK and prevent it from being implicitly
1189 // added to the APK's manifest's <uses-library> elements.
1190 //
1191 // Care must be taken when using this as it could result in runtime errors if the APK actually
1192 // uses classes provided by the library and which are not provided in any other way.
1193 //
1194 // This is primarily intended for use by various CTS tests that check the runtime handling of the
1195 // android.test.base shared library (and related libraries) but which depend on some common
1196 // libraries that depend on the android.test.base library. Without this those tests will end up
1197 // with a <uses-library android:name="android.test.base"/> in their manifest which would either
1198 // render the tests worthless (as they would be testing the wrong behavior), or would break the
1199 // test altogether by providing access to classes that the tests were not expecting. Those tests
1200 // provide the android.test.base statically and use jarjar to rename them so they do not collide
1201 // with the classes provided by the android.test.base library.
1202 Exclude_uses_libs []string
Colin Cross50ddcc42019-05-16 12:28:22 -07001203}
1204
1205// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
1206// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
1207// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
1208// with knowledge of their shared libraries.
1209type usesLibrary struct {
1210 usesLibraryProperties UsesLibraryProperties
Ulya Trafimovich22890c42021-01-05 12:04:17 +00001211
1212 // Whether to enforce verify_uses_library check.
1213 enforce bool
Colin Cross50ddcc42019-05-16 12:28:22 -07001214}
1215
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +01001216func (u *usesLibrary) addLib(lib string, optional bool) {
1217 if !android.InList(lib, u.usesLibraryProperties.Uses_libs) && !android.InList(lib, u.usesLibraryProperties.Optional_uses_libs) {
1218 if optional {
1219 u.usesLibraryProperties.Optional_uses_libs = append(u.usesLibraryProperties.Optional_uses_libs, lib)
1220 } else {
1221 u.usesLibraryProperties.Uses_libs = append(u.usesLibraryProperties.Uses_libs, lib)
1222 }
1223 }
1224}
1225
Paul Duffin250e6192019-06-07 10:44:37 +01001226func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Jeongik Cha4b073cd2021-06-08 11:35:00 +09001227 if !ctx.Config().UnbundledBuild() || ctx.Config().UnbundledBuildImage() {
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +01001228 reqTag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false, false)
1229 ctx.AddVariationDependencies(nil, reqTag, u.usesLibraryProperties.Uses_libs...)
1230
1231 optTag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true, false)
1232 ctx.AddVariationDependencies(nil, optTag, u.presentOptionalUsesLibs(ctx)...)
1233
Paul Duffin250e6192019-06-07 10:44:37 +01001234 // Only add these extra dependencies if the module depends on framework libs. This avoids
1235 // creating a cyclic dependency:
1236 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1237 if hasFrameworkLibs {
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +01001238 // Add implicit <uses-library> dependencies on compatibility libraries. Some of them are
1239 // optional, and some required --- this depends on the most common usage of the library
1240 // and may be wrong for some apps (they need explicit `uses_libs`/`optional_uses_libs`).
1241
1242 compat28OptTag := makeUsesLibraryDependencyTag(28, true, true)
1243 ctx.AddVariationDependencies(nil, compat28OptTag, dexpreopt.OptionalCompatUsesLibs28...)
1244
1245 compat29ReqTag := makeUsesLibraryDependencyTag(29, false, true)
1246 ctx.AddVariationDependencies(nil, compat29ReqTag, dexpreopt.CompatUsesLibs29...)
1247
1248 compat30OptTag := makeUsesLibraryDependencyTag(30, true, true)
1249 ctx.AddVariationDependencies(nil, compat30OptTag, dexpreopt.OptionalCompatUsesLibs30...)
Colin Cross3245b2c2019-06-07 13:18:09 -07001250 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001251 }
1252}
1253
1254// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1255// build.
1256func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1257 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1258 return optionalUsesLibs
1259}
1260
Ulya Trafimovicheea486a2021-02-26 11:38:21 +00001261// Helper function to replace string in a list.
1262func replaceInList(list []string, oldstr, newstr string) {
1263 for i, str := range list {
1264 if str == oldstr {
1265 list[i] = newstr
1266 }
1267 }
1268}
1269
Ulya Trafimovich24446712021-07-15 14:59:34 +01001270// Returns a map of module names of shared library dependencies to the paths to their dex jars on
1271// host and on device.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +00001272func (u *usesLibrary) classLoaderContextForUsesLibDeps(ctx android.ModuleContext) dexpreopt.ClassLoaderContextMap {
1273 clcMap := make(dexpreopt.ClassLoaderContextMap)
Ulya Trafimovich24446712021-07-15 14:59:34 +01001274
1275 // Skip when UnbundledBuild() is true, but UnbundledBuildImage() is false. With
1276 // UnbundledBuildImage() it is necessary to generate dexpreopt.config for post-dexpreopting.
1277 if ctx.Config().UnbundledBuild() && !ctx.Config().UnbundledBuildImage() {
1278 return clcMap
Colin Cross50ddcc42019-05-16 12:28:22 -07001279 }
1280
Ulya Trafimovich24446712021-07-15 14:59:34 +01001281 ctx.VisitDirectDeps(func(m android.Module) {
1282 tag, isUsesLibTag := ctx.OtherModuleDependencyTag(m).(usesLibraryDependencyTag)
1283 if !isUsesLibTag {
1284 return
1285 }
1286
Ulya Trafimoviche14f80b2021-07-15 15:05:48 +01001287 dep := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(m))
Ulya Trafimovich24446712021-07-15 14:59:34 +01001288
Ulya Trafimovich840efb62021-07-15 14:34:40 +01001289 // Skip stub libraries. A dependency on the implementation library has been added earlier,
1290 // so it will be added to CLC, but the stub shouldn't be. Stub libraries can be distingushed
1291 // from implementation libraries by their name, which is different as it has a suffix.
1292 if comp, ok := m.(SdkLibraryComponentDependency); ok {
1293 if impl := comp.OptionalSdkLibraryImplementation(); impl != nil && *impl != dep {
1294 return
1295 }
1296 }
1297
Ulya Trafimovich24446712021-07-15 14:59:34 +01001298 if lib, ok := m.(UsesLibraryDependency); ok {
Ulya Trafimoviche14f80b2021-07-15 15:05:48 +01001299 libName := dep
Ulya Trafimovich24446712021-07-15 14:59:34 +01001300 if ulib, ok := m.(ProvidesUsesLib); ok && ulib.ProvidesUsesLib() != nil {
Ulya Trafimoviche14f80b2021-07-15 15:05:48 +01001301 libName = *ulib.ProvidesUsesLib()
Ulya Trafimovich24446712021-07-15 14:59:34 +01001302 // Replace module name with library name in `uses_libs`/`optional_uses_libs` in
1303 // order to pass verify_uses_libraries check (which compares these properties
1304 // against library names written in the manifest).
1305 replaceInList(u.usesLibraryProperties.Uses_libs, dep, libName)
1306 replaceInList(u.usesLibraryProperties.Optional_uses_libs, dep, libName)
1307 }
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +01001308 clcMap.AddContext(ctx, tag.sdkVersion, libName, tag.optional, tag.implicit,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001309 lib.DexJarBuildPath().PathOrNil(), lib.DexJarInstallPath(),
1310 lib.ClassLoaderContexts())
Ulya Trafimovich24446712021-07-15 14:59:34 +01001311 } else if ctx.Config().AllowMissingDependencies() {
1312 ctx.AddMissingDependencies([]string{dep})
1313 } else {
1314 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library", dep)
1315 }
1316 })
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +00001317 return clcMap
Colin Cross50ddcc42019-05-16 12:28:22 -07001318}
1319
1320// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1321// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1322// unconditionally in the future.
1323func (u *usesLibrary) enforceUsesLibraries() bool {
1324 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1325 len(u.usesLibraryProperties.Optional_uses_libs) > 0
Ulya Trafimovich22890c42021-01-05 12:04:17 +00001326 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, u.enforce || defaultEnforceUsesLibs)
Colin Cross50ddcc42019-05-16 12:28:22 -07001327}
1328
Ulya Trafimovichfc24ad32020-08-19 16:32:54 +01001329// Freeze the value of `enforce_uses_libs` based on the current values of `uses_libs` and `optional_uses_libs`.
1330func (u *usesLibrary) freezeEnforceUsesLibraries() {
1331 enforce := u.enforceUsesLibraries()
1332 u.usesLibraryProperties.Enforce_uses_libs = &enforce
1333}
1334
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001335// verifyUsesLibraries checks the <uses-library> tags in the manifest against the ones specified
1336// in the `uses_libs`/`optional_uses_libs` properties. The input can be either an XML manifest, or
1337// an APK with the manifest embedded in it (manifest_check will know which one it is by the file
1338// extension: APKs are supposed to end with '.apk').
1339func (u *usesLibrary) verifyUsesLibraries(ctx android.ModuleContext, inputFile android.Path,
Ulya Trafimovicha76d6602021-03-16 15:34:50 +00001340 outputFile android.WritablePath) android.Path {
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001341
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +00001342 statusFile := dexpreopt.UsesLibrariesStatusFile(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -07001343
Ulya Trafimovich6e55ef12021-03-04 12:37:50 +00001344 // Disable verify_uses_libraries check if dexpreopt is globally disabled. Without dexpreopt the
1345 // check is not necessary, and although it is good to have, it is difficult to maintain on
1346 // non-linux build platforms where dexpreopt is generally disabled (the check may fail due to
1347 // various unrelated reasons, such as a failure to get manifest from an APK).
Ulya Trafimovich39dd0a42021-03-29 14:57:34 +01001348 global := dexpreopt.GetGlobalConfig(ctx)
1349 if global.DisablePreopt || global.OnlyPreoptBootImageAndSystemServer {
Ulya Trafimovicha76d6602021-03-16 15:34:50 +00001350 return inputFile
Ulya Trafimovich6e55ef12021-03-04 12:37:50 +00001351 }
1352
Colin Crossf1a035e2020-11-16 17:32:30 -08001353 rule := android.NewRuleBuilder(pctx, ctx)
1354 cmd := rule.Command().BuiltTool("manifest_check").
Colin Cross50ddcc42019-05-16 12:28:22 -07001355 Flag("--enforce-uses-libraries").
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001356 Input(inputFile).
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +00001357 FlagWithOutput("--enforce-uses-libraries-status ", statusFile).
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001358 FlagWithInput("--aapt ", ctx.Config().HostToolPath(ctx, "aapt"))
1359
1360 if outputFile != nil {
1361 cmd.FlagWithOutput("-o ", outputFile)
1362 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001363
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +00001364 if dexpreopt.GetGlobalConfig(ctx).RelaxUsesLibraryCheck {
1365 cmd.Flag("--enforce-uses-libraries-relax")
1366 }
1367
Colin Cross50ddcc42019-05-16 12:28:22 -07001368 for _, lib := range u.usesLibraryProperties.Uses_libs {
1369 cmd.FlagWithArg("--uses-library ", lib)
1370 }
1371
1372 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1373 cmd.FlagWithArg("--optional-uses-library ", lib)
1374 }
1375
Colin Crossf1a035e2020-11-16 17:32:30 -08001376 rule.Build("verify_uses_libraries", "verify <uses-library>")
Ulya Trafimovicha76d6602021-03-16 15:34:50 +00001377 return outputFile
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001378}
Colin Cross50ddcc42019-05-16 12:28:22 -07001379
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001380// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against
1381// the build system and returns the path to a copy of the manifest.
1382func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1383 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
Ulya Trafimovicha76d6602021-03-16 15:34:50 +00001384 return u.verifyUsesLibraries(ctx, manifest, outputFile)
Colin Cross50ddcc42019-05-16 12:28:22 -07001385}
1386
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001387// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the build
1388// system and returns the path to a copy of the APK.
Colin Cross50ddcc42019-05-16 12:28:22 -07001389func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
Ulya Trafimovich0aba2522021-03-03 16:38:37 +00001390 u.verifyUsesLibraries(ctx, apk, nil) // for APKs manifest_check does not write output file
Colin Cross50ddcc42019-05-16 12:28:22 -07001391 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
Colin Cross50ddcc42019-05-16 12:28:22 -07001392 return outputFile
1393}
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -04001394
1395// For Bazel / bp2build
1396
1397type bazelAndroidAppCertificateAttributes struct {
1398 Certificate string
1399}
1400
Liz Kammerbe46fcc2021-11-01 15:32:43 -04001401func (m *AndroidAppCertificate) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
1402 androidAppCertificateBp2Build(ctx, m)
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -04001403}
1404
Liz Kammerbe46fcc2021-11-01 15:32:43 -04001405func androidAppCertificateBp2Build(ctx android.TopDownMutatorContext, module *AndroidAppCertificate) {
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -04001406 var certificate string
1407 if module.properties.Certificate != nil {
1408 certificate = *module.properties.Certificate
1409 }
1410
1411 attrs := &bazelAndroidAppCertificateAttributes{
1412 Certificate: certificate,
1413 }
1414
1415 props := bazel.BazelTargetModuleProperties{
1416 Rule_class: "android_app_certificate",
Sam Delmerico9dfb1392022-02-10 21:11:59 +00001417 Bzl_load_location: "//build/bazel/rules/android:android_app_certificate.bzl",
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -04001418 }
1419
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux447f6c92021-08-31 20:30:36 +00001420 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: module.Name()}, attrs)
Rupert Shuttleworth5c4881c2021-07-28 06:21:31 -04001421}
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001422
1423type bazelAndroidAppAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00001424 *javaCommonAttributes
1425 Deps bazel.LabelListAttribute
Sam Delmerico9dfb1392022-02-10 21:11:59 +00001426 Manifest bazel.Label
1427 Custom_package *string
1428 Resource_files bazel.LabelListAttribute
1429 Certificate *bazel.Label
1430 Certificate_name *string
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001431}
1432
Liz Kammerbe46fcc2021-11-01 15:32:43 -04001433// ConvertWithBp2build is used to convert android_app to Bazel.
1434func (a *AndroidApp) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmericoc0161432022-02-25 21:34:51 +00001435 commonAttrs, depLabels := a.convertLibraryAttrsBp2Build(ctx)
1436
1437 deps := depLabels.Deps
1438 if !commonAttrs.Srcs.IsEmpty() {
1439 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
1440 } else if !deps.IsEmpty() || !depLabels.StaticDeps.IsEmpty() {
1441 ctx.ModuleErrorf("android_app has dynamic or static dependencies but no sources." +
1442 " Bazel does not allow direct dependencies without sources nor exported" +
1443 " dependencies on android_binary rule.")
1444 }
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001445
1446 manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
1447
1448 resourceFiles := bazel.LabelList{
1449 Includes: []bazel.Label{},
1450 }
1451 for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
1452 files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
1453 resourceFiles.Includes = append(resourceFiles.Includes, files...)
1454 }
1455
Sam Delmerico9dfb1392022-02-10 21:11:59 +00001456 var certificate *bazel.Label
1457 certificateNamePtr := a.overridableAppProperties.Certificate
1458 certificateName := proptools.StringDefault(certificateNamePtr, "")
1459 certModule := android.SrcIsModule(certificateName)
1460 if certModule != "" {
1461 c := android.BazelLabelForModuleDepSingle(ctx, certificateName)
1462 certificate = &c
1463 certificateNamePtr = nil
1464 }
1465
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001466 attrs := &bazelAndroidAppAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00001467 commonAttrs,
1468 deps,
Romain Jobredeauxe8acade2022-02-02 12:16:58 -05001469 android.BazelLabelForModuleSrcSingle(ctx, manifest),
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001470 // TODO(b/209576404): handle package name override by product variable PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
Romain Jobredeauxe8acade2022-02-02 12:16:58 -05001471 a.overridableAppProperties.Package_name,
1472 bazel.MakeLabelListAttribute(resourceFiles),
Sam Delmerico9dfb1392022-02-10 21:11:59 +00001473 certificate,
1474 certificateNamePtr,
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001475 }
Sam Delmerico9dfb1392022-02-10 21:11:59 +00001476
1477 props := bazel.BazelTargetModuleProperties{
1478 Rule_class: "android_binary",
1479 Bzl_load_location: "//build/bazel/rules/android:android_binary.bzl",
1480 }
Romain Jobredeaux1282c422021-10-29 10:52:59 -04001481
1482 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: a.Name()}, attrs)
1483
1484}