blob: 245c586e189b11aa43f352d6e3ebe1b1dc0e5067 [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.
Sasha Smundak854c14f2020-06-16 10:28:22 -0700135 as.masterFile = as.BaseModuleName() + ".apk"
Sasha Smundak4de27a52020-04-23 09:49:59 -0700136 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()
Colin Cross95f7b342020-06-11 11:32:11 -0700689 allowed := ctx.Config().EnforceSystemCertificateAllowList()
Jeongik Chac9464142019-01-07 12:07:27 +0900690
Colin Cross95f7b342020-06-11 11:32:11 -0700691 if enforceSystemCert && !inList(m.Name(), allowed) {
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
Colin Cross1e28e3c2020-06-02 20:09:13 -0700740 a.linter.mergedManifest = a.aapt.mergedManifestFile
741 a.linter.manifest = a.aapt.manifestPath
742 a.linter.resources = a.aapt.resourceFiles
743
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800744 dexJarFile := a.dexBuildActions(ctx)
745
Colin Crosseb032962020-05-13 11:05:02 -0700746 jniLibs, certificateDeps := collectAppDeps(ctx, a, a.shouldEmbedJnis(ctx), !Bool(a.appProperties.Jni_uses_platform_apis))
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800747 jniJarFile := a.jniBuildActions(jniLibs, ctx)
748
749 if ctx.Failed() {
750 return
751 }
752
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700753 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
754 a.certificate = certificates[0]
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800755
756 // Build a final signed app package.
Jaewoong Jung5a498812019-11-07 14:14:38 -0800757 packageFile := android.PathForModuleOut(ctx, a.installApkName+".apk")
Songchun Fan688de9a2020-03-24 20:32:24 -0700758 v4SigningRequested := Bool(a.Module.deviceProperties.V4_signature)
759 var v4SignatureFile android.WritablePath = nil
760 if v4SigningRequested {
761 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+".apk.idsig")
762 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700763 var lineageFile android.Path
764 if lineage := String(a.overridableAppProperties.Lineage); lineage != "" {
765 lineageFile = android.PathForModuleSrc(ctx, lineage)
766 }
767 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800768 a.outputFile = packageFile
Songchun Fan688de9a2020-03-24 20:32:24 -0700769 if v4SigningRequested {
770 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
771 }
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800772
Colin Crosse560c4a2019-03-19 16:03:11 -0700773 for _, split := range a.aapt.splits {
774 // Sign the split APKs
Jaewoong Jung5a498812019-11-07 14:14:38 -0800775 packageFile := android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk")
Songchun Fan688de9a2020-03-24 20:32:24 -0700776 if v4SigningRequested {
777 v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk.idsig")
778 }
Liz Kammer70dd74d2020-05-07 13:24:05 -0700779 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps, v4SignatureFile, lineageFile)
Colin Crosse560c4a2019-03-19 16:03:11 -0700780 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
Songchun Fan688de9a2020-03-24 20:32:24 -0700781 if v4SigningRequested {
782 a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
783 }
Colin Crosse560c4a2019-03-19 16:03:11 -0700784 }
785
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800786 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700787 bundleFile := android.PathForModuleOut(ctx, "base.zip")
788 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
789 a.bundleFile = bundleFile
790
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800791 // Install the app package.
Jiyong Park8ba50f92019-11-13 15:01:01 +0900792 if (Bool(a.Module.properties.Installable) || ctx.Host()) && a.IsForPlatform() {
793 ctx.InstallFile(a.installDir, a.outputFile.Base(), a.outputFile)
794 for _, extra := range a.extraOutputFiles {
795 ctx.InstallFile(a.installDir, extra.Base(), extra)
796 }
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800797 }
Artur Satayevd9b503a2020-04-27 19:05:28 +0100798
799 a.buildAppDependencyInfo(ctx)
Colin Cross30e076a2015-04-13 13:58:27 -0700800}
801
Colin Crosseb032962020-05-13 11:05:02 -0700802type appDepsInterface interface {
803 sdkVersion() sdkSpec
804 minSdkVersion() sdkSpec
805 RequiresStableAPIs(ctx android.BaseModuleContext) bool
806}
807
808func collectAppDeps(ctx android.ModuleContext, app appDepsInterface,
809 shouldCollectRecursiveNativeDeps bool,
Colin Cross1c93c292020-02-15 10:38:00 -0800810 checkNativeSdkVersion bool) ([]jniLib, []Certificate) {
Colin Crosseb032962020-05-13 11:05:02 -0700811
Colin Crossa4f08812018-10-02 22:03:40 -0700812 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900813 var certificates []Certificate
Peter Collingbournead84f972019-12-17 16:46:18 -0800814 seenModulePaths := make(map[string]bool)
Colin Crossa4f08812018-10-02 22:03:40 -0700815
Colin Crosseb032962020-05-13 11:05:02 -0700816 if checkNativeSdkVersion {
817 checkNativeSdkVersion = app.sdkVersion().specified() &&
818 app.sdkVersion().kind != sdkCorePlatform && !app.RequiresStableAPIs(ctx)
819 }
820
Peter Collingbournead84f972019-12-17 16:46:18 -0800821 ctx.WalkDeps(func(module android.Module, parent android.Module) bool {
Colin Crossa4f08812018-10-02 22:03:40 -0700822 otherName := ctx.OtherModuleName(module)
823 tag := ctx.OtherModuleDependencyTag(module)
824
Peter Collingbournead84f972019-12-17 16:46:18 -0800825 if IsJniDepTag(tag) || tag == cc.SharedDepTag {
Colin Crossa4f08812018-10-02 22:03:40 -0700826 if dep, ok := module.(*cc.Module); ok {
Peter Collingbournead84f972019-12-17 16:46:18 -0800827 if dep.IsNdk() || dep.IsStubs() {
828 return false
829 }
830
Colin Crossa4f08812018-10-02 22:03:40 -0700831 lib := dep.OutputFile()
Peter Collingbournead84f972019-12-17 16:46:18 -0800832 path := lib.Path()
833 if seenModulePaths[path.String()] {
834 return false
835 }
836 seenModulePaths[path.String()] = true
837
Colin Crosseb032962020-05-13 11:05:02 -0700838 if checkNativeSdkVersion && dep.SdkVersion() == "" {
839 ctx.PropertyErrorf("jni_libs", "JNI dependency %q uses platform APIs, but this module does not",
840 otherName)
Colin Cross1c93c292020-02-15 10:38:00 -0800841 }
842
Colin Crossa4f08812018-10-02 22:03:40 -0700843 if lib.Valid() {
844 jniLibs = append(jniLibs, jniLib{
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700845 name: ctx.OtherModuleName(module),
846 path: path,
847 target: module.Target(),
848 coverageFile: dep.CoverageOutputFile(),
Colin Crossa4f08812018-10-02 22:03:40 -0700849 })
850 } else {
851 ctx.ModuleErrorf("dependency %q missing output file", otherName)
852 }
853 } else {
854 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700855 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800856
857 return shouldCollectRecursiveNativeDeps
858 }
859
860 if tag == certificateTag {
Colin Crossbd01e2a2018-10-04 15:21:03 -0700861 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900862 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700863 } else {
864 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
865 }
Colin Crossa4f08812018-10-02 22:03:40 -0700866 }
Peter Collingbournead84f972019-12-17 16:46:18 -0800867
868 return false
Colin Crossa4f08812018-10-02 22:03:40 -0700869 })
870
Colin Crossbd01e2a2018-10-04 15:21:03 -0700871 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700872}
873
Artur Satayevd9b503a2020-04-27 19:05:28 +0100874func (a *AndroidApp) walkPayloadDeps(ctx android.ModuleContext,
875 do func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool)) {
876
877 ctx.WalkDeps(func(child, parent android.Module) bool {
878 isExternal := !a.DepIsInSameApex(ctx, child)
879 if am, ok := child.(android.ApexModule); ok {
880 do(ctx, parent, am, isExternal)
881 }
882 return !isExternal
883 })
884}
885
886func (a *AndroidApp) buildAppDependencyInfo(ctx android.ModuleContext) {
887 if ctx.Host() {
888 return
889 }
890
891 depsInfo := android.DepNameToDepInfoMap{}
892 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) {
893 depName := to.Name()
894 if info, exist := depsInfo[depName]; exist {
895 info.From = append(info.From, from.Name())
896 info.IsExternal = info.IsExternal && externalDep
897 depsInfo[depName] = info
898 } else {
899 toMinSdkVersion := "(no version)"
900 if m, ok := to.(interface{ MinSdkVersion() string }); ok {
901 if v := m.MinSdkVersion(); v != "" {
902 toMinSdkVersion = v
903 }
904 }
905 depsInfo[depName] = android.ApexModuleDepInfo{
906 To: depName,
907 From: []string{from.Name()},
908 IsExternal: externalDep,
909 MinSdkVersion: toMinSdkVersion,
910 }
911 }
912 })
913
914 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(), depsInfo)
915}
916
Artur Satayev2b4b7bb2020-04-28 14:57:42 +0100917func (a *AndroidApp) Updatable() bool {
918 return Bool(a.appProperties.Updatable) || a.ApexModuleBase.Updatable()
919}
920
Colin Cross0ea8ba82019-06-06 14:33:29 -0700921func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800922 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
923 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000924 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800925 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800926 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800927}
928
Jiyong Park0f80c182020-01-31 02:49:53 +0900929func (a *AndroidApp) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
930 if IsJniDepTag(ctx.OtherModuleDependencyTag(dep)) {
931 return true
932 }
933 return a.Library.DepIsInSameApex(ctx, dep)
934}
935
Jiyong Parkb7c639e2019-08-19 14:56:02 +0900936// For OutputFileProducer interface
937func (a *AndroidApp) OutputFiles(tag string) (android.Paths, error) {
938 switch tag {
939 case ".aapt.srcjar":
940 return []android.Path{a.aaptSrcJar}, nil
941 }
942 return a.Library.OutputFiles(tag)
943}
944
Jiyong Parkf7487312019-10-17 12:54:30 +0900945func (a *AndroidApp) Privileged() bool {
946 return Bool(a.appProperties.Privileged)
947}
948
Jaewoong Jung37ca4a12020-03-26 14:01:48 -0700949func (a *AndroidApp) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
950 return ctx.Device() && (ctx.DeviceConfig().NativeCoverageEnabled() || ctx.DeviceConfig().ClangCoverageEnabled())
951}
952
953func (a *AndroidApp) PreventInstall() {
954 a.appProperties.PreventInstall = true
955}
956
957func (a *AndroidApp) HideFromMake() {
958 a.appProperties.HideFromMake = true
959}
960
961func (a *AndroidApp) MarkAsCoverageVariant(coverage bool) {
962 a.appProperties.IsCoverageVariant = coverage
963}
964
965var _ cc.Coverage = (*AndroidApp)(nil)
966
Colin Cross1b16b0e2019-02-12 14:41:32 -0800967// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700968func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700969 module := &AndroidApp{}
970
Sasha Smundak2057f822019-04-16 17:16:58 -0700971 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross66dbc0b2017-12-28 12:23:20 -0800972 module.Module.deviceProperties.Optimize.Shrink = proptools.BoolPtr(true)
973
Colin Crossae5caf52018-05-22 11:11:52 -0700974 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700975 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700976
Colin Cross1c14b4e2020-06-15 16:09:53 -0700977 module.addHostAndDeviceProperties()
Colin Cross36242852017-06-23 15:06:31 -0700978 module.AddProperties(
Colin Crossa97c5d32018-03-28 14:58:31 -0700979 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800980 &module.appProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700981 &module.overridableAppProperties,
982 &module.usesLibrary.usesLibraryProperties)
Colin Cross36242852017-06-23 15:06:31 -0700983
Colin Crossa9d8bee2018-10-02 13:59:46 -0700984 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
985 return class == android.Device && ctx.Config().DevicePrefer32BitApps()
986 })
987
Colin Crossa4f08812018-10-02 22:03:40 -0700988 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
989 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800990 android.InitOverridableModule(module, &module.appProperties.Overrides)
Jiyong Park52cd06f2019-11-11 10:14:32 +0900991 android.InitApexModule(module)
Colin Crossa4f08812018-10-02 22:03:40 -0700992
Colin Cross36242852017-06-23 15:06:31 -0700993 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700994}
Colin Crossae5caf52018-05-22 11:11:52 -0700995
996type appTestProperties struct {
997 Instrumentation_for *string
Jaewoong Jung26dedd32019-06-06 08:45:58 -0700998
999 // if specified, the instrumentation target package name in the manifest is overwritten by it.
1000 Instrumentation_target_package *string
Colin Crossae5caf52018-05-22 11:11:52 -07001001}
1002
1003type AndroidTest struct {
1004 AndroidApp
1005
1006 appTestProperties appTestProperties
1007
1008 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001009
1010 testConfig android.Path
Colin Crossd96ca352018-08-10 16:06:24 -07001011 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -07001012}
1013
Jaewoong Jung0949f312019-09-11 10:25:18 -07001014func (a *AndroidTest) InstallInTestcases() bool {
1015 return true
1016}
1017
Colin Crossae5caf52018-05-22 11:11:52 -07001018func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
easoncyleeba606252020-04-30 14:57:06 +08001019 var configs []tradefed.Config
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001020 if a.appTestProperties.Instrumentation_target_package != nil {
1021 a.additionalAaptFlags = append(a.additionalAaptFlags,
1022 "--rename-instrumentation-target-package "+*a.appTestProperties.Instrumentation_target_package)
1023 } else if a.appTestProperties.Instrumentation_for != nil {
1024 // Check if the instrumentation target package is overridden.
Jaewoong Jung4102e5d2019-02-27 16:26:28 -08001025 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
1026 if overridden {
1027 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
1028 }
1029 }
Colin Crossae5caf52018-05-22 11:11:52 -07001030 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -07001031
easoncyleeba606252020-04-30 14:57:06 +08001032 for _, module := range a.testProperties.Test_mainline_modules {
1033 configs = append(configs, tradefed.Option{Name: "config-descriptor:metadata", Key: "mainline-param", Value: module})
1034 }
1035
Jaewoong Jung39982342020-01-14 10:27:18 -08001036 testConfig := tradefed.AutoGenInstrumentationTestConfig(ctx, a.testProperties.Test_config,
easoncyleeba606252020-04-30 14:57:06 +08001037 a.testProperties.Test_config_template, a.manifestPath, a.testProperties.Test_suites, a.testProperties.Auto_gen_config, configs)
Jaewoong Jung39982342020-01-14 10:27:18 -08001038 a.testConfig = a.FixTestConfig(ctx, testConfig)
Colin Cross8a497952019-03-05 22:25:09 -08001039 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001040}
1041
Jaewoong Jung39982342020-01-14 10:27:18 -08001042func (a *AndroidTest) FixTestConfig(ctx android.ModuleContext, testConfig android.Path) android.Path {
1043 if testConfig == nil {
1044 return nil
1045 }
1046
1047 fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", "AndroidTest.xml")
1048 rule := android.NewRuleBuilder()
1049 command := rule.Command().BuiltTool(ctx, "test_config_fixer").Input(testConfig).Output(fixedConfig)
1050 fixNeeded := false
1051
1052 if ctx.ModuleName() != a.installApkName {
1053 fixNeeded = true
1054 command.FlagWithArg("--test-file-name ", a.installApkName+".apk")
1055 }
1056
1057 if a.overridableAppProperties.Package_name != nil {
1058 fixNeeded = true
1059 command.FlagWithInput("--manifest ", a.manifestPath).
1060 FlagWithArg("--package-name ", *a.overridableAppProperties.Package_name)
1061 }
1062
1063 if fixNeeded {
1064 rule.Build(pctx, ctx, "fix_test_config", "fix test config")
1065 return fixedConfig
1066 }
1067 return testConfig
1068}
1069
Colin Cross303e21f2018-08-07 16:49:25 -07001070func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -07001071 a.AndroidApp.DepsMutator(ctx)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001072}
1073
1074func (a *AndroidTest) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
1075 a.AndroidApp.OverridablePropertiesDepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -07001076 if a.appTestProperties.Instrumentation_for != nil {
1077 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
1078 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
1079 // use instrumentationForTag instead of libTag.
1080 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
1081 }
Colin Crossae5caf52018-05-22 11:11:52 -07001082}
1083
Colin Cross1b16b0e2019-02-12 14:41:32 -08001084// android_test compiles test sources and Android resources into an Android application package `.apk` file and
1085// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -07001086func AndroidTestFactory() android.Module {
1087 module := &AndroidTest{}
1088
Sasha Smundak2057f822019-04-16 17:16:58 -07001089 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -07001090
1091 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001092 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001093 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001094 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001095 module.Module.dexpreopter.isTest = true
Colin Cross1e28e3c2020-06-02 20:09:13 -07001096 module.Module.linter.test = true
Colin Crossae5caf52018-05-22 11:11:52 -07001097
Colin Cross1c14b4e2020-06-15 16:09:53 -07001098 module.addHostAndDeviceProperties()
Colin Crossae5caf52018-05-22 11:11:52 -07001099 module.AddProperties(
Colin Crossae5caf52018-05-22 11:11:52 -07001100 &module.aaptProperties,
1101 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001102 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001103 &module.overridableAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -07001104 &module.usesLibrary.usesLibraryProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -07001105 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -07001106
Colin Crossa4f08812018-10-02 22:03:40 -07001107 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1108 android.InitDefaultableModule(module)
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001109 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossae5caf52018-05-22 11:11:52 -07001110 return module
1111}
Colin Crossbd01e2a2018-10-04 15:21:03 -07001112
Colin Cross252fc6f2018-10-04 15:22:03 -07001113type appTestHelperAppProperties struct {
1114 // list of compatibility suites (for example "cts", "vts") that the module should be
1115 // installed into.
1116 Test_suites []string `android:"arch_variant"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001117
1118 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1119 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1120 // explicitly.
1121 Auto_gen_config *bool
Colin Cross252fc6f2018-10-04 15:22:03 -07001122}
1123
1124type AndroidTestHelperApp struct {
1125 AndroidApp
1126
1127 appTestHelperAppProperties appTestHelperAppProperties
1128}
1129
Jaewoong Jung326a9412019-11-21 10:41:00 -08001130func (a *AndroidTestHelperApp) InstallInTestcases() bool {
1131 return true
1132}
1133
Colin Cross1b16b0e2019-02-12 14:41:32 -08001134// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
1135// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
1136// test.
Colin Cross252fc6f2018-10-04 15:22:03 -07001137func AndroidTestHelperAppFactory() android.Module {
1138 module := &AndroidTestHelperApp{}
1139
Sasha Smundak2057f822019-04-16 17:16:58 -07001140 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001141
1142 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -08001143 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -07001144 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -08001145 module.Module.dexpreopter.isTest = true
Colin Cross1e28e3c2020-06-02 20:09:13 -07001146 module.Module.linter.test = true
Colin Cross252fc6f2018-10-04 15:22:03 -07001147
Colin Cross1c14b4e2020-06-15 16:09:53 -07001148 module.addHostAndDeviceProperties()
Colin Cross252fc6f2018-10-04 15:22:03 -07001149 module.AddProperties(
Colin Cross252fc6f2018-10-04 15:22:03 -07001150 &module.aaptProperties,
1151 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -08001152 &module.appTestHelperAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -07001153 &module.overridableAppProperties,
1154 &module.usesLibrary.usesLibraryProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -07001155
1156 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1157 android.InitDefaultableModule(module)
Anton Hansson3d2b6b42020-01-10 15:06:01 +00001158 android.InitApexModule(module)
Colin Cross252fc6f2018-10-04 15:22:03 -07001159 return module
1160}
1161
Colin Crossbd01e2a2018-10-04 15:21:03 -07001162type AndroidAppCertificate struct {
1163 android.ModuleBase
1164 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001165 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -07001166}
1167
1168type AndroidAppCertificateProperties struct {
1169 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
1170 Certificate *string
1171}
1172
Colin Cross1b16b0e2019-02-12 14:41:32 -08001173// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
1174// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -07001175func AndroidAppCertificateFactory() android.Module {
1176 module := &AndroidAppCertificate{}
1177 module.AddProperties(&module.properties)
1178 android.InitAndroidModule(module)
1179 return module
1180}
1181
Colin Crossbd01e2a2018-10-04 15:21:03 -07001182func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1183 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +09001184 c.Certificate = Certificate{
Colin Cross503c1d02020-01-28 14:00:53 -08001185 Pem: android.PathForModuleSrc(ctx, cert+".x509.pem"),
1186 Key: android.PathForModuleSrc(ctx, cert+".pk8"),
Colin Crossbd01e2a2018-10-04 15:21:03 -07001187 }
1188}
Jaewoong Jung525443a2019-02-28 15:35:54 -08001189
1190type OverrideAndroidApp struct {
1191 android.ModuleBase
1192 android.OverrideModuleBase
1193}
1194
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001195func (i *OverrideAndroidApp) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung525443a2019-02-28 15:35:54 -08001196 // All the overrides happen in the base module.
1197 // TODO(jungjw): Check the base module type.
1198}
1199
1200// override_android_app is used to create an android_app module based on another android_app by overriding
1201// some of its properties.
1202func OverrideAndroidAppModuleFactory() android.Module {
1203 m := &OverrideAndroidApp{}
1204 m.AddProperties(&overridableAppProperties{})
1205
Jaewoong Jungb639a6a2019-05-10 15:16:29 -07001206 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -08001207 android.InitOverrideModule(m)
1208 return m
1209}
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001210
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001211type OverrideAndroidTest struct {
1212 android.ModuleBase
1213 android.OverrideModuleBase
1214}
1215
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001216func (i *OverrideAndroidTest) GenerateAndroidBuildActions(_ android.ModuleContext) {
Jaewoong Jung26dedd32019-06-06 08:45:58 -07001217 // All the overrides happen in the base module.
1218 // TODO(jungjw): Check the base module type.
1219}
1220
1221// override_android_test is used to create an android_app module based on another android_test by overriding
1222// some of its properties.
1223func OverrideAndroidTestModuleFactory() android.Module {
1224 m := &OverrideAndroidTest{}
1225 m.AddProperties(&overridableAppProperties{})
1226 m.AddProperties(&appTestProperties{})
1227
1228 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
1229 android.InitOverrideModule(m)
1230 return m
1231}
1232
Roshan Piusb8307962020-04-27 09:42:27 -07001233type OverrideRuntimeResourceOverlay struct {
1234 android.ModuleBase
1235 android.OverrideModuleBase
1236}
1237
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001238func (i *OverrideRuntimeResourceOverlay) GenerateAndroidBuildActions(_ android.ModuleContext) {
Roshan Piusb8307962020-04-27 09:42:27 -07001239 // All the overrides happen in the base module.
1240 // TODO(jungjw): Check the base module type.
1241}
1242
1243// override_runtime_resource_overlay is used to create a module based on another
1244// runtime_resource_overlay module by overriding some of its properties.
1245func OverrideRuntimeResourceOverlayModuleFactory() android.Module {
1246 m := &OverrideRuntimeResourceOverlay{}
1247 m.AddProperties(&OverridableRuntimeResourceOverlayProperties{})
1248
1249 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
1250 android.InitOverrideModule(m)
1251 return m
1252}
1253
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001254type AndroidAppImport struct {
1255 android.ModuleBase
1256 android.DefaultableModuleBase
1257 prebuilt android.Prebuilt
1258
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001259 properties AndroidAppImportProperties
1260 dpiVariants interface{}
1261 archVariants interface{}
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001262
1263 outputFile android.Path
Colin Cross503c1d02020-01-28 14:00:53 -08001264 certificate Certificate
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001265
1266 dexpreopter
Colin Cross50ddcc42019-05-16 12:28:22 -07001267
1268 usesLibrary usesLibrary
Jaewoong Jung8aae22e2019-07-17 10:21:49 -07001269
Liz Kammer7e20dda2020-05-20 14:36:30 -07001270 preprocessed bool
1271
Colin Cross70dda7e2019-10-01 22:05:35 -07001272 installPath android.InstallPath
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001273}
1274
1275type AndroidAppImportProperties struct {
1276 // A prebuilt apk to import
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001277 Apk *string
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001278
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001279 // The name of a certificate in the default certificate directory or an android_app_certificate
1280 // module name in the form ":module". Should be empty if presigned or default_dev_cert is set.
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001281 Certificate *string
1282
1283 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
1284 // be set for presigned modules.
1285 Presigned *bool
1286
Liz Kammer2bc57f62020-05-13 15:49:21 -07001287 // Name of the signing certificate lineage file.
1288 Lineage *string
1289
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001290 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
1291 // need to either specify a specific certificate or be presigned.
1292 Default_dev_cert *bool
1293
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001294 // Specifies that this app should be installed to the priv-app directory,
1295 // where the system will grant it additional privileges not available to
1296 // normal apps.
1297 Privileged *bool
1298
1299 // Names of modules to be overridden. Listed modules can only be other binaries
1300 // (in Make or Soong).
1301 // This does not completely prevent installation of the overridden binaries, but if both
1302 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
1303 // from PRODUCT_PACKAGES.
1304 Overrides []string
Jaewoong Jung8aae22e2019-07-17 10:21:49 -07001305
1306 // Optional name for the installed app. If unspecified, it is derived from the module name.
1307 Filename *string
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001308}
1309
Martin Stjernholm6d415272020-01-31 17:10:36 +00001310func (a *AndroidAppImport) IsInstallable() bool {
1311 return true
1312}
1313
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001314// Updates properties with variant-specific values.
1315func (a *AndroidAppImport) processVariants(ctx android.LoadHookContext) {
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001316 config := ctx.Config()
1317
1318 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
1319 // Try DPI variant matches in the reverse-priority order so that the highest priority match
1320 // overwrites everything else.
1321 // TODO(jungjw): Can we optimize this by making it priority order?
1322 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001323 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001324 }
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001325 if config.ProductAAPTPreferredConfig() != "" {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001326 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001327 }
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001328
1329 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName("Arch")
1330 archType := ctx.Config().Targets[android.Android][0].Arch.ArchType
1331 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001332}
1333
Colin Cross1184b642019-12-30 18:43:07 -08001334func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001335 dst interface{}, variantGroup reflect.Value, variant string) {
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001336 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
1337 if !src.IsValid() {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001338 return
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001339 }
1340
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001341 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
1342 if err != nil {
1343 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
1344 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
1345 } else {
1346 panic(err)
1347 }
1348 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -07001349}
1350
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001351func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
1352 cert := android.SrcIsModule(String(a.properties.Certificate))
1353 if cert != "" {
1354 ctx.AddDependency(ctx.Module(), certificateTag, cert)
1355 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001356
Paul Duffin250e6192019-06-07 10:44:37 +01001357 a.usesLibrary.deps(ctx, true)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001358}
1359
1360func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
1361 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001362 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
1363 // with them may invalidate pre-existing signature data.
Liz Kammer7e20dda2020-05-20 14:36:30 -07001364 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || a.preprocessed) {
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001365 ctx.Build(pctx, android.BuildParams{
1366 Rule: android.Cp,
1367 Output: outputPath,
1368 Input: inputPath,
1369 })
1370 return
1371 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001372 rule := android.NewRuleBuilder()
1373 rule.Command().
1374 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
Colin Crossee94d6a2019-07-08 17:08:34 -07001375 BuiltTool(ctx, "zip2zip").
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001376 FlagWithInput("-i ", inputPath).
1377 FlagWithOutput("-o ", outputPath).
1378 FlagWithArg("-0 ", "'lib/**/*.so'").
1379 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
1380 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
1381}
1382
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001383// Returns whether this module should have the dex file stored uncompressed in the APK.
1384func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
Liz Kammer7e20dda2020-05-20 14:36:30 -07001385 if ctx.Config().UnbundledBuild() || a.preprocessed {
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001386 return false
1387 }
1388
1389 // Uncompress dex in APKs of privileged apps
Jiyong Parkf7487312019-10-17 12:54:30 +09001390 if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001391 return true
1392 }
1393
1394 return shouldUncompressDex(ctx, &a.dexpreopter)
1395}
1396
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001397func (a *AndroidAppImport) uncompressDex(
1398 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
1399 rule := android.NewRuleBuilder()
1400 rule.Command().
1401 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
Colin Crossee94d6a2019-07-08 17:08:34 -07001402 BuiltTool(ctx, "zip2zip").
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001403 FlagWithInput("-i ", inputPath).
1404 FlagWithOutput("-o ", outputPath).
1405 FlagWithArg("-0 ", "'classes*.dex'").
1406 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
1407 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
1408}
1409
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001410func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001411 a.generateAndroidBuildActions(ctx)
1412}
1413
Jooyung Han65cd0f02020-03-23 20:21:11 +09001414func (a *AndroidAppImport) InstallApkName() string {
1415 return a.BaseModuleName()
1416}
1417
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001418func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001419 numCertPropsSet := 0
1420 if String(a.properties.Certificate) != "" {
1421 numCertPropsSet++
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001422 }
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001423 if Bool(a.properties.Presigned) {
1424 numCertPropsSet++
1425 }
1426 if Bool(a.properties.Default_dev_cert) {
1427 numCertPropsSet++
1428 }
1429 if numCertPropsSet != 1 {
1430 ctx.ModuleErrorf("One and only one of certficate, presigned, and default_dev_cert properties must be set")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001431 }
1432
Colin Crosseb032962020-05-13 11:05:02 -07001433 _, certificates := collectAppDeps(ctx, a, false, false)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001434
1435 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001436 // TODO: LOCAL_PACKAGE_SPLITS
1437
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001438 srcApk := a.prebuilt.SingleSourcePath(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -07001439
1440 if a.usesLibrary.enforceUsesLibraries() {
1441 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
1442 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001443
1444 // TODO: Install or embed JNI libraries
1445
1446 // Uncompress JNI libraries in the apk
1447 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
1448 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
1449
Kyeongkab.Namc4997142019-11-22 11:38:16 +09001450 var installDir android.InstallPath
1451 if Bool(a.properties.Privileged) {
1452 installDir = android.PathForModuleInstall(ctx, "priv-app", a.BaseModuleName())
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001453 } else if ctx.InstallInTestcases() {
1454 installDir = android.PathForModuleInstall(ctx, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch())
Kyeongkab.Namc4997142019-11-22 11:38:16 +09001455 } else {
1456 installDir = android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
1457 }
1458
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001459 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001460 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -07001461 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -07001462
1463 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
1464 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
1465 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
1466 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
1467
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001468 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -07001469 if a.dexpreopter.uncompressedDex {
1470 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
1471 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
1472 dexOutput = dexUncompressed
1473 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001474
Jooyung Han65cd0f02020-03-23 20:21:11 +09001475 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
1476
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001477 // TODO: Handle EXTERNAL
Liz Kammer7e20dda2020-05-20 14:36:30 -07001478
1479 // Sign or align the package if package has not been preprocessed
1480 if a.preprocessed {
1481 a.outputFile = srcApk
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001482 a.certificate = PresignedCertificate
Liz Kammer7e20dda2020-05-20 14:36:30 -07001483 } else if !Bool(a.properties.Presigned) {
Jaewoong Jung961d4fd2019-08-22 14:25:58 -07001484 // If the certificate property is empty at this point, default_dev_cert must be set to true.
1485 // Which makes processMainCert's behavior for the empty cert string WAI.
1486 certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001487 if len(certificates) != 1 {
1488 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
1489 }
Colin Cross503c1d02020-01-28 14:00:53 -08001490 a.certificate = certificates[0]
Jooyung Han65cd0f02020-03-23 20:21:11 +09001491 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
Liz Kammer2bc57f62020-05-13 15:49:21 -07001492 var lineageFile android.Path
1493 if lineage := String(a.properties.Lineage); lineage != "" {
1494 lineageFile = android.PathForModuleSrc(ctx, lineage)
1495 }
1496 SignAppPackage(ctx, signed, dexOutput, certificates, nil, lineageFile)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001497 a.outputFile = signed
1498 } else {
Jooyung Han65cd0f02020-03-23 20:21:11 +09001499 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001500 TransformZipAlign(ctx, alignedApk, dexOutput)
1501 a.outputFile = alignedApk
Sasha Smundakc4f0ff12020-05-27 16:36:07 -07001502 a.certificate = PresignedCertificate
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001503 }
1504
1505 // TODO: Optionally compress the output apk.
1506
Jooyung Han65cd0f02020-03-23 20:21:11 +09001507 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001508
1509 // TODO: androidmk converter jni libs
1510}
1511
1512func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
1513 return &a.prebuilt
1514}
1515
1516func (a *AndroidAppImport) Name() string {
1517 return a.prebuilt.Name(a.ModuleBase.Name())
1518}
1519
Dario Frenicde2a032019-10-27 00:29:22 +01001520func (a *AndroidAppImport) OutputFile() android.Path {
1521 return a.outputFile
1522}
1523
Jiyong Park618922e2020-01-08 13:35:43 +09001524func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
1525 return nil
1526}
1527
Colin Cross503c1d02020-01-28 14:00:53 -08001528func (a *AndroidAppImport) Certificate() Certificate {
1529 return a.certificate
1530}
1531
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001532var dpiVariantGroupType reflect.Type
1533var archVariantGroupType reflect.Type
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001534
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001535func initAndroidAppImportVariantGroupTypes() {
1536 dpiVariantGroupType = createVariantGroupType(supportedDpis, "Dpi_variants")
1537
1538 archNames := make([]string, len(android.ArchTypeList()))
1539 for i, archType := range android.ArchTypeList() {
1540 archNames[i] = archType.Name
1541 }
1542 archVariantGroupType = createVariantGroupType(archNames, "Arch")
1543}
1544
1545// Populates all variant struct properties at creation time.
1546func (a *AndroidAppImport) populateAllVariantStructs() {
1547 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
1548 a.AddProperties(a.dpiVariants)
1549
1550 a.archVariants = reflect.New(archVariantGroupType).Interface()
1551 a.AddProperties(a.archVariants)
1552}
1553
Jiyong Parkf7487312019-10-17 12:54:30 +09001554func (a *AndroidAppImport) Privileged() bool {
1555 return Bool(a.properties.Privileged)
1556}
1557
Colin Crosseb032962020-05-13 11:05:02 -07001558func (a *AndroidAppImport) sdkVersion() sdkSpec {
1559 return sdkSpecFrom("")
1560}
1561
1562func (a *AndroidAppImport) minSdkVersion() sdkSpec {
1563 return sdkSpecFrom("")
1564}
1565
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001566func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
1567 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
1568
1569 variantFields := make([]reflect.StructField, len(variants))
1570 for i, variant := range variants {
1571 variantFields[i] = reflect.StructField{
1572 Name: proptools.FieldNameForProperty(variant),
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001573 Type: props,
1574 }
1575 }
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001576
1577 variantGroupStruct := reflect.StructOf(variantFields)
1578 return reflect.StructOf([]reflect.StructField{
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001579 {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001580 Name: variantGroupName,
1581 Type: variantGroupStruct,
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001582 },
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001583 })
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001584}
1585
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001586// android_app_import imports a prebuilt apk with additional processing specified in the module.
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001587// DPI-specific apk source files can be specified using dpi_variants. Example:
1588//
1589// android_app_import {
1590// name: "example_import",
1591// apk: "prebuilts/example.apk",
1592// dpi_variants: {
1593// mdpi: {
1594// apk: "prebuilts/example_mdpi.apk",
1595// },
1596// xhdpi: {
1597// apk: "prebuilts/example_xhdpi.apk",
1598// },
1599// },
1600// certificate: "PRESIGNED",
1601// }
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001602func AndroidAppImportFactory() android.Module {
1603 module := &AndroidAppImport{}
1604 module.AddProperties(&module.properties)
1605 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -07001606 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001607 module.populateAllVariantStructs()
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001608 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
Jaewoong Jung1ce9ac62019-08-13 14:11:33 -07001609 module.processVariants(ctx)
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001610 })
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001611
Jaewoong Jung0feed892020-05-26 20:10:08 -07001612 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1613 android.InitDefaultableModule(module)
Jaewoong Jung3e18b192019-06-11 12:25:34 -07001614 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -07001615
1616 return module
1617}
Colin Cross50ddcc42019-05-16 12:28:22 -07001618
Liz Kammer7e20dda2020-05-20 14:36:30 -07001619type androidTestImportProperties struct {
1620 // Whether the prebuilt apk can be installed without additional processing. Default is false.
1621 Preprocessed *bool
1622}
1623
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001624type AndroidTestImport struct {
1625 AndroidAppImport
1626
1627 testProperties testProperties
1628
Liz Kammer7e20dda2020-05-20 14:36:30 -07001629 testImportProperties androidTestImportProperties
1630
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001631 data android.Paths
1632}
1633
1634func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Liz Kammer7e20dda2020-05-20 14:36:30 -07001635 a.preprocessed = Bool(a.testImportProperties.Preprocessed)
1636
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001637 a.generateAndroidBuildActions(ctx)
1638
1639 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
1640}
1641
Jaewoong Jung7c5bd832020-01-13 09:55:39 -08001642func (a *AndroidTestImport) InstallInTestcases() bool {
1643 return true
1644}
1645
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001646// android_test_import imports a prebuilt test apk with additional processing specified in the
1647// module. DPI or arch variant configurations can be made as with android_app_import.
1648func AndroidTestImportFactory() android.Module {
1649 module := &AndroidTestImport{}
1650 module.AddProperties(&module.properties)
1651 module.AddProperties(&module.dexpreoptProperties)
1652 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
1653 module.AddProperties(&module.testProperties)
Liz Kammer7e20dda2020-05-20 14:36:30 -07001654 module.AddProperties(&module.testImportProperties)
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001655 module.populateAllVariantStructs()
1656 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
1657 module.processVariants(ctx)
1658 })
1659
Colin Crossf30c4532020-05-06 22:29:10 -07001660 module.dexpreopter.isTest = true
1661
Jaewoong Junga689ffe2020-05-01 15:50:08 -07001662 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1663 android.InitDefaultableModule(module)
Jaewoong Jungb28eb5f2019-08-27 15:01:50 -07001664 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
1665
1666 return module
1667}
1668
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001669type RuntimeResourceOverlay struct {
1670 android.ModuleBase
1671 android.DefaultableModuleBase
Roshan Piusb8307962020-04-27 09:42:27 -07001672 android.OverridableModuleBase
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001673 aapt
1674
Roshan Piusb8307962020-04-27 09:42:27 -07001675 properties RuntimeResourceOverlayProperties
1676 overridableProperties OverridableRuntimeResourceOverlayProperties
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001677
Jaewoong Jung78ec5d82020-01-31 10:11:47 -08001678 certificate Certificate
1679
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001680 outputFile android.Path
1681 installDir android.InstallPath
1682}
1683
1684type RuntimeResourceOverlayProperties struct {
1685 // the name of a certificate in the default certificate directory or an android_app_certificate
1686 // module name in the form ":module".
1687 Certificate *string
1688
Liz Kammer7fe241f2020-05-19 16:15:25 -07001689 // Name of the signing certificate lineage file.
1690 Lineage *string
1691
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001692 // optional theme name. If specified, the overlay package will be applied
1693 // only when the ro.boot.vendor.overlay.theme system property is set to the same value.
1694 Theme *string
1695
1696 // if not blank, set to the version of the sdk to compile against.
1697 // Defaults to compiling against the current platform.
1698 Sdk_version *string
1699
1700 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
1701 // Defaults to sdk_version if not set.
1702 Min_sdk_version *string
Jaewoong Jungca095d72020-04-09 16:15:30 -07001703
1704 // list of android_library modules whose resources are extracted and linked against statically
1705 Static_libs []string
1706
1707 // list of android_app modules whose resources are extracted and linked against
1708 Resource_libs []string
Jaewoong Jungbfc6ac02020-04-24 15:22:40 -07001709
1710 // Names of modules to be overridden. Listed modules can only be other overlays
1711 // (in Make or Soong).
1712 // This does not completely prevent installation of the overridden overlays, but if both
1713 // overlays would be installed by default (in PRODUCT_PACKAGES) the other overlay will be removed
1714 // from PRODUCT_PACKAGES.
1715 Overrides []string
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001716}
1717
1718func (r *RuntimeResourceOverlay) DepsMutator(ctx android.BottomUpMutatorContext) {
1719 sdkDep := decodeSdkDep(ctx, sdkContext(r))
1720 if sdkDep.hasFrameworkLibs() {
1721 r.aapt.deps(ctx, sdkDep)
1722 }
1723
1724 cert := android.SrcIsModule(String(r.properties.Certificate))
1725 if cert != "" {
1726 ctx.AddDependency(ctx.Module(), certificateTag, cert)
1727 }
Jaewoong Jungca095d72020-04-09 16:15:30 -07001728
1729 ctx.AddVariationDependencies(nil, staticLibTag, r.properties.Static_libs...)
1730 ctx.AddVariationDependencies(nil, libTag, r.properties.Resource_libs...)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001731}
1732
1733func (r *RuntimeResourceOverlay) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1734 // Compile and link resources
1735 r.aapt.hasNoCode = true
Jaewoong Jungf0f747c2020-01-24 10:30:02 -08001736 // Do not remove resources without default values nor dedupe resource configurations with the same value
Roshan Piusb8307962020-04-27 09:42:27 -07001737 aaptLinkFlags := []string{"--no-resource-deduping", "--no-resource-removal"}
1738 // Allow the override of "package name" and "overlay target package name"
1739 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
1740 if overridden || r.overridableProperties.Package_name != nil {
1741 // The product override variable has a priority over the package_name property.
1742 if !overridden {
1743 manifestPackageName = *r.overridableProperties.Package_name
1744 }
1745 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
1746 }
1747 if r.overridableProperties.Target_package_name != nil {
1748 aaptLinkFlags = append(aaptLinkFlags,
1749 "--rename-overlay-target-package "+*r.overridableProperties.Target_package_name)
1750 }
1751 r.aapt.buildActions(ctx, r, aaptLinkFlags...)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001752
1753 // Sign the built package
Colin Crosseb032962020-05-13 11:05:02 -07001754 _, certificates := collectAppDeps(ctx, r, false, false)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001755 certificates = processMainCert(r.ModuleBase, String(r.properties.Certificate), certificates, ctx)
1756 signed := android.PathForModuleOut(ctx, "signed", r.Name()+".apk")
Liz Kammer7fe241f2020-05-19 16:15:25 -07001757 var lineageFile android.Path
1758 if lineage := String(r.properties.Lineage); lineage != "" {
1759 lineageFile = android.PathForModuleSrc(ctx, lineage)
1760 }
1761 SignAppPackage(ctx, signed, r.aapt.exportPackage, certificates, nil, lineageFile)
Jaewoong Jung78ec5d82020-01-31 10:11:47 -08001762 r.certificate = certificates[0]
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001763
1764 r.outputFile = signed
1765 r.installDir = android.PathForModuleInstall(ctx, "overlay", String(r.properties.Theme))
1766 ctx.InstallFile(r.installDir, r.outputFile.Base(), r.outputFile)
1767}
1768
Jiyong Park6a927c42020-01-21 02:03:43 +09001769func (r *RuntimeResourceOverlay) sdkVersion() sdkSpec {
1770 return sdkSpecFrom(String(r.properties.Sdk_version))
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001771}
1772
1773func (r *RuntimeResourceOverlay) systemModules() string {
1774 return ""
1775}
1776
Jiyong Park6a927c42020-01-21 02:03:43 +09001777func (r *RuntimeResourceOverlay) minSdkVersion() sdkSpec {
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001778 if r.properties.Min_sdk_version != nil {
Jiyong Park6a927c42020-01-21 02:03:43 +09001779 return sdkSpecFrom(*r.properties.Min_sdk_version)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001780 }
1781 return r.sdkVersion()
1782}
1783
Jiyong Park6a927c42020-01-21 02:03:43 +09001784func (r *RuntimeResourceOverlay) targetSdkVersion() sdkSpec {
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001785 return r.sdkVersion()
1786}
1787
1788// runtime_resource_overlay generates a resource-only apk file that can overlay application and
1789// system resources at run time.
1790func RuntimeResourceOverlayFactory() android.Module {
1791 module := &RuntimeResourceOverlay{}
1792 module.AddProperties(
1793 &module.properties,
Roshan Piusb8307962020-04-27 09:42:27 -07001794 &module.aaptProperties,
1795 &module.overridableProperties)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001796
Roshan Piusb8307962020-04-27 09:42:27 -07001797 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
1798 android.InitDefaultableModule(module)
1799 android.InitOverridableModule(module, &module.properties.Overrides)
Jaewoong Jung9befb0c2020-01-18 10:33:43 -08001800 return module
1801}
1802
Colin Cross50ddcc42019-05-16 12:28:22 -07001803type UsesLibraryProperties struct {
1804 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
1805 Uses_libs []string
1806
1807 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
1808 // required=false.
1809 Optional_uses_libs []string
1810
1811 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
1812 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
1813 Enforce_uses_libs *bool
1814}
1815
1816// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
1817// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
1818// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
1819// with knowledge of their shared libraries.
1820type usesLibrary struct {
1821 usesLibraryProperties UsesLibraryProperties
1822}
1823
Paul Duffin250e6192019-06-07 10:44:37 +01001824func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Colin Cross3245b2c2019-06-07 13:18:09 -07001825 if !ctx.Config().UnbundledBuild() {
1826 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
1827 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
Paul Duffin250e6192019-06-07 10:44:37 +01001828 // Only add these extra dependencies if the module depends on framework libs. This avoids
1829 // creating a cyclic dependency:
1830 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1831 if hasFrameworkLibs {
Colin Cross3245b2c2019-06-07 13:18:09 -07001832 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
1833 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
1834 // library to dexpreopt.
1835 ctx.AddVariationDependencies(nil, usesLibTag,
1836 "org.apache.http.legacy",
1837 "android.hidl.base-V1.0-java",
1838 "android.hidl.manager-V1.0-java")
1839 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001840 }
1841}
1842
1843// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1844// build.
1845func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1846 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1847 return optionalUsesLibs
1848}
1849
1850// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
1851func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
1852 usesLibPaths := make(map[string]android.Path)
1853
1854 if !ctx.Config().UnbundledBuild() {
1855 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
1856 if lib, ok := m.(Dependency); ok {
1857 if dexJar := lib.DexJar(); dexJar != nil {
1858 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
1859 } else {
1860 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
1861 ctx.OtherModuleName(m))
1862 }
1863 } else if ctx.Config().AllowMissingDependencies() {
1864 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
1865 } else {
1866 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
1867 ctx.OtherModuleName(m))
1868 }
1869 })
1870 }
1871
1872 return usesLibPaths
1873}
1874
1875// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1876// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1877// unconditionally in the future.
1878func (u *usesLibrary) enforceUsesLibraries() bool {
1879 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1880 len(u.usesLibraryProperties.Optional_uses_libs) > 0
1881 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
1882}
1883
1884// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
1885// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
1886func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1887 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
1888
1889 rule := android.NewRuleBuilder()
Colin Crossee94d6a2019-07-08 17:08:34 -07001890 cmd := rule.Command().BuiltTool(ctx, "manifest_check").
Colin Cross50ddcc42019-05-16 12:28:22 -07001891 Flag("--enforce-uses-libraries").
1892 Input(manifest).
1893 FlagWithOutput("-o ", outputFile)
1894
1895 for _, lib := range u.usesLibraryProperties.Uses_libs {
1896 cmd.FlagWithArg("--uses-library ", lib)
1897 }
1898
1899 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1900 cmd.FlagWithArg("--optional-uses-library ", lib)
1901 }
1902
1903 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1904
1905 return outputFile
1906}
1907
1908// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1909// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1910func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1911 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1912
1913 rule := android.NewRuleBuilder()
1914 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1915 rule.Command().
1916 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1917 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1918 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1919 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1920 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1921
1922 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1923
1924 return outputFile
1925}