blob: 42f8bada39b1ad6f427b5a2d58435a1da5a07c60 [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"
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070023 "strings"
Colin Cross30e076a2015-04-13 13:58:27 -070024
Colin Cross50ddcc42019-05-16 12:28:22 -070025 "github.com/google/blueprint"
26 "github.com/google/blueprint/proptools"
27
Colin Cross635c3b02016-05-18 15:37:25 -070028 "android/soong/android"
Colin Crossa4f08812018-10-02 22:03:40 -070029 "android/soong/cc"
Colin Cross303e21f2018-08-07 16:49:25 -070030 "android/soong/tradefed"
Colin Cross30e076a2015-04-13 13:58:27 -070031)
32
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070033var supportedDpis = [...]string{"Ldpi", "Mdpi", "Hdpi", "Xhdpi", "Xxhdpi", "Xxxhdpi"}
34var dpiVariantsStruct reflect.Type
35
Colin Cross3bc7ffa2017-11-22 16:19:37 -080036func init() {
Colin Cross5ab4e6d2017-11-22 16:20:45 -080037 android.RegisterModuleType("android_app", AndroidAppFactory)
Colin Crossae5caf52018-05-22 11:11:52 -070038 android.RegisterModuleType("android_test", AndroidTestFactory)
Colin Cross252fc6f2018-10-04 15:22:03 -070039 android.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
Colin Crossbd01e2a2018-10-04 15:21:03 -070040 android.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
Jaewoong Jung525443a2019-02-28 15:35:54 -080041 android.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
Jaewoong Jungccbb3932019-04-15 09:48:31 -070042 android.RegisterModuleType("android_app_import", AndroidAppImportFactory)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070043
44 // Dynamically construct a struct for the dpi_variants property in android_app_import.
45 perDpiStruct := reflect.StructOf([]reflect.StructField{
46 {
47 Name: "Apk",
48 Type: reflect.TypeOf((*string)(nil)),
49 },
50 })
51 dpiVariantsFields := make([]reflect.StructField, len(supportedDpis))
52 for i, dpi := range supportedDpis {
53 dpiVariantsFields[i] = reflect.StructField{
54 Name: string(dpi),
55 Type: perDpiStruct,
56 }
57 }
58 dpiVariantsStruct = reflect.StructOf(dpiVariantsFields)
Colin Cross3bc7ffa2017-11-22 16:19:37 -080059}
60
Colin Cross30e076a2015-04-13 13:58:27 -070061// AndroidManifest.xml merging
62// package splits
63
Colin Crossfabb6082018-02-20 17:22:23 -080064type appProperties struct {
Colin Crossbd01e2a2018-10-04 15:21:03 -070065 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
Colin Cross7d5136f2015-05-11 13:39:40 -070066 Additional_certificates []string
67
68 // If set, create package-export.apk, which other packages can
69 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
Nan Zhangea568a42017-11-08 21:20:04 -080070 Export_package_resources *bool
Colin Cross7d5136f2015-05-11 13:39:40 -070071
Colin Cross16056062017-12-13 22:46:28 -080072 // Specifies that this app should be installed to the priv-app directory,
73 // where the system will grant it additional privileges not available to
74 // normal apps.
75 Privileged *bool
Colin Crossa97c5d32018-03-28 14:58:31 -070076
77 // list of resource labels to generate individual resource packages
78 Package_splits []string
Jason Monkd4122be2018-08-10 09:33:36 -040079
80 // Names of modules to be overridden. Listed modules can only be other binaries
81 // (in Make or Soong).
82 // This does not completely prevent installation of the overridden binaries, but if both
83 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
84 // from PRODUCT_PACKAGES.
85 Overrides []string
Colin Crossa4f08812018-10-02 22:03:40 -070086
87 // list of native libraries that will be provided in or alongside the resulting jar
88 Jni_libs []string `android:"arch_variant"`
89
Jaewoong Jungbc625cd2019-05-06 15:48:44 -070090 // STL library to use for JNI libraries.
91 Stl *string `android:"arch_variant"`
92
Colin Crosse4246ab2019-02-05 21:55:21 -080093 // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
94 // flag so that they are used from inside the APK at runtime. Defaults to true for android_test modules unless
95 // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to false for other
96 // module types where the native libraries are generally preinstalled outside the APK.
97 Use_embedded_native_libs *bool
Colin Cross46abdad2019-02-07 13:07:08 -080098
99 // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
100 // they are used from inside the APK at runtime.
101 Use_embedded_dex *bool
Colin Cross47fa9d32019-03-26 10:51:39 -0700102
103 // Forces native libraries to always be packaged into the APK,
104 // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
105 // True for android_test* modules.
106 AlwaysPackageNativeLibs bool `blueprint:"mutated"`
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700107
108 // If set, find and merge all NOTICE files that this module and its dependencies have and store
109 // it in the APK as an asset.
110 Embed_notices *bool
Colin Cross7d5136f2015-05-11 13:39:40 -0700111}
112
Jaewoong Jung525443a2019-02-28 15:35:54 -0800113// android_app properties that can be overridden by override_android_app
114type overridableAppProperties struct {
115 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
116 // or an android_app_certificate module name in the form ":module".
117 Certificate *string
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700118
119 // the package name of this app. The package name in the manifest file is used if one was not given.
120 Package_name *string
Jaewoong Jung525443a2019-02-28 15:35:54 -0800121}
122
Colin Cross30e076a2015-04-13 13:58:27 -0700123type AndroidApp struct {
Colin Crossa97c5d32018-03-28 14:58:31 -0700124 Library
125 aapt
Jaewoong Jung525443a2019-02-28 15:35:54 -0800126 android.OverridableModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700127
Colin Cross50ddcc42019-05-16 12:28:22 -0700128 usesLibrary usesLibrary
129
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900130 certificate Certificate
Colin Cross30e076a2015-04-13 13:58:27 -0700131
Colin Crossfabb6082018-02-20 17:22:23 -0800132 appProperties appProperties
Colin Crossae5caf52018-05-22 11:11:52 -0700133
Jaewoong Jung525443a2019-02-28 15:35:54 -0800134 overridableAppProperties overridableAppProperties
135
Colin Crossa4f08812018-10-02 22:03:40 -0700136 installJniLibs []jniLib
Colin Crossf6237212018-10-29 23:14:58 -0700137
138 bundleFile android.Path
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800139
140 // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
141 installApkName string
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800142
143 additionalAaptFlags []string
Colin Crosse1731a52017-12-14 11:22:55 -0800144}
145
Colin Cross89c31582018-04-30 15:55:11 -0700146func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
147 return nil
148}
149
Colin Cross66f78822018-05-02 12:58:28 -0700150func (a *AndroidApp) ExportedStaticPackages() android.Paths {
151 return nil
152}
153
Colin Crossa97c5d32018-03-28 14:58:31 -0700154var _ AndroidLibraryDependency = (*AndroidApp)(nil)
155
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900156type Certificate struct {
157 Pem, Key android.Path
Colin Cross30e076a2015-04-13 13:58:27 -0700158}
159
Colin Cross46c9b8b2017-06-22 16:51:17 -0700160func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
161 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700162
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700163 if String(a.appProperties.Stl) == "c++_shared" && a.sdkVersion() == "" {
164 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
165 }
166
Paul Duffin250e6192019-06-07 10:44:37 +0100167 sdkDep := decodeSdkDep(ctx, sdkContext(a))
168 if sdkDep.hasFrameworkLibs() {
169 a.aapt.deps(ctx, sdkDep)
Colin Cross30e076a2015-04-13 13:58:27 -0700170 }
Colin Crossa4f08812018-10-02 22:03:40 -0700171
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700172 embedJni := a.shouldEmbedJnis(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700173 for _, jniTarget := range ctx.MultiTargets() {
174 variation := []blueprint.Variation{
175 {Mutator: "arch", Variation: jniTarget.String()},
176 {Mutator: "link", Variation: "shared"},
177 }
178 tag := &jniDependencyTag{
179 target: jniTarget,
180 }
181 ctx.AddFarVariationDependencies(variation, tag, a.appProperties.Jni_libs...)
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700182 if String(a.appProperties.Stl) == "c++_shared" {
183 if embedJni {
Jaewoong Jung710756a2019-06-04 11:53:47 -0700184 ctx.AddFarVariationDependencies(variation, tag, "ndk_libc++_shared")
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700185 }
186 }
Colin Crossa4f08812018-10-02 22:03:40 -0700187 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700188
Paul Duffin250e6192019-06-07 10:44:37 +0100189 a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700190}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700191
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700192func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800193 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700194 if cert != "" {
195 ctx.AddDependency(ctx.Module(), certificateTag, cert)
196 }
197
198 for _, cert := range a.appProperties.Additional_certificates {
199 cert = android.SrcIsModule(cert)
200 if cert != "" {
201 ctx.AddDependency(ctx.Module(), certificateTag, cert)
202 } else {
203 ctx.PropertyErrorf("additional_certificates",
204 `must be names of android_app_certificate modules in the form ":module"`)
205 }
206 }
Colin Cross30e076a2015-04-13 13:58:27 -0700207}
208
Colin Cross46c9b8b2017-06-22 16:51:17 -0700209func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sasha Smundak6ad77252019-05-01 13:16:22 -0700210 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
Colin Cross46abdad2019-02-07 13:07:08 -0800211 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700212 a.generateAndroidBuildActions(ctx)
213}
214
Sasha Smundak6ad77252019-05-01 13:16:22 -0700215// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800216// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700217func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Colin Crosse4246ab2019-02-05 21:55:21 -0800218 minSdkVersion, err := sdkVersionToNumber(ctx, a.minSdkVersion())
219 if err != nil {
220 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.minSdkVersion(), err)
221 }
222
223 return minSdkVersion >= 23 && Bool(a.appProperties.Use_embedded_native_libs)
224}
225
Colin Cross43f08db2018-11-12 10:13:39 -0800226// Returns whether this module should have the dex file stored uncompressed in the APK.
227func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800228 if Bool(a.appProperties.Use_embedded_dex) {
229 return true
230 }
231
Colin Cross5a0dcd52018-10-05 14:20:06 -0700232 if ctx.Config().UnbundledBuild() {
Colin Cross43f08db2018-11-12 10:13:39 -0800233 return false
Colin Cross5a0dcd52018-10-05 14:20:06 -0700234 }
235
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700236 // Uncompress dex in APKs of privileged apps
237 if ctx.Config().UncompressPrivAppDex() && Bool(a.appProperties.Privileged) {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000238 return true
239 }
240
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700241 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700242}
243
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700244func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
245 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
246 a.appProperties.AlwaysPackageNativeLibs
247}
248
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800249func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
David Brazdild25060a2019-02-18 18:24:16 +0000250 a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
251
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700252 // Ask manifest_fixer to add or update the application element indicating this app has no code.
253 a.aapt.hasNoCode = !a.hasCode(ctx)
254
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800255 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800256
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800257 // Add TARGET_AAPT_CHARACTERISTICS values to AAPT link flags if they exist and --product flags were not provided.
Colin Crosse78dcd32018-04-19 15:25:19 -0700258 hasProduct := false
259 for _, f := range a.aaptProperties.Aaptflags {
260 if strings.HasPrefix(f, "--product") {
261 hasProduct = true
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800262 break
Colin Crosse78dcd32018-04-19 15:25:19 -0700263 }
264 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700265 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800266 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700267 }
268
Dan Willemsen72be5902018-10-24 20:24:57 -0700269 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
270 // Product AAPT config
271 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800272 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700273 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700274
Dan Willemsen72be5902018-10-24 20:24:57 -0700275 // Product AAPT preferred config
276 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800277 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700278 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700279 }
280
Jiyong Park7f67f482019-01-05 12:57:48 +0900281 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700282 if overridden || a.overridableAppProperties.Package_name != nil {
283 // The product override variable has a priority over the package_name property.
284 if !overridden {
285 manifestPackageName = *a.overridableAppProperties.Package_name
286 }
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800287 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
Jiyong Park7f67f482019-01-05 12:57:48 +0900288 }
289
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800290 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
291
Colin Crosse560c4a2019-03-19 16:03:11 -0700292 a.aapt.splitNames = a.appProperties.Package_splits
Colin Cross50ddcc42019-05-16 12:28:22 -0700293 a.aapt.sdkLibraries = a.exportedSdkLibs
Colin Crosse560c4a2019-03-19 16:03:11 -0700294
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800295 a.aapt.buildActions(ctx, sdkContext(a), aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700296
Colin Cross46c9b8b2017-06-22 16:51:17 -0700297 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700298 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800299}
Colin Cross30e076a2015-04-13 13:58:27 -0700300
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800301func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700302 var staticLibProguardFlagFiles android.Paths
303 ctx.VisitDirectDeps(func(m android.Module) {
304 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
305 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
306 }
307 })
308
309 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
310
311 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
312 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800313}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800314
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800315func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross43f08db2018-11-12 10:13:39 -0800316
317 var installDir string
318 if ctx.ModuleName() == "framework-res" {
319 // framework-res.apk is installed as system/framework/framework-res.apk
320 installDir = "framework"
321 } else if Bool(a.appProperties.Privileged) {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800322 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800323 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800324 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800325 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700326
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800327 a.dexpreopter.installPath = android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000328 a.dexpreopter.isInstallable = Bool(a.properties.Installable)
329 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700330
331 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
332 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
333 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
334 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
335 a.dexpreopter.manifestFile = a.mergedManifestFile
336
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000337 a.deviceProperties.UncompressDex = a.dexpreopter.uncompressedDex
Colin Cross5a0dcd52018-10-05 14:20:06 -0700338
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800339 if ctx.ModuleName() != "framework-res" {
340 a.Module.compile(ctx, a.aaptSrcJar)
341 }
Colin Cross30e076a2015-04-13 13:58:27 -0700342
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800343 return a.maybeStrippedDexJarFile
344}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800345
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800346func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700347 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700348 if len(jniLibs) > 0 {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700349 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700350 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Sasha Smundak6ad77252019-05-01 13:16:22 -0700351 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Colin Crossa4f08812018-10-02 22:03:40 -0700352 } else {
353 a.installJniLibs = jniLibs
354 }
355 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800356 return jniJarFile
357}
Colin Crossa4f08812018-10-02 22:03:40 -0700358
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700359func (a *AndroidApp) noticeBuildActions(ctx android.ModuleContext, installDir android.OutputPath) android.OptionalPath {
360 if !Bool(a.appProperties.Embed_notices) && !ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
361 return android.OptionalPath{}
362 }
363
364 // Collect NOTICE files from all dependencies.
365 seenModules := make(map[android.Module]bool)
366 noticePathSet := make(map[android.Path]bool)
367
368 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
369 // Have we already seen this?
370 if _, ok := seenModules[child]; ok {
371 return false
372 }
373 seenModules[child] = true
374
375 // Skip host modules.
376 if child.Target().Os.Class == android.Host || child.Target().Os.Class == android.HostCross {
377 return false
378 }
379
380 path := child.(android.Module).NoticeFile()
381 if path.Valid() {
382 noticePathSet[path.Path()] = true
383 }
384 return true
385 })
386
387 // If the app has one, add it too.
388 if a.NoticeFile().Valid() {
389 noticePathSet[a.NoticeFile().Path()] = true
390 }
391
392 if len(noticePathSet) == 0 {
393 return android.OptionalPath{}
394 }
395 var noticePaths []android.Path
396 for path := range noticePathSet {
397 noticePaths = append(noticePaths, path)
398 }
399 sort.Slice(noticePaths, func(i, j int) bool {
400 return noticePaths[i].String() < noticePaths[j].String()
401 })
402 noticeFile := android.BuildNoticeOutput(ctx, installDir, a.installApkName+".apk", noticePaths)
403
404 return android.OptionalPathForPath(noticeFile)
405}
406
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700407// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
408// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
409func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
410 if android.SrcIsModule(certPropValue) == "" {
411 var mainCert Certificate
412 if certPropValue != "" {
413 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
414 mainCert = Certificate{
415 defaultDir.Join(ctx, certPropValue+".x509.pem"),
416 defaultDir.Join(ctx, certPropValue+".pk8"),
417 }
418 } else {
419 pem, key := ctx.Config().DefaultAppCertificate(ctx)
420 mainCert = Certificate{pem, key}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700421 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700422 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700423 }
424
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700425 if !m.Platform() {
426 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900427 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
428 if strings.HasPrefix(certPath, systemCertPath) {
429 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
430 whitelist := ctx.Config().EnforceSystemCertificateWhitelist()
431
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700432 if enforceSystemCert && !inList(m.Name(), whitelist) {
Jeongik Chac9464142019-01-07 12:07:27 +0900433 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
434 }
435 }
436 }
437
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700438 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800439}
440
441func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700442 var apkDeps android.Paths
443
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800444 // Check if the install APK name needs to be overridden.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800445 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Name())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800446
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700447 var installDir android.OutputPath
448 if ctx.ModuleName() == "framework-res" {
449 // framework-res.apk is installed as system/framework/framework-res.apk
450 installDir = android.PathForModuleInstall(ctx, "framework")
451 } else if Bool(a.appProperties.Privileged) {
452 installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
453 } else {
454 installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
455 }
456
457 a.aapt.noticeFile = a.noticeBuildActions(ctx, installDir)
458
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800459 // Process all building blocks, from AAPT to certificates.
460 a.aaptBuildActions(ctx)
461
Colin Cross50ddcc42019-05-16 12:28:22 -0700462 if a.usesLibrary.enforceUsesLibraries() {
463 manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
464 apkDeps = append(apkDeps, manifestCheckFile)
465 }
466
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800467 a.proguardBuildActions(ctx)
468
469 dexJarFile := a.dexBuildActions(ctx)
470
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700471 jniLibs, certificateDeps := collectAppDeps(ctx)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800472 jniJarFile := a.jniBuildActions(jniLibs, ctx)
473
474 if ctx.Failed() {
475 return
476 }
477
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700478 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
479 a.certificate = certificates[0]
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800480
481 // Build a final signed app package.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800482 // TODO(jungjw): Consider changing this to installApkName.
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800483 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700484 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800485 a.outputFile = packageFile
486
Colin Crosse560c4a2019-03-19 16:03:11 -0700487 for _, split := range a.aapt.splits {
488 // Sign the split APKs
489 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"_"+split.suffix+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700490 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps)
Colin Crosse560c4a2019-03-19 16:03:11 -0700491 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
492 }
493
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800494 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700495 bundleFile := android.PathForModuleOut(ctx, "base.zip")
496 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
497 a.bundleFile = bundleFile
498
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800499 // Install the app package.
Colin Crosse560c4a2019-03-19 16:03:11 -0700500 ctx.InstallFile(installDir, a.installApkName+".apk", a.outputFile)
501 for _, split := range a.aapt.splits {
502 ctx.InstallFile(installDir, a.installApkName+"_"+split.suffix+".apk", split.path)
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800503 }
Colin Cross30e076a2015-04-13 13:58:27 -0700504}
505
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700506func collectAppDeps(ctx android.ModuleContext) ([]jniLib, []Certificate) {
Colin Crossa4f08812018-10-02 22:03:40 -0700507 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900508 var certificates []Certificate
Colin Crossa4f08812018-10-02 22:03:40 -0700509
510 ctx.VisitDirectDeps(func(module android.Module) {
511 otherName := ctx.OtherModuleName(module)
512 tag := ctx.OtherModuleDependencyTag(module)
513
514 if jniTag, ok := tag.(*jniDependencyTag); ok {
515 if dep, ok := module.(*cc.Module); ok {
516 lib := dep.OutputFile()
517 if lib.Valid() {
518 jniLibs = append(jniLibs, jniLib{
519 name: ctx.OtherModuleName(module),
520 path: lib.Path(),
521 target: jniTag.target,
522 })
523 } else {
524 ctx.ModuleErrorf("dependency %q missing output file", otherName)
525 }
526 } else {
527 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700528 }
Colin Crossbd01e2a2018-10-04 15:21:03 -0700529 } else if tag == certificateTag {
530 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900531 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700532 } else {
533 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
534 }
Colin Crossa4f08812018-10-02 22:03:40 -0700535 }
536 })
537
Colin Crossbd01e2a2018-10-04 15:21:03 -0700538 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700539}
540
Colin Cross0ea8ba82019-06-06 14:33:29 -0700541func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800542 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
543 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000544 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800545 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800546 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800547}
548
Colin Cross1b16b0e2019-02-12 14:41:32 -0800549// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700550func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700551 module := &AndroidApp{}
552
Sasha Smundak2057f822019-04-16 17:16:58 -0700553 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross66dbc0b2017-12-28 12:23:20 -0800554 module.Module.deviceProperties.Optimize.Shrink = proptools.BoolPtr(true)
555
Colin Crossae5caf52018-05-22 11:11:52 -0700556 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700557 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700558
Colin Cross36242852017-06-23 15:06:31 -0700559 module.AddProperties(
Colin Cross540eff82017-06-22 17:01:52 -0700560 &module.Module.properties,
561 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800562 &module.Module.dexpreoptProperties,
Colin Crossa97c5d32018-03-28 14:58:31 -0700563 &module.Module.protoProperties,
564 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800565 &module.appProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700566 &module.overridableAppProperties,
567 &module.usesLibrary.usesLibraryProperties)
Colin Cross36242852017-06-23 15:06:31 -0700568
Colin Crossa9d8bee2018-10-02 13:59:46 -0700569 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
570 return class == android.Device && ctx.Config().DevicePrefer32BitApps()
571 })
572
Colin Crossa4f08812018-10-02 22:03:40 -0700573 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
574 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800575 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossa4f08812018-10-02 22:03:40 -0700576
Colin Cross36242852017-06-23 15:06:31 -0700577 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700578}
Colin Crossae5caf52018-05-22 11:11:52 -0700579
580type appTestProperties struct {
581 Instrumentation_for *string
582}
583
584type AndroidTest struct {
585 AndroidApp
586
587 appTestProperties appTestProperties
588
589 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700590
591 testConfig android.Path
Colin Crossd96ca352018-08-10 16:06:24 -0700592 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -0700593}
594
595func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800596 // Check if the instrumentation target package is overridden before generating build actions.
597 if a.appTestProperties.Instrumentation_for != nil {
598 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
599 if overridden {
600 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
601 }
602 }
Sasha Smundak6ad77252019-05-01 13:16:22 -0700603 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
604 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700605 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -0700606
yangbill4f41bc22019-02-13 21:45:47 +0800607 a.testConfig = tradefed.AutoGenInstrumentationTestConfig(ctx, a.testProperties.Test_config, a.testProperties.Test_config_template, a.manifestPath, a.testProperties.Test_suites)
Colin Cross8a497952019-03-05 22:25:09 -0800608 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700609}
610
611func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -0700612 a.AndroidApp.DepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -0700613 if a.appTestProperties.Instrumentation_for != nil {
614 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
615 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
616 // use instrumentationForTag instead of libTag.
617 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
618 }
Colin Crossae5caf52018-05-22 11:11:52 -0700619}
620
Colin Cross1b16b0e2019-02-12 14:41:32 -0800621// android_test compiles test sources and Android resources into an Android application package `.apk` file and
622// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -0700623func AndroidTestFactory() android.Module {
624 module := &AndroidTest{}
625
Sasha Smundak2057f822019-04-16 17:16:58 -0700626 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -0700627
628 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700629 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800630 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700631 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800632 module.Module.dexpreopter.isTest = true
Colin Crossae5caf52018-05-22 11:11:52 -0700633
634 module.AddProperties(
635 &module.Module.properties,
636 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800637 &module.Module.dexpreoptProperties,
Colin Crossae5caf52018-05-22 11:11:52 -0700638 &module.Module.protoProperties,
639 &module.aaptProperties,
640 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700641 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800642 &module.overridableAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700643 &module.usesLibrary.usesLibraryProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700644 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -0700645
Colin Crossa4f08812018-10-02 22:03:40 -0700646 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
647 android.InitDefaultableModule(module)
Colin Crossae5caf52018-05-22 11:11:52 -0700648 return module
649}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700650
Colin Cross252fc6f2018-10-04 15:22:03 -0700651type appTestHelperAppProperties struct {
652 // list of compatibility suites (for example "cts", "vts") that the module should be
653 // installed into.
654 Test_suites []string `android:"arch_variant"`
655}
656
657type AndroidTestHelperApp struct {
658 AndroidApp
659
660 appTestHelperAppProperties appTestHelperAppProperties
661}
662
Colin Cross1b16b0e2019-02-12 14:41:32 -0800663// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
664// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
665// test.
Colin Cross252fc6f2018-10-04 15:22:03 -0700666func AndroidTestHelperAppFactory() android.Module {
667 module := &AndroidTestHelperApp{}
668
Sasha Smundak2057f822019-04-16 17:16:58 -0700669 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700670
671 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800672 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700673 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800674 module.Module.dexpreopter.isTest = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700675
676 module.AddProperties(
677 &module.Module.properties,
678 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800679 &module.Module.dexpreoptProperties,
Colin Cross252fc6f2018-10-04 15:22:03 -0700680 &module.Module.protoProperties,
681 &module.aaptProperties,
682 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800683 &module.appTestHelperAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700684 &module.overridableAppProperties,
685 &module.usesLibrary.usesLibraryProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -0700686
687 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
688 android.InitDefaultableModule(module)
689 return module
690}
691
Colin Crossbd01e2a2018-10-04 15:21:03 -0700692type AndroidAppCertificate struct {
693 android.ModuleBase
694 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900695 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -0700696}
697
698type AndroidAppCertificateProperties struct {
699 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
700 Certificate *string
701}
702
Colin Cross1b16b0e2019-02-12 14:41:32 -0800703// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
704// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -0700705func AndroidAppCertificateFactory() android.Module {
706 module := &AndroidAppCertificate{}
707 module.AddProperties(&module.properties)
708 android.InitAndroidModule(module)
709 return module
710}
711
Colin Crossbd01e2a2018-10-04 15:21:03 -0700712func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
713 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900714 c.Certificate = Certificate{
Colin Crossbd01e2a2018-10-04 15:21:03 -0700715 android.PathForModuleSrc(ctx, cert+".x509.pem"),
716 android.PathForModuleSrc(ctx, cert+".pk8"),
717 }
718}
Jaewoong Jung525443a2019-02-28 15:35:54 -0800719
720type OverrideAndroidApp struct {
721 android.ModuleBase
722 android.OverrideModuleBase
723}
724
725func (i *OverrideAndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
726 // All the overrides happen in the base module.
727 // TODO(jungjw): Check the base module type.
728}
729
730// override_android_app is used to create an android_app module based on another android_app by overriding
731// some of its properties.
732func OverrideAndroidAppModuleFactory() android.Module {
733 m := &OverrideAndroidApp{}
734 m.AddProperties(&overridableAppProperties{})
735
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700736 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800737 android.InitOverrideModule(m)
738 return m
739}
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700740
741type AndroidAppImport struct {
742 android.ModuleBase
743 android.DefaultableModuleBase
744 prebuilt android.Prebuilt
745
746 properties AndroidAppImportProperties
747
748 outputFile android.Path
749 certificate *Certificate
750
751 dexpreopter
Colin Cross50ddcc42019-05-16 12:28:22 -0700752
753 usesLibrary usesLibrary
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700754}
755
756type AndroidAppImportProperties struct {
757 // A prebuilt apk to import
758 Apk string
759
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700760 // Per-DPI settings. This property makes it possible to specify a different source apk path for
761 // each DPI.
762 //
763 // Example:
764 //
765 // android_app_import {
766 // name: "example_import",
767 // apk: "prebuilts/example.apk",
768 // dpi_variants: {
769 // mdpi: {
770 // apk: "prebuilts/example_mdpi.apk",
771 // },
772 // xhdpi: {
773 // apk: "prebuilts/example_xhdpi.apk",
774 // },
775 // },
776 // certificate: "PRESIGNED",
777 // }
778 Dpi_variants interface{}
779
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700780 // The name of a certificate in the default certificate directory, blank to use the default
781 // product certificate, or an android_app_certificate module name in the form ":module".
782 Certificate *string
783
784 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
785 // be set for presigned modules.
786 Presigned *bool
787
788 // Specifies that this app should be installed to the priv-app directory,
789 // where the system will grant it additional privileges not available to
790 // normal apps.
791 Privileged *bool
792
793 // Names of modules to be overridden. Listed modules can only be other binaries
794 // (in Make or Soong).
795 // This does not completely prevent installation of the overridden binaries, but if both
796 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
797 // from PRODUCT_PACKAGES.
798 Overrides []string
799}
800
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700801func getApkPathForDpi(dpiVariantsValue reflect.Value, dpi string) string {
802 dpiField := dpiVariantsValue.FieldByName(proptools.FieldNameForProperty(dpi))
803 if !dpiField.IsValid() {
804 return ""
805 }
806 apkValue := dpiField.FieldByName("Apk").Elem()
807 if apkValue.IsValid() {
808 return apkValue.String()
809 }
810 return ""
811}
812
813// Chooses a source APK path to use based on the module's per-DPI settings and the product config.
814func (a *AndroidAppImport) getSrcApkPath(ctx android.ModuleContext) string {
815 config := ctx.Config()
816 dpiVariantsValue := reflect.ValueOf(a.properties.Dpi_variants).Elem()
817 if !dpiVariantsValue.IsValid() {
818 return a.properties.Apk
819 }
820 // Match PRODUCT_AAPT_PREF_CONFIG first and then PRODUCT_AAPT_PREBUILT_DPI.
821 if config.ProductAAPTPreferredConfig() != "" {
822 if apk := getApkPathForDpi(dpiVariantsValue, config.ProductAAPTPreferredConfig()); apk != "" {
823 return apk
824 }
825 }
826 for _, dpi := range config.ProductAAPTPrebuiltDPI() {
827 if apk := getApkPathForDpi(dpiVariantsValue, dpi); apk != "" {
828 return apk
829 }
830 }
831
832 // No match. Use the generic one.
833 return a.properties.Apk
834}
835
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700836func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
837 cert := android.SrcIsModule(String(a.properties.Certificate))
838 if cert != "" {
839 ctx.AddDependency(ctx.Module(), certificateTag, cert)
840 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700841
Paul Duffin250e6192019-06-07 10:44:37 +0100842 a.usesLibrary.deps(ctx, true)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700843}
844
845func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
846 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
847 rule := android.NewRuleBuilder()
848 rule.Command().
849 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
850 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
851 FlagWithInput("-i ", inputPath).
852 FlagWithOutput("-o ", outputPath).
853 FlagWithArg("-0 ", "'lib/**/*.so'").
854 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
855 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
856}
857
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700858// Returns whether this module should have the dex file stored uncompressed in the APK.
859func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
860 if ctx.Config().UnbundledBuild() {
861 return false
862 }
863
864 // Uncompress dex in APKs of privileged apps
865 if ctx.Config().UncompressPrivAppDex() && Bool(a.properties.Privileged) {
866 return true
867 }
868
869 return shouldUncompressDex(ctx, &a.dexpreopter)
870}
871
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700872func (a *AndroidAppImport) uncompressDex(
873 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
874 rule := android.NewRuleBuilder()
875 rule.Command().
876 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
877 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
878 FlagWithInput("-i ", inputPath).
879 FlagWithOutput("-o ", outputPath).
880 FlagWithArg("-0 ", "'classes*.dex'").
881 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
882 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
883}
884
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700885func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
886 if String(a.properties.Certificate) == "" && !Bool(a.properties.Presigned) {
887 ctx.PropertyErrorf("certificate", "No certificate specified for prebuilt")
888 }
889 if String(a.properties.Certificate) != "" && Bool(a.properties.Presigned) {
890 ctx.PropertyErrorf("certificate", "Certificate can't be specified for presigned modules")
891 }
892
893 _, certificates := collectAppDeps(ctx)
894
895 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700896 // TODO: LOCAL_PACKAGE_SPLITS
897
Colin Cross50ddcc42019-05-16 12:28:22 -0700898 var srcApk android.Path
899 srcApk = android.PathForModuleSrc(ctx, a.getSrcApkPath(ctx))
900
901 if a.usesLibrary.enforceUsesLibraries() {
902 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
903 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700904
905 // TODO: Install or embed JNI libraries
906
907 // Uncompress JNI libraries in the apk
908 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
909 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
910
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700911 installDir := android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
912 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
913 a.dexpreopter.isInstallable = true
914 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700915 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700916
917 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
918 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
919 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
920 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
921
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700922 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700923 if a.dexpreopter.uncompressedDex {
924 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
925 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
926 dexOutput = dexUncompressed
927 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700928
929 // Sign or align the package
930 // TODO: Handle EXTERNAL
931 if !Bool(a.properties.Presigned) {
932 certificates = processMainCert(a.ModuleBase, *a.properties.Certificate, certificates, ctx)
933 if len(certificates) != 1 {
934 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
935 }
936 a.certificate = &certificates[0]
937 signed := android.PathForModuleOut(ctx, "signed", ctx.ModuleName()+".apk")
938 SignAppPackage(ctx, signed, dexOutput, certificates)
939 a.outputFile = signed
940 } else {
941 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", ctx.ModuleName()+".apk")
942 TransformZipAlign(ctx, alignedApk, dexOutput)
943 a.outputFile = alignedApk
944 }
945
946 // TODO: Optionally compress the output apk.
947
948 ctx.InstallFile(installDir, a.BaseModuleName()+".apk", a.outputFile)
949
950 // TODO: androidmk converter jni libs
951}
952
953func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
954 return &a.prebuilt
955}
956
957func (a *AndroidAppImport) Name() string {
958 return a.prebuilt.Name(a.ModuleBase.Name())
959}
960
961// android_app_import imports a prebuilt apk with additional processing specified in the module.
962func AndroidAppImportFactory() android.Module {
963 module := &AndroidAppImport{}
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700964 module.properties.Dpi_variants = reflect.New(dpiVariantsStruct).Interface()
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700965 module.AddProperties(&module.properties)
966 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -0700967 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700968
969 InitJavaModule(module, android.DeviceSupported)
970 android.InitSingleSourcePrebuiltModule(module, &module.properties.Apk)
971
972 return module
973}
Colin Cross50ddcc42019-05-16 12:28:22 -0700974
975type UsesLibraryProperties struct {
976 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
977 Uses_libs []string
978
979 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
980 // required=false.
981 Optional_uses_libs []string
982
983 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
984 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
985 Enforce_uses_libs *bool
986}
987
988// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
989// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
990// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
991// with knowledge of their shared libraries.
992type usesLibrary struct {
993 usesLibraryProperties UsesLibraryProperties
994}
995
Paul Duffin250e6192019-06-07 10:44:37 +0100996func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Colin Cross3245b2c2019-06-07 13:18:09 -0700997 if !ctx.Config().UnbundledBuild() {
998 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
999 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
Paul Duffin250e6192019-06-07 10:44:37 +01001000 // Only add these extra dependencies if the module depends on framework libs. This avoids
1001 // creating a cyclic dependency:
1002 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1003 if hasFrameworkLibs {
Colin Cross3245b2c2019-06-07 13:18:09 -07001004 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
1005 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
1006 // library to dexpreopt.
1007 ctx.AddVariationDependencies(nil, usesLibTag,
1008 "org.apache.http.legacy",
1009 "android.hidl.base-V1.0-java",
1010 "android.hidl.manager-V1.0-java")
1011 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001012 }
1013}
1014
1015// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1016// build.
1017func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1018 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1019 return optionalUsesLibs
1020}
1021
1022// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
1023func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
1024 usesLibPaths := make(map[string]android.Path)
1025
1026 if !ctx.Config().UnbundledBuild() {
1027 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
1028 if lib, ok := m.(Dependency); ok {
1029 if dexJar := lib.DexJar(); dexJar != nil {
1030 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
1031 } else {
1032 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
1033 ctx.OtherModuleName(m))
1034 }
1035 } else if ctx.Config().AllowMissingDependencies() {
1036 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
1037 } else {
1038 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
1039 ctx.OtherModuleName(m))
1040 }
1041 })
1042 }
1043
1044 return usesLibPaths
1045}
1046
1047// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1048// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1049// unconditionally in the future.
1050func (u *usesLibrary) enforceUsesLibraries() bool {
1051 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1052 len(u.usesLibraryProperties.Optional_uses_libs) > 0
1053 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
1054}
1055
1056// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
1057// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
1058func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1059 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
1060
1061 rule := android.NewRuleBuilder()
1062 cmd := rule.Command().Tool(ctx.Config().HostToolPath(ctx, "manifest_check")).
1063 Flag("--enforce-uses-libraries").
1064 Input(manifest).
1065 FlagWithOutput("-o ", outputFile)
1066
1067 for _, lib := range u.usesLibraryProperties.Uses_libs {
1068 cmd.FlagWithArg("--uses-library ", lib)
1069 }
1070
1071 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1072 cmd.FlagWithArg("--optional-uses-library ", lib)
1073 }
1074
1075 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1076
1077 return outputFile
1078}
1079
1080// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1081// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1082func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1083 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1084
1085 rule := android.NewRuleBuilder()
1086 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1087 rule.Command().
1088 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1089 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1090 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1091 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1092 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1093
1094 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1095
1096 return outputFile
1097}