blob: ba0565751ad41e311e3f630963be489d5d879d2a [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
17// This file contains the module types for compiling Android apps.
18
19import (
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070020 "path/filepath"
21 "reflect"
Jaewoong Jung5b425e22019-06-17 17:40:56 -070022 "sort"
Sasha Smundak4de27a52020-04-23 09:49:59 -070023 "strconv"
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070024 "strings"
Colin Cross30e076a2015-04-13 13:58:27 -070025
Colin Cross50ddcc42019-05-16 12:28:22 -070026 "github.com/google/blueprint"
27 "github.com/google/blueprint/proptools"
28
Colin Cross635c3b02016-05-18 15:37:25 -070029 "android/soong/android"
Colin Crossa4f08812018-10-02 22:03:40 -070030 "android/soong/cc"
Colin Cross303e21f2018-08-07 16:49:25 -070031 "android/soong/tradefed"
Colin Cross30e076a2015-04-13 13:58:27 -070032)
33
Jaewoong Jung3e18b192019-06-11 12:25:34 -070034var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070035
Colin Cross3bc7ffa2017-11-22 16:19:37 -080036func init() {
Paul Duffinf9b1da02019-12-18 19:51:55 +000037 RegisterAppBuildComponents(android.InitRegistrationContext)
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -070038
39 initAndroidAppImportVariantGroupTypes()
Colin Cross3bc7ffa2017-11-22 16:19:37 -080040}
41
Paul Duffinf9b1da02019-12-18 19:51:55 +000042func RegisterAppBuildComponents(ctx android.RegistrationContext) {
43 ctx.RegisterModuleType("android_app", AndroidAppFactory)
44 ctx.RegisterModuleType("android_test", AndroidTestFactory)
45 ctx.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
46 ctx.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
47 ctx.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
48 ctx.RegisterModuleType("override_android_test", OverrideAndroidTestModuleFactory)
Roshan Piusb8307962020-04-27 09:42:27 -070049 ctx.RegisterModuleType("override_runtime_resource_overlay", OverrideRuntimeResourceOverlayModuleFactory)
Paul Duffinf9b1da02019-12-18 19:51:55 +000050 ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
51 ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -080052 ctx.RegisterModuleType("runtime_resource_overlay", RuntimeResourceOverlayFactory)
Sasha Smundak4de27a52020-04-23 09:49:59 -070053 ctx.RegisterModuleType("android_app_set", AndroidApkSetFactory)
54}
55
56type AndroidAppSetProperties struct {
57 // APK Set path
58 Set *string
59
60 // Specifies that this app should be installed to the priv-app directory,
61 // where the system will grant it additional privileges not available to
62 // normal apps.
63 Privileged *bool
64
65 // APKs in this set use prerelease SDK version
66 Prerelease *bool
67
68 // Names of modules to be overridden. Listed modules can only be other apps
69 // (in Make or Soong).
70 Overrides []string
71}
72
73type AndroidAppSet struct {
74 android.ModuleBase
75 android.DefaultableModuleBase
76 prebuilt android.Prebuilt
77
78 properties AndroidAppSetProperties
79 packedOutput android.WritablePath
80 masterFile string
81}
82
83func (as *AndroidAppSet) Name() string {
84 return as.prebuilt.Name(as.ModuleBase.Name())
85}
86
87func (as *AndroidAppSet) IsInstallable() bool {
88 return true
89}
90
91func (as *AndroidAppSet) Prebuilt() *android.Prebuilt {
92 return &as.prebuilt
93}
94
95func (as *AndroidAppSet) Privileged() bool {
96 return Bool(as.properties.Privileged)
97}
98
Sasha Smundakc4f0ff12020-05-27 16:36:07 -070099func (as *AndroidAppSet) OutputFile() android.Path {
100 return as.packedOutput
101}
102
103func (as *AndroidAppSet) MasterFile() string {
104 return as.masterFile
105}
106
Jaewoong Jung8cf307e2020-05-14 14:15:24 -0700107var TargetCpuAbi = map[string]string{
Sasha Smundak4de27a52020-04-23 09:49:59 -0700108 "arm": "ARMEABI_V7A",
109 "arm64": "ARM64_V8A",
110 "x86": "X86",
111 "x86_64": "X86_64",
112}
113
Jaewoong Jung8cf307e2020-05-14 14:15:24 -0700114func SupportedAbis(ctx android.ModuleContext) []string {
Jaewoong Jung829b7132020-06-10 12:23:32 -0700115 abiName := func(targetIdx int, deviceArch string) string {
Jaewoong Jung8cf307e2020-05-14 14:15:24 -0700116 if abi, found := TargetCpuAbi[deviceArch]; found {
Sasha Smundak4de27a52020-04-23 09:49:59 -0700117 return abi
118 }
Jaewoong Jung829b7132020-06-10 12:23:32 -0700119 ctx.ModuleErrorf("Target %d has invalid Arch: %s", targetIdx, deviceArch)
Sasha Smundak4de27a52020-04-23 09:49:59 -0700120 return "BAD_ABI"
121 }
122
Jaewoong Jung829b7132020-06-10 12:23:32 -0700123 var result []string
124 for i, target := range ctx.Config().Targets[android.Android] {
125 result = append(result, abiName(i, target.Arch.ArchType.String()))
Sasha Smundak4de27a52020-04-23 09:49:59 -0700126 }
127 return result
128}
129
130func (as *AndroidAppSet) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sasha Smundakc4f0ff12020-05-27 16:36:07 -0700131 as.packedOutput = android.PathForModuleOut(ctx, ctx.ModuleName()+".zip")
Sasha Smundak4de27a52020-04-23 09:49:59 -0700132 // We are assuming here that the master file in the APK
133 // set has `.apk` suffix. If it doesn't the build will fail.
134 // APK sets containing APEX files are handled elsewhere.
135 as.masterFile = ctx.ModuleName() + ".apk"
136 screenDensities := "all"
137 if dpis := ctx.Config().ProductAAPTPrebuiltDPI(); len(dpis) > 0 {
138 screenDensities = strings.ToUpper(strings.Join(dpis, ","))
139 }
140 // TODO(asmundak): handle locales.
141 // TODO(asmundak): do we support device features
142 ctx.Build(pctx,
143 android.BuildParams{
144 Rule: extractMatchingApks,
145 Description: "Extract APKs from APK set",
146 Output: as.packedOutput,
147 Inputs: android.Paths{as.prebuilt.SingleSourcePath(ctx)},
148 Args: map[string]string{
Jaewoong Jung8cf307e2020-05-14 14:15:24 -0700149 "abis": strings.Join(SupportedAbis(ctx), ","),
Sasha Smundak4de27a52020-04-23 09:49:59 -0700150 "allow-prereleased": strconv.FormatBool(proptools.Bool(as.properties.Prerelease)),
151 "screen-densities": screenDensities,
152 "sdk-version": ctx.Config().PlatformSdkVersion(),
153 "stem": ctx.ModuleName(),
154 },
155 })
Sasha Smundak4de27a52020-04-23 09:49:59 -0700156}
157
158// android_app_set extracts a set of APKs based on the target device
159// configuration and installs this set as "split APKs".
Sasha Smundakc4f0ff12020-05-27 16:36:07 -0700160// The extracted set always contains 'master' APK whose name is
161// _module_name_.apk and every split APK matching target device.
162// The extraction of the density-specific splits depends on
163// PRODUCT_AAPT_PREBUILT_DPI variable. If present (its value should
164// be a list density names: LDPI, MDPI, HDPI, etc.), only listed
165// splits will be extracted. Otherwise all density-specific splits
166// will be extracted.
Sasha Smundak4de27a52020-04-23 09:49:59 -0700167func AndroidApkSetFactory() android.Module {
168 module := &AndroidAppSet{}
169 module.AddProperties(&module.properties)
170 InitJavaModule(module, android.DeviceSupported)
171 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Set")
172 return module
Paul Duffinf9b1da02019-12-18 19:51:55 +0000173}
174
Colin Cross30e076a2015-04-13 13:58:27 -0700175// AndroidManifest.xml merging
176// package splits
177
Colin Crossfabb6082018-02-20 17:22:23 -0800178type appProperties struct {
Colin Crossbd01e2a2018-10-04 15:21:03 -0700179 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
Colin Cross7d5136f2015-05-11 13:39:40 -0700180 Additional_certificates []string
181
182 // If set, create package-export.apk, which other packages can
183 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
Nan Zhangea568a42017-11-08 21:20:04 -0800184 Export_package_resources *bool
Colin Cross7d5136f2015-05-11 13:39:40 -0700185
Colin Cross16056062017-12-13 22:46:28 -0800186 // Specifies that this app should be installed to the priv-app directory,
187 // where the system will grant it additional privileges not available to
188 // normal apps.
189 Privileged *bool
Colin Crossa97c5d32018-03-28 14:58:31 -0700190
191 // list of resource labels to generate individual resource packages
192 Package_splits []string
Jason Monkd4122be2018-08-10 09:33:36 -0400193
194 // Names of modules to be overridden. Listed modules can only be other binaries
195 // (in Make or Soong).
196 // This does not completely prevent installation of the overridden binaries, but if both
197 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
198 // from PRODUCT_PACKAGES.
199 Overrides []string
Colin Crossa4f08812018-10-02 22:03:40 -0700200
201 // list of native libraries that will be provided in or alongside the resulting jar
202 Jni_libs []string `android:"arch_variant"`
203
Colin Cross76583a42020-05-06 17:51:39 -0700204 // if true, use JNI libraries that link against platform APIs even if this module sets
Colin Crossee87c602020-02-19 16:57:15 -0800205 // sdk_version.
206 Jni_uses_platform_apis *bool
207
Colin Cross76583a42020-05-06 17:51:39 -0700208 // if true, use JNI libraries that link against SDK APIs even if this module does not set
209 // sdk_version.
210 Jni_uses_sdk_apis *bool
211
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700212 // STL library to use for JNI libraries.
213 Stl *string `android:"arch_variant"`
214
Colin Crosse4246ab2019-02-05 21:55:21 -0800215 // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
216 // 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 +0900217 // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to true for
218 // android_app modules that are embedded to APEXes, defaults to false for other module types where the native
219 // libraries are generally preinstalled outside the APK.
Colin Crosse4246ab2019-02-05 21:55:21 -0800220 Use_embedded_native_libs *bool
Colin Cross46abdad2019-02-07 13:07:08 -0800221
222 // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
223 // they are used from inside the APK at runtime.
224 Use_embedded_dex *bool
Colin Cross47fa9d32019-03-26 10:51:39 -0700225
226 // Forces native libraries to always be packaged into the APK,
227 // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
228 // True for android_test* modules.
229 AlwaysPackageNativeLibs bool `blueprint:"mutated"`
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700230
231 // If set, find and merge all NOTICE files that this module and its dependencies have and store
232 // it in the APK as an asset.
233 Embed_notices *bool
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700234
235 // cc.Coverage related properties
236 PreventInstall bool `blueprint:"mutated"`
237 HideFromMake bool `blueprint:"mutated"`
238 IsCoverageVariant bool `blueprint:"mutated"`
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100239
240 // Whether this app is considered mainline updatable or not. When set to true, this will enforce
Artur Satayev11962102020-04-16 13:43:02 +0100241 // additional rules to make sure an app can safely be updated. Default is false.
242 // Prefer using other specific properties if build behaviour must be changed; avoid using this
243 // flag for anything but neverallow rules (unless the behaviour change is invisible to owners).
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100244 Updatable *bool
Colin Cross7d5136f2015-05-11 13:39:40 -0700245}
246
Jaewoong Jung525443a2019-02-28 15:35:54 -0800247// android_app properties that can be overridden by override_android_app
248type overridableAppProperties struct {
249 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
250 // or an android_app_certificate module name in the form ":module".
251 Certificate *string
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700252
Liz Kammer70dd74d2020-05-07 13:24:05 -0700253 // Name of the signing certificate lineage file.
254 Lineage *string
255
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700256 // the package name of this app. The package name in the manifest file is used if one was not given.
257 Package_name *string
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800258
259 // the logging parent of this app.
260 Logging_parent *string
Jaewoong Jung525443a2019-02-28 15:35:54 -0800261}
262
Roshan Piusb8307962020-04-27 09:42:27 -0700263// runtime_resource_overlay properties that can be overridden by override_runtime_resource_overlay
264type OverridableRuntimeResourceOverlayProperties struct {
265 // the package name of this app. The package name in the manifest file is used if one was not given.
266 Package_name *string
267
268 // the target package name of this overlay app. The target package name in the manifest file is used if one was not given.
269 Target_package_name *string
270}
271
Colin Cross30e076a2015-04-13 13:58:27 -0700272type AndroidApp struct {
Colin Crossa97c5d32018-03-28 14:58:31 -0700273 Library
274 aapt
Jaewoong Jung525443a2019-02-28 15:35:54 -0800275 android.OverridableModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700276
Colin Cross50ddcc42019-05-16 12:28:22 -0700277 usesLibrary usesLibrary
278
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900279 certificate Certificate
Colin Cross30e076a2015-04-13 13:58:27 -0700280
Colin Crossfabb6082018-02-20 17:22:23 -0800281 appProperties appProperties
Colin Crossae5caf52018-05-22 11:11:52 -0700282
Jaewoong Jung525443a2019-02-28 15:35:54 -0800283 overridableAppProperties overridableAppProperties
284
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700285 installJniLibs []jniLib
286 jniCoverageOutputs android.Paths
Colin Crossf6237212018-10-29 23:14:58 -0700287
288 bundleFile android.Path
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800289
290 // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
291 installApkName string
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800292
Colin Cross70dda7e2019-10-01 22:05:35 -0700293 installDir android.InstallPath
Jaewoong Jung0949f312019-09-11 10:25:18 -0700294
Jaewoong Jung7dd4ae22019-09-27 17:13:15 -0700295 onDeviceDir string
296
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800297 additionalAaptFlags []string
Jaewoong Jung98772792019-07-01 17:15:13 -0700298
299 noticeOutputs android.NoticeOutputs
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900300
301 overriddenManifestPackageName string
Artur Satayevd9b503a2020-04-27 19:05:28 +0100302
303 android.ApexBundleDepsInfo
Colin Crosse1731a52017-12-14 11:22:55 -0800304}
305
Martin Stjernholm6d415272020-01-31 17:10:36 +0000306func (a *AndroidApp) IsInstallable() bool {
307 return Bool(a.properties.Installable)
308}
309
Colin Cross89c31582018-04-30 15:55:11 -0700310func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
311 return nil
312}
313
Colin Cross66f78822018-05-02 12:58:28 -0700314func (a *AndroidApp) ExportedStaticPackages() android.Paths {
315 return nil
316}
317
Sundong Ahne1f05aa2019-08-27 13:55:42 +0900318func (a *AndroidApp) OutputFile() android.Path {
319 return a.outputFile
320}
321
Colin Cross503c1d02020-01-28 14:00:53 -0800322func (a *AndroidApp) Certificate() Certificate {
323 return a.certificate
324}
325
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700326func (a *AndroidApp) JniCoverageOutputs() android.Paths {
327 return a.jniCoverageOutputs
328}
329
Colin Crossa97c5d32018-03-28 14:58:31 -0700330var _ AndroidLibraryDependency = (*AndroidApp)(nil)
331
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900332type Certificate struct {
Colin Cross503c1d02020-01-28 14:00:53 -0800333 Pem, Key android.Path
334 presigned bool
335}
336
Sasha Smundakc4f0ff12020-05-27 16:36:07 -0700337var PresignedCertificate = Certificate{presigned: true}
Colin Cross503c1d02020-01-28 14:00:53 -0800338
339func (c Certificate) AndroidMkString() string {
340 if c.presigned {
341 return "PRESIGNED"
342 } else {
343 return c.Pem.String()
344 }
Colin Cross30e076a2015-04-13 13:58:27 -0700345}
346
Colin Cross46c9b8b2017-06-22 16:51:17 -0700347func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
348 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700349
Jiyong Park6a927c42020-01-21 02:03:43 +0900350 if String(a.appProperties.Stl) == "c++_shared" && !a.sdkVersion().specified() {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700351 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
352 }
353
Paul Duffin250e6192019-06-07 10:44:37 +0100354 sdkDep := decodeSdkDep(ctx, sdkContext(a))
355 if sdkDep.hasFrameworkLibs() {
356 a.aapt.deps(ctx, sdkDep)
Colin Cross30e076a2015-04-13 13:58:27 -0700357 }
Colin Crossa4f08812018-10-02 22:03:40 -0700358
Colin Cross1dd9c442020-05-08 11:20:24 -0700359 usesSDK := a.sdkVersion().specified() && a.sdkVersion().kind != sdkCorePlatform
360
361 if usesSDK && Bool(a.appProperties.Jni_uses_sdk_apis) {
362 ctx.PropertyErrorf("jni_uses_sdk_apis",
363 "can only be set for modules that do not set sdk_version")
364 } else if !usesSDK && Bool(a.appProperties.Jni_uses_platform_apis) {
365 ctx.PropertyErrorf("jni_uses_platform_apis",
366 "can only be set for modules that set sdk_version")
367 }
368
Peter Collingbournead84f972019-12-17 16:46:18 -0800369 tag := &jniDependencyTag{}
Colin Crossa4f08812018-10-02 22:03:40 -0700370 for _, jniTarget := range ctx.MultiTargets() {
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700371 variation := append(jniTarget.Variations(),
372 blueprint.Variation{Mutator: "link", Variation: "shared"})
Colin Cross01fd7cc2020-02-19 16:54:04 -0800373
374 // If the app builds against an Android SDK use the SDK variant of JNI dependencies
375 // unless jni_uses_platform_apis is set.
Colin Crosseb032962020-05-13 11:05:02 -0700376 // Don't require the SDK variant for apps that are shipped on vendor, etc., as they already
377 // have stable APIs through the VNDK.
378 if (usesSDK && !a.RequiresStableAPIs(ctx) &&
379 !Bool(a.appProperties.Jni_uses_platform_apis)) ||
Colin Cross76583a42020-05-06 17:51:39 -0700380 Bool(a.appProperties.Jni_uses_sdk_apis) {
Colin Cross01fd7cc2020-02-19 16:54:04 -0800381 variation = append(variation, blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
382 }
Colin Crossa4f08812018-10-02 22:03:40 -0700383 ctx.AddFarVariationDependencies(variation, tag, a.appProperties.Jni_libs...)
384 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700385
Paul Duffin250e6192019-06-07 10:44:37 +0100386 a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700387}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700388
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700389func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800390 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700391 if cert != "" {
392 ctx.AddDependency(ctx.Module(), certificateTag, cert)
393 }
394
395 for _, cert := range a.appProperties.Additional_certificates {
396 cert = android.SrcIsModule(cert)
397 if cert != "" {
398 ctx.AddDependency(ctx.Module(), certificateTag, cert)
399 } else {
400 ctx.PropertyErrorf("additional_certificates",
401 `must be names of android_app_certificate modules in the form ":module"`)
402 }
403 }
Colin Cross30e076a2015-04-13 13:58:27 -0700404}
405
Jeongik Cha538c0d02019-07-11 15:54:27 +0900406func (a *AndroidTestHelperApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
407 a.generateAndroidBuildActions(ctx)
408}
409
Colin Cross46c9b8b2017-06-22 16:51:17 -0700410func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100411 a.checkAppSdkVersions(ctx)
Colin Crossae5caf52018-05-22 11:11:52 -0700412 a.generateAndroidBuildActions(ctx)
413}
414
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100415func (a *AndroidApp) checkAppSdkVersions(ctx android.ModuleContext) {
Artur Satayev2b4b7bb2020-04-28 14:57:42 +0100416 if a.Updatable() {
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100417 if !a.sdkVersion().stable() {
418 ctx.PropertyErrorf("sdk_version", "Updatable apps must use stable SDKs, found %v", a.sdkVersion())
419 }
Artur Satayev11962102020-04-16 13:43:02 +0100420 if String(a.deviceProperties.Min_sdk_version) == "" {
421 ctx.PropertyErrorf("updatable", "updatable apps must set min_sdk_version.")
422 }
Jooyung Hanaf7f91f2020-04-29 14:01:06 +0900423 if minSdkVersion, err := a.minSdkVersion().effectiveVersion(ctx); err == nil {
424 a.checkJniLibsSdkVersion(ctx, minSdkVersion)
425 } else {
426 ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
427 }
Artur Satayeve5ac15a2020-04-08 19:09:30 +0100428 }
429
430 a.checkPlatformAPI(ctx)
431 a.checkSdkVersions(ctx)
432}
433
Jooyung Hanaf7f91f2020-04-29 14:01:06 +0900434// If an updatable APK sets min_sdk_version, min_sdk_vesion of JNI libs should match with it.
435// This check is enforced for "updatable" APKs (including APK-in-APEX).
436// b/155209650: until min_sdk_version is properly supported, use sdk_version instead.
437// because, sdk_version is overridden by min_sdk_version (if set as smaller)
438// and linkType is checked with dependencies so we can be sure that the whole dependency tree
439// will meet the requirements.
440func (a *AndroidApp) checkJniLibsSdkVersion(ctx android.ModuleContext, minSdkVersion sdkVersion) {
441 // It's enough to check direct JNI deps' sdk_version because all transitive deps from JNI deps are checked in cc.checkLinkType()
442 ctx.VisitDirectDeps(func(m android.Module) {
443 if !IsJniDepTag(ctx.OtherModuleDependencyTag(m)) {
444 return
445 }
446 dep, _ := m.(*cc.Module)
Jooyung Han9d2c0f72020-05-20 17:12:13 +0900447 // The domain of cc.sdk_version is "current" and <number>
448 // We can rely on sdkSpec to convert it to <number> so that "current" is handled
449 // properly regardless of sdk finalization.
450 jniSdkVersion, err := sdkSpecFrom(dep.SdkVersion()).effectiveVersion(ctx)
451 if err != nil || minSdkVersion < jniSdkVersion {
Jooyung Hanaf7f91f2020-04-29 14:01:06 +0900452 ctx.OtherModuleErrorf(dep, "sdk_version(%v) is higher than min_sdk_version(%v) of the containing android_app(%v)",
453 dep.SdkVersion(), minSdkVersion, ctx.ModuleName())
454 return
455 }
456
457 })
458}
459
Sasha Smundak6ad77252019-05-01 13:16:22 -0700460// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800461// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700462func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Jiyong Park6a927c42020-01-21 02:03:43 +0900463 minSdkVersion, err := a.minSdkVersion().effectiveVersion(ctx)
Colin Crosse4246ab2019-02-05 21:55:21 -0800464 if err != nil {
465 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.minSdkVersion(), err)
466 }
467
Jiyong Park52cd06f2019-11-11 10:14:32 +0900468 return (minSdkVersion >= 23 && Bool(a.appProperties.Use_embedded_native_libs)) ||
469 !a.IsForPlatform()
Colin Crosse4246ab2019-02-05 21:55:21 -0800470}
471
Colin Cross43f08db2018-11-12 10:13:39 -0800472// Returns whether this module should have the dex file stored uncompressed in the APK.
473func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800474 if Bool(a.appProperties.Use_embedded_dex) {
475 return true
476 }
477
Colin Cross53a87f52019-06-25 13:35:30 -0700478 // Uncompress dex in APKs of privileged apps (even for unbundled builds, they may
479 // be preinstalled as prebuilts).
Jiyong Parkf7487312019-10-17 12:54:30 +0900480 if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000481 return true
482 }
483
Colin Cross53a87f52019-06-25 13:35:30 -0700484 if ctx.Config().UnbundledBuild() {
485 return false
486 }
487
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700488 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700489}
490
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700491func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
492 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
Jiyong Park52cd06f2019-11-11 10:14:32 +0900493 !a.IsForPlatform() || a.appProperties.AlwaysPackageNativeLibs
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700494}
495
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900496func (a *AndroidApp) OverriddenManifestPackageName() string {
497 return a.overriddenManifestPackageName
498}
499
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800500func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
David Brazdild25060a2019-02-18 18:24:16 +0000501 a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
502
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700503 // Ask manifest_fixer to add or update the application element indicating this app has no code.
504 a.aapt.hasNoCode = !a.hasCode(ctx)
505
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800506 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800507
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800508 // 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 -0800509 hasProduct := android.PrefixInList(a.aaptProperties.Aaptflags, "--product")
Colin Crosse78dcd32018-04-19 15:25:19 -0700510 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800511 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700512 }
513
Dan Willemsen72be5902018-10-24 20:24:57 -0700514 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
515 // Product AAPT config
516 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800517 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700518 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700519
Dan Willemsen72be5902018-10-24 20:24:57 -0700520 // Product AAPT preferred config
521 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800522 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700523 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700524 }
525
Jiyong Park7f67f482019-01-05 12:57:48 +0900526 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700527 if overridden || a.overridableAppProperties.Package_name != nil {
528 // The product override variable has a priority over the package_name property.
529 if !overridden {
530 manifestPackageName = *a.overridableAppProperties.Package_name
531 }
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800532 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900533 a.overriddenManifestPackageName = manifestPackageName
Jiyong Park7f67f482019-01-05 12:57:48 +0900534 }
535
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800536 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
537
Colin Crosse560c4a2019-03-19 16:03:11 -0700538 a.aapt.splitNames = a.appProperties.Package_splits
Colin Cross50ddcc42019-05-16 12:28:22 -0700539 a.aapt.sdkLibraries = a.exportedSdkLibs
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800540 a.aapt.LoggingParent = String(a.overridableAppProperties.Logging_parent)
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800541 a.aapt.buildActions(ctx, sdkContext(a), aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700542
Colin Cross46c9b8b2017-06-22 16:51:17 -0700543 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700544 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800545}
Colin Cross30e076a2015-04-13 13:58:27 -0700546
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800547func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700548 var staticLibProguardFlagFiles android.Paths
549 ctx.VisitDirectDeps(func(m android.Module) {
550 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
551 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
552 }
553 })
554
555 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
556
557 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
558 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800559}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800560
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800561func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross43f08db2018-11-12 10:13:39 -0800562
563 var installDir string
564 if ctx.ModuleName() == "framework-res" {
565 // framework-res.apk is installed as system/framework/framework-res.apk
566 installDir = "framework"
Jiyong Parkf7487312019-10-17 12:54:30 +0900567 } else if a.Privileged() {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800568 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800569 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800570 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800571 }
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800572 a.dexpreopter.installPath = android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
David Srbecky98c71222020-05-20 22:20:28 +0100573 if a.deviceProperties.Uncompress_dex == nil {
574 // If the value was not force-set by the user, use reasonable default based on the module.
575 a.deviceProperties.Uncompress_dex = proptools.BoolPtr(a.shouldUncompressDex(ctx))
576 }
577 a.dexpreopter.uncompressedDex = *a.deviceProperties.Uncompress_dex
Colin Cross50ddcc42019-05-16 12:28:22 -0700578 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
579 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
580 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
581 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
582 a.dexpreopter.manifestFile = a.mergedManifestFile
583
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800584 if ctx.ModuleName() != "framework-res" {
585 a.Module.compile(ctx, a.aaptSrcJar)
586 }
Colin Cross30e076a2015-04-13 13:58:27 -0700587
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800588 return a.maybeStrippedDexJarFile
589}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800590
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800591func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700592 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700593 if len(jniLibs) > 0 {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700594 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700595 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Sasha Smundak6ad77252019-05-01 13:16:22 -0700596 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700597 for _, jni := range jniLibs {
598 if jni.coverageFile.Valid() {
Jaewoong Junge62e5942020-04-07 13:07:55 -0700599 // Only collect coverage for the first target arch if this is a multilib target.
600 // TODO(jungjw): Ideally, we want to collect both reports, but that would cause coverage
601 // data file path collisions since the current coverage file path format doesn't contain
602 // arch-related strings. This is fine for now though; the code coverage team doesn't use
603 // multi-arch targets such as test_suite_* for coverage collections yet.
604 //
605 // Work with the team to come up with a new format that handles multilib modules properly
606 // and change this.
607 if len(ctx.Config().Targets[android.Android]) == 1 ||
608 ctx.Config().Targets[android.Android][0].Arch.ArchType == jni.target.Arch.ArchType {
609 a.jniCoverageOutputs = append(a.jniCoverageOutputs, jni.coverageFile.Path())
610 }
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700611 }
612 }
Colin Crossa4f08812018-10-02 22:03:40 -0700613 } else {
614 a.installJniLibs = jniLibs
615 }
616 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800617 return jniJarFile
618}
Colin Crossa4f08812018-10-02 22:03:40 -0700619
Jaewoong Jung0949f312019-09-11 10:25:18 -0700620func (a *AndroidApp) noticeBuildActions(ctx android.ModuleContext) {
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700621 // Collect NOTICE files from all dependencies.
622 seenModules := make(map[android.Module]bool)
623 noticePathSet := make(map[android.Path]bool)
624
625 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
626 // Have we already seen this?
627 if _, ok := seenModules[child]; ok {
628 return false
629 }
630 seenModules[child] = true
631
632 // Skip host modules.
633 if child.Target().Os.Class == android.Host || child.Target().Os.Class == android.HostCross {
634 return false
635 }
636
637 path := child.(android.Module).NoticeFile()
638 if path.Valid() {
639 noticePathSet[path.Path()] = true
640 }
641 return true
642 })
643
644 // If the app has one, add it too.
645 if a.NoticeFile().Valid() {
646 noticePathSet[a.NoticeFile().Path()] = true
647 }
648
649 if len(noticePathSet) == 0 {
Jaewoong Jung98772792019-07-01 17:15:13 -0700650 return
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700651 }
652 var noticePaths []android.Path
653 for path := range noticePathSet {
654 noticePaths = append(noticePaths, path)
655 }
656 sort.Slice(noticePaths, func(i, j int) bool {
657 return noticePaths[i].String() < noticePaths[j].String()
658 })
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700659
Jaewoong Jung0949f312019-09-11 10:25:18 -0700660 a.noticeOutputs = android.BuildNoticeOutput(ctx, a.installDir, a.installApkName+".apk", noticePaths)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700661}
662
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700663// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
664// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
665func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
666 if android.SrcIsModule(certPropValue) == "" {
667 var mainCert Certificate
668 if certPropValue != "" {
669 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
670 mainCert = Certificate{
Colin Cross503c1d02020-01-28 14:00:53 -0800671 Pem: defaultDir.Join(ctx, certPropValue+".x509.pem"),
672 Key: defaultDir.Join(ctx, certPropValue+".pk8"),
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700673 }
674 } else {
675 pem, key := ctx.Config().DefaultAppCertificate(ctx)
Colin Cross503c1d02020-01-28 14:00:53 -0800676 mainCert = Certificate{
677 Pem: pem,
678 Key: key,
679 }
Colin Crossbd01e2a2018-10-04 15:21:03 -0700680 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700681 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700682 }
683
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700684 if !m.Platform() {
685 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900686 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
687 if strings.HasPrefix(certPath, systemCertPath) {
688 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
689 whitelist := ctx.Config().EnforceSystemCertificateWhitelist()
690
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700691 if enforceSystemCert && !inList(m.Name(), whitelist) {
Jeongik Chac9464142019-01-07 12:07:27 +0900692 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
693 }
694 }
695 }
696
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700697 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800698}
699
Jooyung Han65cd0f02020-03-23 20:21:11 +0900700func (a *AndroidApp) InstallApkName() string {
701 return a.installApkName
702}
703
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800704func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700705 var apkDeps android.Paths
706
Jeongik Cha538c0d02019-07-11 15:54:27 +0900707 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
708 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
709
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800710 // Check if the install APK name needs to be overridden.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800711 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Name())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800712
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700713 if ctx.ModuleName() == "framework-res" {
714 // framework-res.apk is installed as system/framework/framework-res.apk
Jaewoong Jung0949f312019-09-11 10:25:18 -0700715 a.installDir = android.PathForModuleInstall(ctx, "framework")
Jiyong Parkf7487312019-10-17 12:54:30 +0900716 } else if a.Privileged() {
Jaewoong Jung0949f312019-09-11 10:25:18 -0700717 a.installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
718 } else if ctx.InstallInTestcases() {
Jaewoong Jung326a9412019-11-21 10:41:00 -0800719 a.installDir = android.PathForModuleInstall(ctx, a.installApkName, ctx.DeviceConfig().DeviceArch())
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700720 } else {
Jaewoong Jung0949f312019-09-11 10:25:18 -0700721 a.installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700722 }
Jaewoong Jung7dd4ae22019-09-27 17:13:15 -0700723 a.onDeviceDir = android.InstallPathToOnDevicePath(ctx, a.installDir)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700724
Jaewoong Jung0949f312019-09-11 10:25:18 -0700725 a.noticeBuildActions(ctx)
Jaewoong Jung98772792019-07-01 17:15:13 -0700726 if Bool(a.appProperties.Embed_notices) || ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
727 a.aapt.noticeFile = a.noticeOutputs.HtmlGzOutput
728 }
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700729
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800730 // Process all building blocks, from AAPT to certificates.
731 a.aaptBuildActions(ctx)
732
Colin Cross50ddcc42019-05-16 12:28:22 -0700733 if a.usesLibrary.enforceUsesLibraries() {
734 manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
735 apkDeps = append(apkDeps, manifestCheckFile)
736 }
737
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800738 a.proguardBuildActions(ctx)
739
740 dexJarFile := a.dexBuildActions(ctx)
741
Colin Crosseb032962020-05-13 11:05:02 -0700742 jniLibs, certificateDeps := collectAppDeps(ctx, a, a.shouldEmbedJnis(ctx), !Bool(a.appProperties.Jni_uses_platform_apis))
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800743 jniJarFile := a.jniBuildActions(jniLibs, ctx)
744
745 if ctx.Failed() {
746 return
747 }
748
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700749 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
750 a.certificate = certificates[0]
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800751
752 // Build a final signed app package.
Jaewoong Jung5a498812019-11-07 14:14:38 -0800753 packageFile := android.PathForModuleOut(ctx, a.installApkName+".apk")
Songchun Fan688de9a2020-03-24 20:32:24 -0700754 v4SigningRequested := Bool(a.Module.deviceProperties.V4_signature)
755 var v4SignatureFile android.WritablePath = nil
756 if v4SigningRequested {
757 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+".apk.idsig")
758 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700759 var lineageFile android.Path
760 if lineage := String(a.overridableAppProperties.Lineage); lineage != "" {
761 lineageFile = android.PathForModuleSrc(ctx, lineage)
762 }
763 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800764 a.outputFile = packageFile
Songchun Fan688de9a2020-03-24 20:32:24 -0700765 if v4SigningRequested {
766 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
767 }
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800768
Colin Crosse560c4a2019-03-19 16:03:11 -0700769 for _, split := range a.aapt.splits {
770 // Sign the split APKs
Jaewoong Jung5a498812019-11-07 14:14:38 -0800771 packageFile := android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk")
Songchun Fan688de9a2020-03-24 20:32:24 -0700772 if v4SigningRequested {
773 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk.idsig")
774 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700775 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Crosse560c4a2019-03-19 16:03:11 -0700776 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
Songchun Fan688de9a2020-03-24 20:32:24 -0700777 if v4SigningRequested {
778 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
779 }
Colin Crosse560c4a2019-03-19 16:03:11 -0700780 }
781
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800782 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700783 bundleFile := android.PathForModuleOut(ctx, "base.zip")
784 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
785 a.bundleFile = bundleFile
786
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800787 // Install the app package.
Jiyong Park8ba50f92019-11-13 15:01:01 +0900788 if (Bool(a.Module.properties.Installable) || ctx.Host()) && a.IsForPlatform() {
789 ctx.InstallFile(a.installDir, a.outputFile.Base(), a.outputFile)
790 for _, extra := range a.extraOutputFiles {
791 ctx.InstallFile(a.installDir, extra.Base(), extra)
792 }
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800793 }
Artur Satayevd9b503a2020-04-27 19:05:28 +0100794
795 a.buildAppDependencyInfo(ctx)
Colin Cross30e076a2015-04-13 13:58:27 -0700796}
797
Colin Crosseb032962020-05-13 11:05:02 -0700798type appDepsInterface interface {
799 sdkVersion() sdkSpec
800 minSdkVersion() sdkSpec
801 RequiresStableAPIs(ctx android.BaseModuleContext) bool
802}
803
804func collectAppDeps(ctx android.ModuleContext, app appDepsInterface,
805 shouldCollectRecursiveNativeDeps bool,
Colin Cross1c93c292020-02-15 10:38:00 -0800806 checkNativeSdkVersion bool) ([]jniLib, []Certificate) {
Colin Crosseb032962020-05-13 11:05:02 -0700807
Colin Crossa4f08812018-10-02 22:03:40 -0700808 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900809 var certificates []Certificate
Peter Collingbournead84f972019-12-17 16:46:18 -0800810 seenModulePaths := make(map[string]bool)
Colin Crossa4f08812018-10-02 22:03:40 -0700811
Colin Crosseb032962020-05-13 11:05:02 -0700812 if checkNativeSdkVersion {
813 checkNativeSdkVersion = app.sdkVersion().specified() &&
814 app.sdkVersion().kind != sdkCorePlatform && !app.RequiresStableAPIs(ctx)
815 }
816
Peter Collingbournead84f972019-12-17 16:46:18 -0800817 ctx.WalkDeps(func(module android.Module, parent android.Module) bool {
Colin Crossa4f08812018-10-02 22:03:40 -0700818 otherName := ctx.OtherModuleName(module)
819 tag := ctx.OtherModuleDependencyTag(module)
820
Peter Collingbournead84f972019-12-17 16:46:18 -0800821 if IsJniDepTag(tag) || tag == cc.SharedDepTag {
Colin Crossa4f08812018-10-02 22:03:40 -0700822 if dep, ok := module.(*cc.Module); ok {
Peter Collingbournead84f972019-12-17 16:46:18 -0800823 if dep.IsNdk() || dep.IsStubs() {
824 return false
825 }
826
Colin Crossa4f08812018-10-02 22:03:40 -0700827 lib := dep.OutputFile()
Peter Collingbournead84f972019-12-17 16:46:18 -0800828 path := lib.Path()
829 if seenModulePaths[path.String()] {
830 return false
831 }
832 seenModulePaths[path.String()] = true
833
Colin Crosseb032962020-05-13 11:05:02 -0700834 if checkNativeSdkVersion && dep.SdkVersion() == "" {
835 ctx.PropertyErrorf("jni_libs", "JNI dependency %q uses platform APIs, but this module does not",
836 otherName)
Colin Cross1c93c292020-02-15 10:38:00 -0800837 }
838
Colin Crossa4f08812018-10-02 22:03:40 -0700839 if lib.Valid() {
840 jniLibs = append(jniLibs, jniLib{
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700841 name: ctx.OtherModuleName(module),
842 path: path,
843 target: module.Target(),
844 coverageFile: dep.CoverageOutputFile(),
Colin Crossa4f08812018-10-02 22:03:40 -0700845 })
846 } else {
847 ctx.ModuleErrorf("dependency %q missing output file", otherName)
848 }
849 } else {
850 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700851 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800852
853 return shouldCollectRecursiveNativeDeps
854 }
855
856 if tag == certificateTag {
Colin Crossbd01e2a2018-10-04 15:21:03 -0700857 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900858 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700859 } else {
860 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
861 }
Colin Crossa4f08812018-10-02 22:03:40 -0700862 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800863
864 return false
Colin Crossa4f08812018-10-02 22:03:40 -0700865 })
866
Colin Crossbd01e2a2018-10-04 15:21:03 -0700867 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700868}
869
Artur Satayevd9b503a2020-04-27 19:05:28 +0100870func (a *AndroidApp) walkPayloadDeps(ctx android.ModuleContext,
871 do func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool)) {
872
873 ctx.WalkDeps(func(child, parent android.Module) bool {
874 isExternal := !a.DepIsInSameApex(ctx, child)
875 if am, ok := child.(android.ApexModule); ok {
876 do(ctx, parent, am, isExternal)
877 }
878 return !isExternal
879 })
880}
881
882func (a *AndroidApp) buildAppDependencyInfo(ctx android.ModuleContext) {
883 if ctx.Host() {
884 return
885 }
886
887 depsInfo := android.DepNameToDepInfoMap{}
888 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) {
889 depName := to.Name()
890 if info, exist := depsInfo[depName]; exist {
891 info.From = append(info.From, from.Name())
892 info.IsExternal = info.IsExternal && externalDep
893 depsInfo[depName] = info
894 } else {
895 toMinSdkVersion := "(no version)"
896 if m, ok := to.(interface{ MinSdkVersion() string }); ok {
897 if v := m.MinSdkVersion(); v != "" {
898 toMinSdkVersion = v
899 }
900 }
901 depsInfo[depName] = android.ApexModuleDepInfo{
902 To: depName,
903 From: []string{from.Name()},
904 IsExternal: externalDep,
905 MinSdkVersion: toMinSdkVersion,
906 }
907 }
908 })
909
910 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(), depsInfo)
911}
912
Artur Satayev2b4b7bb2020-04-28 14:57:42 +0100913func (a *AndroidApp) Updatable() bool {
914 return Bool(a.appProperties.Updatable) || a.ApexModuleBase.Updatable()
915}
916
Colin Cross0ea8ba82019-06-06 14:33:29 -0700917func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800918 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
919 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000920 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800921 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800922 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800923}
924
Jiyong Park0f80c182020-01-31 02:49:53 +0900925func (a *AndroidApp) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
926 if IsJniDepTag(ctx.OtherModuleDependencyTag(dep)) {
927 return true
928 }
929 return a.Library.DepIsInSameApex(ctx, dep)
930}
931
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900932// For OutputFileProducer interface
933func (a *AndroidApp) OutputFiles(tag string) (android.Paths, error) {
934 switch tag {
935 case ".aapt.srcjar":
936 return []android.Path{a.aaptSrcJar}, nil
937 }
938 return a.Library.OutputFiles(tag)
939}
940
Jiyong Parkf7487312019-10-17 12:54:30 +0900941func (a *AndroidApp) Privileged() bool {
942 return Bool(a.appProperties.Privileged)
943}
944
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700945func (a *AndroidApp) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
946 return ctx.Device() && (ctx.DeviceConfig().NativeCoverageEnabled() || ctx.DeviceConfig().ClangCoverageEnabled())
947}
948
949func (a *AndroidApp) PreventInstall() {
950 a.appProperties.PreventInstall = true
951}
952
953func (a *AndroidApp) HideFromMake() {
954 a.appProperties.HideFromMake = true
955}
956
957func (a *AndroidApp) MarkAsCoverageVariant(coverage bool) {
958 a.appProperties.IsCoverageVariant = coverage
959}
960
961var _ cc.Coverage = (*AndroidApp)(nil)
962
Colin Cross1b16b0e2019-02-12 14:41:32 -0800963// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700964func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700965 module := &AndroidApp{}
966
Sasha Smundak2057f822019-04-16 17:16:58 -0700967 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross66dbc0b2017-12-28 12:23:20 -0800968 module.Module.deviceProperties.Optimize.Shrink = proptools.BoolPtr(true)
969
Colin Crossae5caf52018-05-22 11:11:52 -0700970 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700971 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700972
Colin Cross36242852017-06-23 15:06:31 -0700973 module.AddProperties(
Colin Cross540eff82017-06-22 17:01:52 -0700974 &module.Module.properties,
975 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800976 &module.Module.dexpreoptProperties,
Colin Crossa97c5d32018-03-28 14:58:31 -0700977 &module.Module.protoProperties,
978 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800979 &module.appProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700980 &module.overridableAppProperties,
981 &module.usesLibrary.usesLibraryProperties)
Colin Cross36242852017-06-23 15:06:31 -0700982
Colin Crossa9d8bee2018-10-02 13:59:46 -0700983 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
984 return class == android.Device && ctx.Config().DevicePrefer32BitApps()
985 })
986
Colin Crossa4f08812018-10-02 22:03:40 -0700987 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
988 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800989 android.InitOverridableModule(module, &module.appProperties.Overrides)
Jiyong Park52cd06f2019-11-11 10:14:32 +0900990 android.InitApexModule(module)
Colin Crossa4f08812018-10-02 22:03:40 -0700991
Colin Cross36242852017-06-23 15:06:31 -0700992 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700993}
Colin Crossae5caf52018-05-22 11:11:52 -0700994
995type appTestProperties struct {
996 Instrumentation_for *string
Jaewoong Jung26dedd32019-06-06 08:45:58 -0700997
998 // if specified, the instrumentation target package name in the manifest is overwritten by it.
999 Instrumentation_target_package *string
Colin Crossae5caf52018-05-22 11:11:52 -07001000}
1001
1002type AndroidTest struct {
1003 AndroidApp
1004
1005 appTestProperties appTestProperties
1006
1007 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001008
1009 testConfig android.Path
Colin Crossd96ca352018-08-10 16:06:24 -07001010 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -07001011}
1012
Jaewoong Jung0949f312019-09-11 10:25:18 -07001013func (a *AndroidTest) InstallInTestcases() bool {
1014 return true
1015}
1016
Colin Crossae5caf52018-05-22 11:11:52 -07001017func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
easoncyleeba606252020-04-30 14:57:06 +08001018 var configs []tradefed.Config
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001019 if a.appTestProperties.Instrumentation_target_package != nil {
1020 a.additionalAaptFlags = append(a.additionalAaptFlags,
1021 "--rename-instrumentation-target-package "+*a.appTestProperties.Instrumentation_target_package)
1022 } else if a.appTestProperties.Instrumentation_for != nil {
1023 // Check if the instrumentation target package is overridden.
Jaewoong Jung4102e5d2019-02-27 16:26:28 -08001024 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
1025 if overridden {
1026 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
1027 }
1028 }
Colin Crossae5caf52018-05-22 11:11:52 -07001029 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -07001030
easoncyleeba606252020-04-30 14:57:06 +08001031 for _, module := range a.testProperties.Test_mainline_modules {
1032 configs = append(configs, tradefed.Option{Name: "config-descriptor:metadata", Key: "mainline-param", Value: module})
1033 }
1034
Jaewoong Jung39982342020-01-14 10:27:18 -08001035 testConfig := tradefed.AutoGenInstrumentationTestConfig(ctx, a.testProperties.Test_config,
easoncyleeba606252020-04-30 14:57:06 +08001036 a.testProperties.Test_config_template, a.manifestPath, a.testProperties.Test_suites, a.testProperties.Auto_gen_config, configs)
Jaewoong Jung39982342020-01-14 10:27:18 -08001037 a.testConfig = a.FixTestConfig(ctx, testConfig)
Colin Cross8a497952019-03-05 22:25:09 -08001038 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001039}
1040
Jaewoong Jung39982342020-01-14 10:27:18 -08001041func (a *AndroidTest) FixTestConfig(ctx android.ModuleContext, testConfig android.Path) android.Path {
1042 if testConfig == nil {
1043 return nil
1044 }
1045
1046 fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", "AndroidTest.xml")
1047 rule := android.NewRuleBuilder()
1048 command := rule.Command().BuiltTool(ctx, "test_config_fixer").Input(testConfig).Output(fixedConfig)
1049 fixNeeded := false
1050
1051 if ctx.ModuleName() != a.installApkName {
1052 fixNeeded = true
1053 command.FlagWithArg("--test-file-name ", a.installApkName+".apk")
1054 }
1055
1056 if a.overridableAppProperties.Package_name != nil {
1057 fixNeeded = true
1058 command.FlagWithInput("--manifest ", a.manifestPath).
1059 FlagWithArg("--package-name ", *a.overridableAppProperties.Package_name)
1060 }
1061
1062 if fixNeeded {
1063 rule.Build(pctx, ctx, "fix_test_config", "fix test config")
1064 return fixedConfig
1065 }
1066 return testConfig
1067}
1068
Colin Cross303e21f2018-08-07 16:49:25 -07001069func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -07001070 a.AndroidApp.DepsMutator(ctx)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001071}
1072
1073func (a *AndroidTest) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
1074 a.AndroidApp.OverridablePropertiesDepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -07001075 if a.appTestProperties.Instrumentation_for != nil {
1076 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
1077 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
1078 // use instrumentationForTag instead of libTag.
1079 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
1080 }
Colin Crossae5caf52018-05-22 11:11:52 -07001081}
1082
Colin Cross1b16b0e2019-02-12 14:41:32 -08001083// android_test compiles test sources and Android resources into an Android application package `.apk` file and
1084// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -07001085func AndroidTestFactory() android.Module {
1086 module := &AndroidTest{}
1087
Sasha Smundak2057f822019-04-16 17:16:58 -07001088 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -07001089
1090 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001091 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001092 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001093 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001094 module.Module.dexpreopter.isTest = true
Colin Crossae5caf52018-05-22 11:11:52 -07001095
1096 module.AddProperties(
1097 &module.Module.properties,
1098 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -08001099 &module.Module.dexpreoptProperties,
Colin Crossae5caf52018-05-22 11:11:52 -07001100 &module.Module.protoProperties,
1101 &module.aaptProperties,
1102 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001103 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001104 &module.overridableAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -07001105 &module.usesLibrary.usesLibraryProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001106 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -07001107
Colin Crossa4f08812018-10-02 22:03:40 -07001108 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1109 android.InitDefaultableModule(module)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001110 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossae5caf52018-05-22 11:11:52 -07001111 return module
1112}
Colin Crossbd01e2a2018-10-04 15:21:03 -07001113
Colin Cross252fc6f2018-10-04 15:22:03 -07001114type appTestHelperAppProperties struct {
1115 // list of compatibility suites (for example "cts", "vts") that the module should be
1116 // installed into.
1117 Test_suites []string `android:"arch_variant"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001118
1119 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1120 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1121 // explicitly.
1122 Auto_gen_config *bool
Colin Cross252fc6f2018-10-04 15:22:03 -07001123}
1124
1125type AndroidTestHelperApp struct {
1126 AndroidApp
1127
1128 appTestHelperAppProperties appTestHelperAppProperties
1129}
1130
Jaewoong Jung326a9412019-11-21 10:41:00 -08001131func (a *AndroidTestHelperApp) InstallInTestcases() bool {
1132 return true
1133}
1134
Colin Cross1b16b0e2019-02-12 14:41:32 -08001135// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
1136// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
1137// test.
Colin Cross252fc6f2018-10-04 15:22:03 -07001138func AndroidTestHelperAppFactory() android.Module {
1139 module := &AndroidTestHelperApp{}
1140
Sasha Smundak2057f822019-04-16 17:16:58 -07001141 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001142
1143 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001144 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001145 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001146 module.Module.dexpreopter.isTest = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001147
1148 module.AddProperties(
1149 &module.Module.properties,
1150 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -08001151 &module.Module.dexpreoptProperties,
Colin Cross252fc6f2018-10-04 15:22:03 -07001152 &module.Module.protoProperties,
1153 &module.aaptProperties,
1154 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001155 &module.appTestHelperAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -07001156 &module.overridableAppProperties,
1157 &module.usesLibrary.usesLibraryProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -07001158
1159 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1160 android.InitDefaultableModule(module)
Anton Hansson3d2b6b42020-01-10 15:06:01 +00001161 android.InitApexModule(module)
Colin Cross252fc6f2018-10-04 15:22:03 -07001162 return module
1163}
1164
Colin Crossbd01e2a2018-10-04 15:21:03 -07001165type AndroidAppCertificate struct {
1166 android.ModuleBase
1167 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001168 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -07001169}
1170
1171type AndroidAppCertificateProperties struct {
1172 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
1173 Certificate *string
1174}
1175
Colin Cross1b16b0e2019-02-12 14:41:32 -08001176// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
1177// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -07001178func AndroidAppCertificateFactory() android.Module {
1179 module := &AndroidAppCertificate{}
1180 module.AddProperties(&module.properties)
1181 android.InitAndroidModule(module)
1182 return module
1183}
1184
Colin Crossbd01e2a2018-10-04 15:21:03 -07001185func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1186 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001187 c.Certificate = Certificate{
Colin Cross503c1d02020-01-28 14:00:53 -08001188 Pem: android.PathForModuleSrc(ctx, cert+".x509.pem"),
1189 Key: android.PathForModuleSrc(ctx, cert+".pk8"),
Colin Crossbd01e2a2018-10-04 15:21:03 -07001190 }
1191}
Jaewoong Jung525443a2019-02-28 15:35:54 -08001192
1193type OverrideAndroidApp struct {
1194 android.ModuleBase
1195 android.OverrideModuleBase
1196}
1197
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001198func (i *OverrideAndroidApp) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung525443a2019-02-28 15:35:54 -08001199 // All the overrides happen in the base module.
1200 // TODO(jungjw): Check the base module type.
1201}
1202
1203// override_android_app is used to create an android_app module based on another android_app by overriding
1204// some of its properties.
1205func OverrideAndroidAppModuleFactory() android.Module {
1206 m := &OverrideAndroidApp{}
1207 m.AddProperties(&overridableAppProperties{})
1208
Jaewoong Jungb639a6a2019-05-10 15:16:29 -07001209 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -08001210 android.InitOverrideModule(m)
1211 return m
1212}
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001213
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001214type OverrideAndroidTest struct {
1215 android.ModuleBase
1216 android.OverrideModuleBase
1217}
1218
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001219func (i *OverrideAndroidTest) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001220 // All the overrides happen in the base module.
1221 // TODO(jungjw): Check the base module type.
1222}
1223
1224// override_android_test is used to create an android_app module based on another android_test by overriding
1225// some of its properties.
1226func OverrideAndroidTestModuleFactory() android.Module {
1227 m := &OverrideAndroidTest{}
1228 m.AddProperties(&overridableAppProperties{})
1229 m.AddProperties(&appTestProperties{})
1230
1231 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
1232 android.InitOverrideModule(m)
1233 return m
1234}
1235
Roshan Piusb8307962020-04-27 09:42:27 -07001236type OverrideRuntimeResourceOverlay struct {
1237 android.ModuleBase
1238 android.OverrideModuleBase
1239}
1240
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001241func (i *OverrideRuntimeResourceOverlay) GenerateAndroidBuildActions(_ android.ModuleContext) {
Roshan Piusb8307962020-04-27 09:42:27 -07001242 // All the overrides happen in the base module.
1243 // TODO(jungjw): Check the base module type.
1244}
1245
1246// override_runtime_resource_overlay is used to create a module based on another
1247// runtime_resource_overlay module by overriding some of its properties.
1248func OverrideRuntimeResourceOverlayModuleFactory() android.Module {
1249 m := &OverrideRuntimeResourceOverlay{}
1250 m.AddProperties(&OverridableRuntimeResourceOverlayProperties{})
1251
1252 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
1253 android.InitOverrideModule(m)
1254 return m
1255}
1256
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001257type AndroidAppImport struct {
1258 android.ModuleBase
1259 android.DefaultableModuleBase
1260 prebuilt android.Prebuilt
1261
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001262 properties AndroidAppImportProperties
1263 dpiVariants interface{}
1264 archVariants interface{}
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001265
1266 outputFile android.Path
Colin Cross503c1d02020-01-28 14:00:53 -08001267 certificate Certificate
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001268
1269 dexpreopter
Colin Cross50ddcc42019-05-16 12:28:22 -07001270
1271 usesLibrary usesLibrary
Jaewoong Jung8aae22e2019-07-17 10:21:49 -07001272
Liz Kammer7e20dda2020-05-20 14:36:30 -07001273 preprocessed bool
1274
Colin Cross70dda7e2019-10-01 22:05:35 -07001275 installPath android.InstallPath
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001276}
1277
1278type AndroidAppImportProperties struct {
1279 // A prebuilt apk to import
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001280 Apk *string
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001281
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001282 // The name of a certificate in the default certificate directory or an android_app_certificate
1283 // module name in the form ":module". Should be empty if presigned or default_dev_cert is set.
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001284 Certificate *string
1285
1286 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
1287 // be set for presigned modules.
1288 Presigned *bool
1289
Liz Kammer2bc57f62020-05-13 15:49:21 -07001290 // Name of the signing certificate lineage file.
1291 Lineage *string
1292
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001293 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
1294 // need to either specify a specific certificate or be presigned.
1295 Default_dev_cert *bool
1296
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001297 // Specifies that this app should be installed to the priv-app directory,
1298 // where the system will grant it additional privileges not available to
1299 // normal apps.
1300 Privileged *bool
1301
1302 // Names of modules to be overridden. Listed modules can only be other binaries
1303 // (in Make or Soong).
1304 // This does not completely prevent installation of the overridden binaries, but if both
1305 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
1306 // from PRODUCT_PACKAGES.
1307 Overrides []string
Jaewoong Jung8aae22e2019-07-17 10:21:49 -07001308
1309 // Optional name for the installed app. If unspecified, it is derived from the module name.
1310 Filename *string
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001311}
1312
Martin Stjernholm6d415272020-01-31 17:10:36 +00001313func (a *AndroidAppImport) IsInstallable() bool {
1314 return true
1315}
1316
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001317// Updates properties with variant-specific values.
1318func (a *AndroidAppImport) processVariants(ctx android.LoadHookContext) {
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001319 config := ctx.Config()
1320
1321 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
1322 // Try DPI variant matches in the reverse-priority order so that the highest priority match
1323 // overwrites everything else.
1324 // TODO(jungjw): Can we optimize this by making it priority order?
1325 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001326 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001327 }
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001328 if config.ProductAAPTPreferredConfig() != "" {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001329 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001330 }
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001331
1332 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName("Arch")
1333 archType := ctx.Config().Targets[android.Android][0].Arch.ArchType
1334 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001335}
1336
Colin Cross1184b642019-12-30 18:43:07 -08001337func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001338 dst interface{}, variantGroup reflect.Value, variant string) {
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001339 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
1340 if !src.IsValid() {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001341 return
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001342 }
1343
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001344 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
1345 if err != nil {
1346 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
1347 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
1348 } else {
1349 panic(err)
1350 }
1351 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001352}
1353
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001354func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
1355 cert := android.SrcIsModule(String(a.properties.Certificate))
1356 if cert != "" {
1357 ctx.AddDependency(ctx.Module(), certificateTag, cert)
1358 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001359
Paul Duffin250e6192019-06-07 10:44:37 +01001360 a.usesLibrary.deps(ctx, true)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001361}
1362
1363func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
1364 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001365 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
1366 // with them may invalidate pre-existing signature data.
Liz Kammer7e20dda2020-05-20 14:36:30 -07001367 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || a.preprocessed) {
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001368 ctx.Build(pctx, android.BuildParams{
1369 Rule: android.Cp,
1370 Output: outputPath,
1371 Input: inputPath,
1372 })
1373 return
1374 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001375 rule := android.NewRuleBuilder()
1376 rule.Command().
1377 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
Colin Crossee94d6a2019-07-08 17:08:34 -07001378 BuiltTool(ctx, "zip2zip").
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001379 FlagWithInput("-i ", inputPath).
1380 FlagWithOutput("-o ", outputPath).
1381 FlagWithArg("-0 ", "'lib/**/*.so'").
1382 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
1383 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
1384}
1385
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001386// Returns whether this module should have the dex file stored uncompressed in the APK.
1387func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
Liz Kammer7e20dda2020-05-20 14:36:30 -07001388 if ctx.Config().UnbundledBuild() || a.preprocessed {
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001389 return false
1390 }
1391
1392 // Uncompress dex in APKs of privileged apps
Jiyong Parkf7487312019-10-17 12:54:30 +09001393 if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001394 return true
1395 }
1396
1397 return shouldUncompressDex(ctx, &a.dexpreopter)
1398}
1399
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001400func (a *AndroidAppImport) uncompressDex(
1401 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
1402 rule := android.NewRuleBuilder()
1403 rule.Command().
1404 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
Colin Crossee94d6a2019-07-08 17:08:34 -07001405 BuiltTool(ctx, "zip2zip").
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001406 FlagWithInput("-i ", inputPath).
1407 FlagWithOutput("-o ", outputPath).
1408 FlagWithArg("-0 ", "'classes*.dex'").
1409 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
1410 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
1411}
1412
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001413func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001414 a.generateAndroidBuildActions(ctx)
1415}
1416
Jooyung Han65cd0f02020-03-23 20:21:11 +09001417func (a *AndroidAppImport) InstallApkName() string {
1418 return a.BaseModuleName()
1419}
1420
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001421func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001422 numCertPropsSet := 0
1423 if String(a.properties.Certificate) != "" {
1424 numCertPropsSet++
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001425 }
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001426 if Bool(a.properties.Presigned) {
1427 numCertPropsSet++
1428 }
1429 if Bool(a.properties.Default_dev_cert) {
1430 numCertPropsSet++
1431 }
1432 if numCertPropsSet != 1 {
1433 ctx.ModuleErrorf("One and only one of certficate, presigned, and default_dev_cert properties must be set")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001434 }
1435
Colin Crosseb032962020-05-13 11:05:02 -07001436 _, certificates := collectAppDeps(ctx, a, false, false)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001437
1438 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001439 // TODO: LOCAL_PACKAGE_SPLITS
1440
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001441 srcApk := a.prebuilt.SingleSourcePath(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -07001442
1443 if a.usesLibrary.enforceUsesLibraries() {
1444 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
1445 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001446
1447 // TODO: Install or embed JNI libraries
1448
1449 // Uncompress JNI libraries in the apk
1450 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
1451 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
1452
Kyeongkab.Namc4997142019-11-22 11:38:16 +09001453 var installDir android.InstallPath
1454 if Bool(a.properties.Privileged) {
1455 installDir = android.PathForModuleInstall(ctx, "priv-app", a.BaseModuleName())
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001456 } else if ctx.InstallInTestcases() {
1457 installDir = android.PathForModuleInstall(ctx, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch())
Kyeongkab.Namc4997142019-11-22 11:38:16 +09001458 } else {
1459 installDir = android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
1460 }
1461
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001462 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001463 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001464 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -07001465
1466 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
1467 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
1468 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
1469 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
1470
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001471 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001472 if a.dexpreopter.uncompressedDex {
1473 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
1474 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
1475 dexOutput = dexUncompressed
1476 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001477
Jooyung Han65cd0f02020-03-23 20:21:11 +09001478 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
1479
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001480 // TODO: Handle EXTERNAL
Liz Kammer7e20dda2020-05-20 14:36:30 -07001481
1482 // Sign or align the package if package has not been preprocessed
1483 if a.preprocessed {
1484 a.outputFile = srcApk
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001485 a.certificate = PresignedCertificate
Liz Kammer7e20dda2020-05-20 14:36:30 -07001486 } else if !Bool(a.properties.Presigned) {
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001487 // If the certificate property is empty at this point, default_dev_cert must be set to true.
1488 // Which makes processMainCert's behavior for the empty cert string WAI.
1489 certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001490 if len(certificates) != 1 {
1491 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
1492 }
Colin Cross503c1d02020-01-28 14:00:53 -08001493 a.certificate = certificates[0]
Jooyung Han65cd0f02020-03-23 20:21:11 +09001494 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
Liz Kammer2bc57f62020-05-13 15:49:21 -07001495 var lineageFile android.Path
1496 if lineage := String(a.properties.Lineage); lineage != "" {
1497 lineageFile = android.PathForModuleSrc(ctx, lineage)
1498 }
1499 SignAppPackage(ctx, signed, dexOutput, certificates, nil, lineageFile)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001500 a.outputFile = signed
1501 } else {
Jooyung Han65cd0f02020-03-23 20:21:11 +09001502 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001503 TransformZipAlign(ctx, alignedApk, dexOutput)
1504 a.outputFile = alignedApk
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001505 a.certificate = PresignedCertificate
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001506 }
1507
1508 // TODO: Optionally compress the output apk.
1509
Jooyung Han65cd0f02020-03-23 20:21:11 +09001510 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001511
1512 // TODO: androidmk converter jni libs
1513}
1514
1515func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
1516 return &a.prebuilt
1517}
1518
1519func (a *AndroidAppImport) Name() string {
1520 return a.prebuilt.Name(a.ModuleBase.Name())
1521}
1522
Dario Frenicde2a032019-10-27 00:29:22 +01001523func (a *AndroidAppImport) OutputFile() android.Path {
1524 return a.outputFile
1525}
1526
Jiyong Park618922e2020-01-08 13:35:43 +09001527func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
1528 return nil
1529}
1530
Colin Cross503c1d02020-01-28 14:00:53 -08001531func (a *AndroidAppImport) Certificate() Certificate {
1532 return a.certificate
1533}
1534
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001535var dpiVariantGroupType reflect.Type
1536var archVariantGroupType reflect.Type
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001537
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001538func initAndroidAppImportVariantGroupTypes() {
1539 dpiVariantGroupType = createVariantGroupType(supportedDpis, "Dpi_variants")
1540
1541 archNames := make([]string, len(android.ArchTypeList()))
1542 for i, archType := range android.ArchTypeList() {
1543 archNames[i] = archType.Name
1544 }
1545 archVariantGroupType = createVariantGroupType(archNames, "Arch")
1546}
1547
1548// Populates all variant struct properties at creation time.
1549func (a *AndroidAppImport) populateAllVariantStructs() {
1550 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
1551 a.AddProperties(a.dpiVariants)
1552
1553 a.archVariants = reflect.New(archVariantGroupType).Interface()
1554 a.AddProperties(a.archVariants)
1555}
1556
Jiyong Parkf7487312019-10-17 12:54:30 +09001557func (a *AndroidAppImport) Privileged() bool {
1558 return Bool(a.properties.Privileged)
1559}
1560
Colin Crosseb032962020-05-13 11:05:02 -07001561func (a *AndroidAppImport) sdkVersion() sdkSpec {
1562 return sdkSpecFrom("")
1563}
1564
1565func (a *AndroidAppImport) minSdkVersion() sdkSpec {
1566 return sdkSpecFrom("")
1567}
1568
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001569func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
1570 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
1571
1572 variantFields := make([]reflect.StructField, len(variants))
1573 for i, variant := range variants {
1574 variantFields[i] = reflect.StructField{
1575 Name: proptools.FieldNameForProperty(variant),
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001576 Type: props,
1577 }
1578 }
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001579
1580 variantGroupStruct := reflect.StructOf(variantFields)
1581 return reflect.StructOf([]reflect.StructField{
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001582 {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001583 Name: variantGroupName,
1584 Type: variantGroupStruct,
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001585 },
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001586 })
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001587}
1588
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001589// android_app_import imports a prebuilt apk with additional processing specified in the module.
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001590// DPI-specific apk source files can be specified using dpi_variants. Example:
1591//
1592// android_app_import {
1593// name: "example_import",
1594// apk: "prebuilts/example.apk",
1595// dpi_variants: {
1596// mdpi: {
1597// apk: "prebuilts/example_mdpi.apk",
1598// },
1599// xhdpi: {
1600// apk: "prebuilts/example_xhdpi.apk",
1601// },
1602// },
1603// certificate: "PRESIGNED",
1604// }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001605func AndroidAppImportFactory() android.Module {
1606 module := &AndroidAppImport{}
1607 module.AddProperties(&module.properties)
1608 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -07001609 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001610 module.populateAllVariantStructs()
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001611 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001612 module.processVariants(ctx)
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001613 })
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001614
Jaewoong Jung0feed892020-05-26 20:10:08 -07001615 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1616 android.InitDefaultableModule(module)
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001617 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001618
1619 return module
1620}
Colin Cross50ddcc42019-05-16 12:28:22 -07001621
Liz Kammer7e20dda2020-05-20 14:36:30 -07001622type androidTestImportProperties struct {
1623 // Whether the prebuilt apk can be installed without additional processing. Default is false.
1624 Preprocessed *bool
1625}
1626
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001627type AndroidTestImport struct {
1628 AndroidAppImport
1629
1630 testProperties testProperties
1631
Liz Kammer7e20dda2020-05-20 14:36:30 -07001632 testImportProperties androidTestImportProperties
1633
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001634 data android.Paths
1635}
1636
1637func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Liz Kammer7e20dda2020-05-20 14:36:30 -07001638 a.preprocessed = Bool(a.testImportProperties.Preprocessed)
1639
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001640 a.generateAndroidBuildActions(ctx)
1641
1642 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
1643}
1644
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001645func (a *AndroidTestImport) InstallInTestcases() bool {
1646 return true
1647}
1648
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001649// android_test_import imports a prebuilt test apk with additional processing specified in the
1650// module. DPI or arch variant configurations can be made as with android_app_import.
1651func AndroidTestImportFactory() android.Module {
1652 module := &AndroidTestImport{}
1653 module.AddProperties(&module.properties)
1654 module.AddProperties(&module.dexpreoptProperties)
1655 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
1656 module.AddProperties(&module.testProperties)
Liz Kammer7e20dda2020-05-20 14:36:30 -07001657 module.AddProperties(&module.testImportProperties)
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001658 module.populateAllVariantStructs()
1659 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
1660 module.processVariants(ctx)
1661 })
1662
Colin Crossf30c4532020-05-06 22:29:10 -07001663 module.dexpreopter.isTest = true
1664
Jaewoong Junga689ffe2020-05-01 15:50:08 -07001665 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1666 android.InitDefaultableModule(module)
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001667 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
1668
1669 return module
1670}
1671
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001672type RuntimeResourceOverlay struct {
1673 android.ModuleBase
1674 android.DefaultableModuleBase
Roshan Piusb8307962020-04-27 09:42:27 -07001675 android.OverridableModuleBase
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001676 aapt
1677
Roshan Piusb8307962020-04-27 09:42:27 -07001678 properties RuntimeResourceOverlayProperties
1679 overridableProperties OverridableRuntimeResourceOverlayProperties
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001680
Jaewoong Jung78ec5d82020-01-31 10:11:47 -08001681 certificate Certificate
1682
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001683 outputFile android.Path
1684 installDir android.InstallPath
1685}
1686
1687type RuntimeResourceOverlayProperties struct {
1688 // the name of a certificate in the default certificate directory or an android_app_certificate
1689 // module name in the form ":module".
1690 Certificate *string
1691
Liz Kammer7fe241f2020-05-19 16:15:25 -07001692 // Name of the signing certificate lineage file.
1693 Lineage *string
1694
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001695 // optional theme name. If specified, the overlay package will be applied
1696 // only when the ro.boot.vendor.overlay.theme system property is set to the same value.
1697 Theme *string
1698
1699 // if not blank, set to the version of the sdk to compile against.
1700 // Defaults to compiling against the current platform.
1701 Sdk_version *string
1702
1703 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
1704 // Defaults to sdk_version if not set.
1705 Min_sdk_version *string
Jaewoong Jungca095d72020-04-09 16:15:30 -07001706
1707 // list of android_library modules whose resources are extracted and linked against statically
1708 Static_libs []string
1709
1710 // list of android_app modules whose resources are extracted and linked against
1711 Resource_libs []string
Jaewoong Jungbfc6ac02020-04-24 15:22:40 -07001712
1713 // Names of modules to be overridden. Listed modules can only be other overlays
1714 // (in Make or Soong).
1715 // This does not completely prevent installation of the overridden overlays, but if both
1716 // overlays would be installed by default (in PRODUCT_PACKAGES) the other overlay will be removed
1717 // from PRODUCT_PACKAGES.
1718 Overrides []string
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001719}
1720
1721func (r *RuntimeResourceOverlay) DepsMutator(ctx android.BottomUpMutatorContext) {
1722 sdkDep := decodeSdkDep(ctx, sdkContext(r))
1723 if sdkDep.hasFrameworkLibs() {
1724 r.aapt.deps(ctx, sdkDep)
1725 }
1726
1727 cert := android.SrcIsModule(String(r.properties.Certificate))
1728 if cert != "" {
1729 ctx.AddDependency(ctx.Module(), certificateTag, cert)
1730 }
Jaewoong Jungca095d72020-04-09 16:15:30 -07001731
1732 ctx.AddVariationDependencies(nil, staticLibTag, r.properties.Static_libs...)
1733 ctx.AddVariationDependencies(nil, libTag, r.properties.Resource_libs...)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001734}
1735
1736func (r *RuntimeResourceOverlay) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1737 // Compile and link resources
1738 r.aapt.hasNoCode = true
Jaewoong Jungf0f747c2020-01-24 10:30:02 -08001739 // Do not remove resources without default values nor dedupe resource configurations with the same value
Roshan Piusb8307962020-04-27 09:42:27 -07001740 aaptLinkFlags := []string{"--no-resource-deduping", "--no-resource-removal"}
1741 // Allow the override of "package name" and "overlay target package name"
1742 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
1743 if overridden || r.overridableProperties.Package_name != nil {
1744 // The product override variable has a priority over the package_name property.
1745 if !overridden {
1746 manifestPackageName = *r.overridableProperties.Package_name
1747 }
1748 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
1749 }
1750 if r.overridableProperties.Target_package_name != nil {
1751 aaptLinkFlags = append(aaptLinkFlags,
1752 "--rename-overlay-target-package "+*r.overridableProperties.Target_package_name)
1753 }
1754 r.aapt.buildActions(ctx, r, aaptLinkFlags...)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001755
1756 // Sign the built package
Colin Crosseb032962020-05-13 11:05:02 -07001757 _, certificates := collectAppDeps(ctx, r, false, false)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001758 certificates = processMainCert(r.ModuleBase, String(r.properties.Certificate), certificates, ctx)
1759 signed := android.PathForModuleOut(ctx, "signed", r.Name()+".apk")
Liz Kammer7fe241f2020-05-19 16:15:25 -07001760 var lineageFile android.Path
1761 if lineage := String(r.properties.Lineage); lineage != "" {
1762 lineageFile = android.PathForModuleSrc(ctx, lineage)
1763 }
1764 SignAppPackage(ctx, signed, r.aapt.exportPackage, certificates, nil, lineageFile)
Jaewoong Jung78ec5d82020-01-31 10:11:47 -08001765 r.certificate = certificates[0]
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001766
1767 r.outputFile = signed
1768 r.installDir = android.PathForModuleInstall(ctx, "overlay", String(r.properties.Theme))
1769 ctx.InstallFile(r.installDir, r.outputFile.Base(), r.outputFile)
1770}
1771
Jiyong Park6a927c42020-01-21 02:03:43 +09001772func (r *RuntimeResourceOverlay) sdkVersion() sdkSpec {
1773 return sdkSpecFrom(String(r.properties.Sdk_version))
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001774}
1775
1776func (r *RuntimeResourceOverlay) systemModules() string {
1777 return ""
1778}
1779
Jiyong Park6a927c42020-01-21 02:03:43 +09001780func (r *RuntimeResourceOverlay) minSdkVersion() sdkSpec {
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001781 if r.properties.Min_sdk_version != nil {
Jiyong Park6a927c42020-01-21 02:03:43 +09001782 return sdkSpecFrom(*r.properties.Min_sdk_version)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001783 }
1784 return r.sdkVersion()
1785}
1786
Jiyong Park6a927c42020-01-21 02:03:43 +09001787func (r *RuntimeResourceOverlay) targetSdkVersion() sdkSpec {
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001788 return r.sdkVersion()
1789}
1790
1791// runtime_resource_overlay generates a resource-only apk file that can overlay application and
1792// system resources at run time.
1793func RuntimeResourceOverlayFactory() android.Module {
1794 module := &RuntimeResourceOverlay{}
1795 module.AddProperties(
1796 &module.properties,
Roshan Piusb8307962020-04-27 09:42:27 -07001797 &module.aaptProperties,
1798 &module.overridableProperties)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001799
Roshan Piusb8307962020-04-27 09:42:27 -07001800 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1801 android.InitDefaultableModule(module)
1802 android.InitOverridableModule(module, &module.properties.Overrides)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001803 return module
1804}
1805
Colin Cross50ddcc42019-05-16 12:28:22 -07001806type UsesLibraryProperties struct {
1807 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
1808 Uses_libs []string
1809
1810 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
1811 // required=false.
1812 Optional_uses_libs []string
1813
1814 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
1815 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
1816 Enforce_uses_libs *bool
1817}
1818
1819// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
1820// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
1821// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
1822// with knowledge of their shared libraries.
1823type usesLibrary struct {
1824 usesLibraryProperties UsesLibraryProperties
1825}
1826
Paul Duffin250e6192019-06-07 10:44:37 +01001827func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Colin Cross3245b2c2019-06-07 13:18:09 -07001828 if !ctx.Config().UnbundledBuild() {
1829 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
1830 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
Paul Duffin250e6192019-06-07 10:44:37 +01001831 // Only add these extra dependencies if the module depends on framework libs. This avoids
1832 // creating a cyclic dependency:
1833 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1834 if hasFrameworkLibs {
Colin Cross3245b2c2019-06-07 13:18:09 -07001835 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
1836 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
1837 // library to dexpreopt.
1838 ctx.AddVariationDependencies(nil, usesLibTag,
1839 "org.apache.http.legacy",
1840 "android.hidl.base-V1.0-java",
1841 "android.hidl.manager-V1.0-java")
1842 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001843 }
1844}
1845
1846// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1847// build.
1848func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1849 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1850 return optionalUsesLibs
1851}
1852
1853// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
1854func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
1855 usesLibPaths := make(map[string]android.Path)
1856
1857 if !ctx.Config().UnbundledBuild() {
1858 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
1859 if lib, ok := m.(Dependency); ok {
1860 if dexJar := lib.DexJar(); dexJar != nil {
1861 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
1862 } else {
1863 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
1864 ctx.OtherModuleName(m))
1865 }
1866 } else if ctx.Config().AllowMissingDependencies() {
1867 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
1868 } else {
1869 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
1870 ctx.OtherModuleName(m))
1871 }
1872 })
1873 }
1874
1875 return usesLibPaths
1876}
1877
1878// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1879// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1880// unconditionally in the future.
1881func (u *usesLibrary) enforceUsesLibraries() bool {
1882 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1883 len(u.usesLibraryProperties.Optional_uses_libs) > 0
1884 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
1885}
1886
1887// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
1888// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
1889func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1890 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
1891
1892 rule := android.NewRuleBuilder()
Colin Crossee94d6a2019-07-08 17:08:34 -07001893 cmd := rule.Command().BuiltTool(ctx, "manifest_check").
Colin Cross50ddcc42019-05-16 12:28:22 -07001894 Flag("--enforce-uses-libraries").
1895 Input(manifest).
1896 FlagWithOutput("-o ", outputFile)
1897
1898 for _, lib := range u.usesLibraryProperties.Uses_libs {
1899 cmd.FlagWithArg("--uses-library ", lib)
1900 }
1901
1902 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1903 cmd.FlagWithArg("--optional-uses-library ", lib)
1904 }
1905
1906 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1907
1908 return outputFile
1909}
1910
1911// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1912// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1913func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1914 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1915
1916 rule := android.NewRuleBuilder()
1917 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1918 rule.Command().
1919 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1920 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1921 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1922 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1923 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1924
1925 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1926
1927 return outputFile
1928}