blob: ce4eb32eefe3b7b4330294484aabb038b834ddfe [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 Jung3e18b192019-06-11 12:25:34 -070033var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070034
Colin Cross3bc7ffa2017-11-22 16:19:37 -080035func init() {
Colin Cross5ab4e6d2017-11-22 16:20:45 -080036 android.RegisterModuleType("android_app", AndroidAppFactory)
Colin Crossae5caf52018-05-22 11:11:52 -070037 android.RegisterModuleType("android_test", AndroidTestFactory)
Colin Cross252fc6f2018-10-04 15:22:03 -070038 android.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
Colin Crossbd01e2a2018-10-04 15:21:03 -070039 android.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
Jaewoong Jung525443a2019-02-28 15:35:54 -080040 android.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
Jaewoong Jungccbb3932019-04-15 09:48:31 -070041 android.RegisterModuleType("android_app_import", AndroidAppImportFactory)
Colin Cross3bc7ffa2017-11-22 16:19:37 -080042}
43
Colin Cross30e076a2015-04-13 13:58:27 -070044// AndroidManifest.xml merging
45// package splits
46
Colin Crossfabb6082018-02-20 17:22:23 -080047type appProperties struct {
Colin Crossbd01e2a2018-10-04 15:21:03 -070048 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
Colin Cross7d5136f2015-05-11 13:39:40 -070049 Additional_certificates []string
50
51 // If set, create package-export.apk, which other packages can
52 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
Nan Zhangea568a42017-11-08 21:20:04 -080053 Export_package_resources *bool
Colin Cross7d5136f2015-05-11 13:39:40 -070054
Colin Cross16056062017-12-13 22:46:28 -080055 // Specifies that this app should be installed to the priv-app directory,
56 // where the system will grant it additional privileges not available to
57 // normal apps.
58 Privileged *bool
Colin Crossa97c5d32018-03-28 14:58:31 -070059
60 // list of resource labels to generate individual resource packages
61 Package_splits []string
Jason Monkd4122be2018-08-10 09:33:36 -040062
63 // Names of modules to be overridden. Listed modules can only be other binaries
64 // (in Make or Soong).
65 // This does not completely prevent installation of the overridden binaries, but if both
66 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
67 // from PRODUCT_PACKAGES.
68 Overrides []string
Colin Crossa4f08812018-10-02 22:03:40 -070069
70 // list of native libraries that will be provided in or alongside the resulting jar
71 Jni_libs []string `android:"arch_variant"`
72
Jaewoong Jungbc625cd2019-05-06 15:48:44 -070073 // STL library to use for JNI libraries.
74 Stl *string `android:"arch_variant"`
75
Colin Crosse4246ab2019-02-05 21:55:21 -080076 // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
77 // flag so that they are used from inside the APK at runtime. Defaults to true for android_test modules unless
78 // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to false for other
79 // module types where the native libraries are generally preinstalled outside the APK.
80 Use_embedded_native_libs *bool
Colin Cross46abdad2019-02-07 13:07:08 -080081
82 // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
83 // they are used from inside the APK at runtime.
84 Use_embedded_dex *bool
Colin Cross47fa9d32019-03-26 10:51:39 -070085
86 // Forces native libraries to always be packaged into the APK,
87 // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
88 // True for android_test* modules.
89 AlwaysPackageNativeLibs bool `blueprint:"mutated"`
Jaewoong Jung5b425e22019-06-17 17:40:56 -070090
91 // If set, find and merge all NOTICE files that this module and its dependencies have and store
92 // it in the APK as an asset.
93 Embed_notices *bool
Colin Cross7d5136f2015-05-11 13:39:40 -070094}
95
Jaewoong Jung525443a2019-02-28 15:35:54 -080096// android_app properties that can be overridden by override_android_app
97type overridableAppProperties struct {
98 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
99 // or an android_app_certificate module name in the form ":module".
100 Certificate *string
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700101
102 // the package name of this app. The package name in the manifest file is used if one was not given.
103 Package_name *string
Jaewoong Jung525443a2019-02-28 15:35:54 -0800104}
105
Colin Cross30e076a2015-04-13 13:58:27 -0700106type AndroidApp struct {
Colin Crossa97c5d32018-03-28 14:58:31 -0700107 Library
108 aapt
Jaewoong Jung525443a2019-02-28 15:35:54 -0800109 android.OverridableModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700110
Colin Cross50ddcc42019-05-16 12:28:22 -0700111 usesLibrary usesLibrary
112
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900113 certificate Certificate
Colin Cross30e076a2015-04-13 13:58:27 -0700114
Colin Crossfabb6082018-02-20 17:22:23 -0800115 appProperties appProperties
Colin Crossae5caf52018-05-22 11:11:52 -0700116
Jaewoong Jung525443a2019-02-28 15:35:54 -0800117 overridableAppProperties overridableAppProperties
118
Colin Crossa4f08812018-10-02 22:03:40 -0700119 installJniLibs []jniLib
Colin Crossf6237212018-10-29 23:14:58 -0700120
121 bundleFile android.Path
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800122
123 // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
124 installApkName string
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800125
126 additionalAaptFlags []string
Jaewoong Jung98772792019-07-01 17:15:13 -0700127
128 noticeOutputs android.NoticeOutputs
Colin Crosse1731a52017-12-14 11:22:55 -0800129}
130
Colin Cross89c31582018-04-30 15:55:11 -0700131func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
132 return nil
133}
134
Colin Cross66f78822018-05-02 12:58:28 -0700135func (a *AndroidApp) ExportedStaticPackages() android.Paths {
136 return nil
137}
138
Colin Crossa97c5d32018-03-28 14:58:31 -0700139var _ AndroidLibraryDependency = (*AndroidApp)(nil)
140
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900141type Certificate struct {
142 Pem, Key android.Path
Colin Cross30e076a2015-04-13 13:58:27 -0700143}
144
Colin Cross46c9b8b2017-06-22 16:51:17 -0700145func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
146 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700147
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700148 if String(a.appProperties.Stl) == "c++_shared" && a.sdkVersion() == "" {
149 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
150 }
151
Paul Duffin250e6192019-06-07 10:44:37 +0100152 sdkDep := decodeSdkDep(ctx, sdkContext(a))
153 if sdkDep.hasFrameworkLibs() {
154 a.aapt.deps(ctx, sdkDep)
Colin Cross30e076a2015-04-13 13:58:27 -0700155 }
Colin Crossa4f08812018-10-02 22:03:40 -0700156
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700157 embedJni := a.shouldEmbedJnis(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700158 for _, jniTarget := range ctx.MultiTargets() {
159 variation := []blueprint.Variation{
160 {Mutator: "arch", Variation: jniTarget.String()},
161 {Mutator: "link", Variation: "shared"},
162 }
163 tag := &jniDependencyTag{
164 target: jniTarget,
165 }
166 ctx.AddFarVariationDependencies(variation, tag, a.appProperties.Jni_libs...)
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700167 if String(a.appProperties.Stl) == "c++_shared" {
168 if embedJni {
Jaewoong Jung710756a2019-06-04 11:53:47 -0700169 ctx.AddFarVariationDependencies(variation, tag, "ndk_libc++_shared")
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700170 }
171 }
Colin Crossa4f08812018-10-02 22:03:40 -0700172 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700173
Paul Duffin250e6192019-06-07 10:44:37 +0100174 a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700175}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700176
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700177func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800178 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700179 if cert != "" {
180 ctx.AddDependency(ctx.Module(), certificateTag, cert)
181 }
182
183 for _, cert := range a.appProperties.Additional_certificates {
184 cert = android.SrcIsModule(cert)
185 if cert != "" {
186 ctx.AddDependency(ctx.Module(), certificateTag, cert)
187 } else {
188 ctx.PropertyErrorf("additional_certificates",
189 `must be names of android_app_certificate modules in the form ":module"`)
190 }
191 }
Colin Cross30e076a2015-04-13 13:58:27 -0700192}
193
Colin Cross46c9b8b2017-06-22 16:51:17 -0700194func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sasha Smundak6ad77252019-05-01 13:16:22 -0700195 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
Colin Cross46abdad2019-02-07 13:07:08 -0800196 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700197 a.generateAndroidBuildActions(ctx)
198}
199
Sasha Smundak6ad77252019-05-01 13:16:22 -0700200// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800201// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700202func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Colin Crosse4246ab2019-02-05 21:55:21 -0800203 minSdkVersion, err := sdkVersionToNumber(ctx, a.minSdkVersion())
204 if err != nil {
205 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.minSdkVersion(), err)
206 }
207
208 return minSdkVersion >= 23 && Bool(a.appProperties.Use_embedded_native_libs)
209}
210
Colin Cross43f08db2018-11-12 10:13:39 -0800211// Returns whether this module should have the dex file stored uncompressed in the APK.
212func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800213 if Bool(a.appProperties.Use_embedded_dex) {
214 return true
215 }
216
Colin Cross53a87f52019-06-25 13:35:30 -0700217 // Uncompress dex in APKs of privileged apps (even for unbundled builds, they may
218 // be preinstalled as prebuilts).
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700219 if ctx.Config().UncompressPrivAppDex() && Bool(a.appProperties.Privileged) {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000220 return true
221 }
222
Colin Cross53a87f52019-06-25 13:35:30 -0700223 if ctx.Config().UnbundledBuild() {
224 return false
225 }
226
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700227 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700228}
229
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700230func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
231 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
232 a.appProperties.AlwaysPackageNativeLibs
233}
234
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800235func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
David Brazdild25060a2019-02-18 18:24:16 +0000236 a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
237
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700238 // Ask manifest_fixer to add or update the application element indicating this app has no code.
239 a.aapt.hasNoCode = !a.hasCode(ctx)
240
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800241 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800242
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800243 // 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 -0700244 hasProduct := false
245 for _, f := range a.aaptProperties.Aaptflags {
246 if strings.HasPrefix(f, "--product") {
247 hasProduct = true
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800248 break
Colin Crosse78dcd32018-04-19 15:25:19 -0700249 }
250 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700251 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800252 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700253 }
254
Dan Willemsen72be5902018-10-24 20:24:57 -0700255 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
256 // Product AAPT config
257 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800258 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700259 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700260
Dan Willemsen72be5902018-10-24 20:24:57 -0700261 // Product AAPT preferred config
262 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800263 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700264 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700265 }
266
Jiyong Park7f67f482019-01-05 12:57:48 +0900267 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700268 if overridden || a.overridableAppProperties.Package_name != nil {
269 // The product override variable has a priority over the package_name property.
270 if !overridden {
271 manifestPackageName = *a.overridableAppProperties.Package_name
272 }
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800273 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
Jiyong Park7f67f482019-01-05 12:57:48 +0900274 }
275
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800276 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
277
Colin Crosse560c4a2019-03-19 16:03:11 -0700278 a.aapt.splitNames = a.appProperties.Package_splits
Colin Cross50ddcc42019-05-16 12:28:22 -0700279 a.aapt.sdkLibraries = a.exportedSdkLibs
Colin Crosse560c4a2019-03-19 16:03:11 -0700280
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800281 a.aapt.buildActions(ctx, sdkContext(a), aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700282
Colin Cross46c9b8b2017-06-22 16:51:17 -0700283 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700284 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800285}
Colin Cross30e076a2015-04-13 13:58:27 -0700286
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800287func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700288 var staticLibProguardFlagFiles android.Paths
289 ctx.VisitDirectDeps(func(m android.Module) {
290 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
291 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
292 }
293 })
294
295 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
296
297 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
298 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800299}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800300
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800301func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross43f08db2018-11-12 10:13:39 -0800302
303 var installDir string
304 if ctx.ModuleName() == "framework-res" {
305 // framework-res.apk is installed as system/framework/framework-res.apk
306 installDir = "framework"
307 } else if Bool(a.appProperties.Privileged) {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800308 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800309 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800310 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800311 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700312
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800313 a.dexpreopter.installPath = android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000314 a.dexpreopter.isInstallable = Bool(a.properties.Installable)
315 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700316
317 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
318 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
319 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
320 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
321 a.dexpreopter.manifestFile = a.mergedManifestFile
322
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000323 a.deviceProperties.UncompressDex = a.dexpreopter.uncompressedDex
Colin Cross5a0dcd52018-10-05 14:20:06 -0700324
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800325 if ctx.ModuleName() != "framework-res" {
326 a.Module.compile(ctx, a.aaptSrcJar)
327 }
Colin Cross30e076a2015-04-13 13:58:27 -0700328
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800329 return a.maybeStrippedDexJarFile
330}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800331
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800332func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700333 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700334 if len(jniLibs) > 0 {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700335 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700336 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Sasha Smundak6ad77252019-05-01 13:16:22 -0700337 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Colin Crossa4f08812018-10-02 22:03:40 -0700338 } else {
339 a.installJniLibs = jniLibs
340 }
341 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800342 return jniJarFile
343}
Colin Crossa4f08812018-10-02 22:03:40 -0700344
Jaewoong Jung98772792019-07-01 17:15:13 -0700345func (a *AndroidApp) noticeBuildActions(ctx android.ModuleContext, installDir android.OutputPath) {
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700346 // Collect NOTICE files from all dependencies.
347 seenModules := make(map[android.Module]bool)
348 noticePathSet := make(map[android.Path]bool)
349
350 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
351 // Have we already seen this?
352 if _, ok := seenModules[child]; ok {
353 return false
354 }
355 seenModules[child] = true
356
357 // Skip host modules.
358 if child.Target().Os.Class == android.Host || child.Target().Os.Class == android.HostCross {
359 return false
360 }
361
362 path := child.(android.Module).NoticeFile()
363 if path.Valid() {
364 noticePathSet[path.Path()] = true
365 }
366 return true
367 })
368
369 // If the app has one, add it too.
370 if a.NoticeFile().Valid() {
371 noticePathSet[a.NoticeFile().Path()] = true
372 }
373
374 if len(noticePathSet) == 0 {
Jaewoong Jung98772792019-07-01 17:15:13 -0700375 return
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700376 }
377 var noticePaths []android.Path
378 for path := range noticePathSet {
379 noticePaths = append(noticePaths, path)
380 }
381 sort.Slice(noticePaths, func(i, j int) bool {
382 return noticePaths[i].String() < noticePaths[j].String()
383 })
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700384
Jaewoong Jung98772792019-07-01 17:15:13 -0700385 a.noticeOutputs = android.BuildNoticeOutput(ctx, installDir, a.installApkName+".apk", noticePaths)
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700386}
387
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700388// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
389// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
390func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
391 if android.SrcIsModule(certPropValue) == "" {
392 var mainCert Certificate
393 if certPropValue != "" {
394 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
395 mainCert = Certificate{
396 defaultDir.Join(ctx, certPropValue+".x509.pem"),
397 defaultDir.Join(ctx, certPropValue+".pk8"),
398 }
399 } else {
400 pem, key := ctx.Config().DefaultAppCertificate(ctx)
401 mainCert = Certificate{pem, key}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700402 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700403 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700404 }
405
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700406 if !m.Platform() {
407 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900408 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
409 if strings.HasPrefix(certPath, systemCertPath) {
410 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
411 whitelist := ctx.Config().EnforceSystemCertificateWhitelist()
412
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700413 if enforceSystemCert && !inList(m.Name(), whitelist) {
Jeongik Chac9464142019-01-07 12:07:27 +0900414 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
415 }
416 }
417 }
418
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700419 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800420}
421
422func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700423 var apkDeps android.Paths
424
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800425 // Check if the install APK name needs to be overridden.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800426 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Name())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800427
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700428 var installDir android.OutputPath
429 if ctx.ModuleName() == "framework-res" {
430 // framework-res.apk is installed as system/framework/framework-res.apk
431 installDir = android.PathForModuleInstall(ctx, "framework")
432 } else if Bool(a.appProperties.Privileged) {
433 installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
434 } else {
435 installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
436 }
437
Jaewoong Jung98772792019-07-01 17:15:13 -0700438 a.noticeBuildActions(ctx, installDir)
439 if Bool(a.appProperties.Embed_notices) || ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
440 a.aapt.noticeFile = a.noticeOutputs.HtmlGzOutput
441 }
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700442
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800443 // Process all building blocks, from AAPT to certificates.
444 a.aaptBuildActions(ctx)
445
Colin Cross50ddcc42019-05-16 12:28:22 -0700446 if a.usesLibrary.enforceUsesLibraries() {
447 manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
448 apkDeps = append(apkDeps, manifestCheckFile)
449 }
450
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800451 a.proguardBuildActions(ctx)
452
453 dexJarFile := a.dexBuildActions(ctx)
454
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700455 jniLibs, certificateDeps := collectAppDeps(ctx)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800456 jniJarFile := a.jniBuildActions(jniLibs, ctx)
457
458 if ctx.Failed() {
459 return
460 }
461
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700462 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
463 a.certificate = certificates[0]
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800464
465 // Build a final signed app package.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800466 // TODO(jungjw): Consider changing this to installApkName.
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800467 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700468 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800469 a.outputFile = packageFile
470
Colin Crosse560c4a2019-03-19 16:03:11 -0700471 for _, split := range a.aapt.splits {
472 // Sign the split APKs
473 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"_"+split.suffix+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700474 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps)
Colin Crosse560c4a2019-03-19 16:03:11 -0700475 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
476 }
477
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800478 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700479 bundleFile := android.PathForModuleOut(ctx, "base.zip")
480 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
481 a.bundleFile = bundleFile
482
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800483 // Install the app package.
Colin Crosse560c4a2019-03-19 16:03:11 -0700484 ctx.InstallFile(installDir, a.installApkName+".apk", a.outputFile)
485 for _, split := range a.aapt.splits {
486 ctx.InstallFile(installDir, a.installApkName+"_"+split.suffix+".apk", split.path)
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800487 }
Colin Cross30e076a2015-04-13 13:58:27 -0700488}
489
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700490func collectAppDeps(ctx android.ModuleContext) ([]jniLib, []Certificate) {
Colin Crossa4f08812018-10-02 22:03:40 -0700491 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900492 var certificates []Certificate
Colin Crossa4f08812018-10-02 22:03:40 -0700493
494 ctx.VisitDirectDeps(func(module android.Module) {
495 otherName := ctx.OtherModuleName(module)
496 tag := ctx.OtherModuleDependencyTag(module)
497
498 if jniTag, ok := tag.(*jniDependencyTag); ok {
499 if dep, ok := module.(*cc.Module); ok {
500 lib := dep.OutputFile()
501 if lib.Valid() {
502 jniLibs = append(jniLibs, jniLib{
503 name: ctx.OtherModuleName(module),
504 path: lib.Path(),
505 target: jniTag.target,
506 })
507 } else {
508 ctx.ModuleErrorf("dependency %q missing output file", otherName)
509 }
510 } else {
511 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700512 }
Colin Crossbd01e2a2018-10-04 15:21:03 -0700513 } else if tag == certificateTag {
514 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900515 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700516 } else {
517 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
518 }
Colin Crossa4f08812018-10-02 22:03:40 -0700519 }
520 })
521
Colin Crossbd01e2a2018-10-04 15:21:03 -0700522 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700523}
524
Colin Cross0ea8ba82019-06-06 14:33:29 -0700525func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800526 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
527 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000528 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800529 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800530 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800531}
532
Colin Cross1b16b0e2019-02-12 14:41:32 -0800533// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700534func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700535 module := &AndroidApp{}
536
Sasha Smundak2057f822019-04-16 17:16:58 -0700537 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross66dbc0b2017-12-28 12:23:20 -0800538 module.Module.deviceProperties.Optimize.Shrink = proptools.BoolPtr(true)
539
Colin Crossae5caf52018-05-22 11:11:52 -0700540 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700541 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700542
Colin Cross36242852017-06-23 15:06:31 -0700543 module.AddProperties(
Colin Cross540eff82017-06-22 17:01:52 -0700544 &module.Module.properties,
545 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800546 &module.Module.dexpreoptProperties,
Colin Crossa97c5d32018-03-28 14:58:31 -0700547 &module.Module.protoProperties,
548 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800549 &module.appProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700550 &module.overridableAppProperties,
551 &module.usesLibrary.usesLibraryProperties)
Colin Cross36242852017-06-23 15:06:31 -0700552
Colin Crossa9d8bee2018-10-02 13:59:46 -0700553 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
554 return class == android.Device && ctx.Config().DevicePrefer32BitApps()
555 })
556
Colin Crossa4f08812018-10-02 22:03:40 -0700557 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
558 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800559 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossa4f08812018-10-02 22:03:40 -0700560
Colin Cross36242852017-06-23 15:06:31 -0700561 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700562}
Colin Crossae5caf52018-05-22 11:11:52 -0700563
564type appTestProperties struct {
565 Instrumentation_for *string
566}
567
568type AndroidTest struct {
569 AndroidApp
570
571 appTestProperties appTestProperties
572
573 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700574
575 testConfig android.Path
Colin Crossd96ca352018-08-10 16:06:24 -0700576 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -0700577}
578
579func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800580 // Check if the instrumentation target package is overridden before generating build actions.
581 if a.appTestProperties.Instrumentation_for != nil {
582 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
583 if overridden {
584 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
585 }
586 }
Sasha Smundak6ad77252019-05-01 13:16:22 -0700587 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
588 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700589 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -0700590
yangbill4f41bc22019-02-13 21:45:47 +0800591 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 -0800592 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700593}
594
595func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -0700596 a.AndroidApp.DepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -0700597 if a.appTestProperties.Instrumentation_for != nil {
598 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
599 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
600 // use instrumentationForTag instead of libTag.
601 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
602 }
Colin Crossae5caf52018-05-22 11:11:52 -0700603}
604
Colin Cross1b16b0e2019-02-12 14:41:32 -0800605// android_test compiles test sources and Android resources into an Android application package `.apk` file and
606// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -0700607func AndroidTestFactory() android.Module {
608 module := &AndroidTest{}
609
Sasha Smundak2057f822019-04-16 17:16:58 -0700610 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -0700611
612 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700613 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800614 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700615 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800616 module.Module.dexpreopter.isTest = true
Colin Crossae5caf52018-05-22 11:11:52 -0700617
618 module.AddProperties(
619 &module.Module.properties,
620 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800621 &module.Module.dexpreoptProperties,
Colin Crossae5caf52018-05-22 11:11:52 -0700622 &module.Module.protoProperties,
623 &module.aaptProperties,
624 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700625 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800626 &module.overridableAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700627 &module.usesLibrary.usesLibraryProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700628 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -0700629
Colin Crossa4f08812018-10-02 22:03:40 -0700630 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
631 android.InitDefaultableModule(module)
Colin Crossae5caf52018-05-22 11:11:52 -0700632 return module
633}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700634
Colin Cross252fc6f2018-10-04 15:22:03 -0700635type appTestHelperAppProperties struct {
636 // list of compatibility suites (for example "cts", "vts") that the module should be
637 // installed into.
638 Test_suites []string `android:"arch_variant"`
639}
640
641type AndroidTestHelperApp struct {
642 AndroidApp
643
644 appTestHelperAppProperties appTestHelperAppProperties
645}
646
Colin Cross1b16b0e2019-02-12 14:41:32 -0800647// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
648// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
649// test.
Colin Cross252fc6f2018-10-04 15:22:03 -0700650func AndroidTestHelperAppFactory() android.Module {
651 module := &AndroidTestHelperApp{}
652
Sasha Smundak2057f822019-04-16 17:16:58 -0700653 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700654
655 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800656 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700657 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800658 module.Module.dexpreopter.isTest = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700659
660 module.AddProperties(
661 &module.Module.properties,
662 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800663 &module.Module.dexpreoptProperties,
Colin Cross252fc6f2018-10-04 15:22:03 -0700664 &module.Module.protoProperties,
665 &module.aaptProperties,
666 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800667 &module.appTestHelperAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700668 &module.overridableAppProperties,
669 &module.usesLibrary.usesLibraryProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -0700670
671 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
672 android.InitDefaultableModule(module)
673 return module
674}
675
Colin Crossbd01e2a2018-10-04 15:21:03 -0700676type AndroidAppCertificate struct {
677 android.ModuleBase
678 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900679 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -0700680}
681
682type AndroidAppCertificateProperties struct {
683 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
684 Certificate *string
685}
686
Colin Cross1b16b0e2019-02-12 14:41:32 -0800687// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
688// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -0700689func AndroidAppCertificateFactory() android.Module {
690 module := &AndroidAppCertificate{}
691 module.AddProperties(&module.properties)
692 android.InitAndroidModule(module)
693 return module
694}
695
Colin Crossbd01e2a2018-10-04 15:21:03 -0700696func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
697 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900698 c.Certificate = Certificate{
Colin Crossbd01e2a2018-10-04 15:21:03 -0700699 android.PathForModuleSrc(ctx, cert+".x509.pem"),
700 android.PathForModuleSrc(ctx, cert+".pk8"),
701 }
702}
Jaewoong Jung525443a2019-02-28 15:35:54 -0800703
704type OverrideAndroidApp struct {
705 android.ModuleBase
706 android.OverrideModuleBase
707}
708
709func (i *OverrideAndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
710 // All the overrides happen in the base module.
711 // TODO(jungjw): Check the base module type.
712}
713
714// override_android_app is used to create an android_app module based on another android_app by overriding
715// some of its properties.
716func OverrideAndroidAppModuleFactory() android.Module {
717 m := &OverrideAndroidApp{}
718 m.AddProperties(&overridableAppProperties{})
719
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700720 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800721 android.InitOverrideModule(m)
722 return m
723}
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700724
725type AndroidAppImport struct {
726 android.ModuleBase
727 android.DefaultableModuleBase
728 prebuilt android.Prebuilt
729
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700730 properties AndroidAppImportProperties
731 dpiVariants interface{}
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700732
733 outputFile android.Path
734 certificate *Certificate
735
736 dexpreopter
Colin Cross50ddcc42019-05-16 12:28:22 -0700737
738 usesLibrary usesLibrary
Jaewoong Jung8aae22e2019-07-17 10:21:49 -0700739
740 installPath android.OutputPath
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700741}
742
743type AndroidAppImportProperties struct {
744 // A prebuilt apk to import
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700745 Apk *string
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700746
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700747 // The name of a certificate in the default certificate directory, blank to use the default
748 // product certificate, or an android_app_certificate module name in the form ":module".
749 Certificate *string
750
751 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
752 // be set for presigned modules.
753 Presigned *bool
754
755 // Specifies that this app should be installed to the priv-app directory,
756 // where the system will grant it additional privileges not available to
757 // normal apps.
758 Privileged *bool
759
760 // Names of modules to be overridden. Listed modules can only be other binaries
761 // (in Make or Soong).
762 // This does not completely prevent installation of the overridden binaries, but if both
763 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
764 // from PRODUCT_PACKAGES.
765 Overrides []string
Jaewoong Jung8aae22e2019-07-17 10:21:49 -0700766
767 // Optional name for the installed app. If unspecified, it is derived from the module name.
768 Filename *string
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700769}
770
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700771// Chooses a source APK path to use based on the module and product specs.
772func (a *AndroidAppImport) updateSrcApkPath(ctx android.LoadHookContext) {
773 config := ctx.Config()
774
775 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
776 // Try DPI variant matches in the reverse-priority order so that the highest priority match
777 // overwrites everything else.
778 // TODO(jungjw): Can we optimize this by making it priority order?
779 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
780 dpi := config.ProductAAPTPrebuiltDPI()[i]
781 if inList(dpi, supportedDpis) {
782 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, dpi, "dpi_variants")
783 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700784 }
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700785 if config.ProductAAPTPreferredConfig() != "" {
786 dpi := config.ProductAAPTPreferredConfig()
787 if inList(dpi, supportedDpis) {
788 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, dpi, "dpi_variants")
789 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700790 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700791}
792
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700793func MergePropertiesFromVariant(ctx android.BaseModuleContext,
794 dst interface{}, variantGroup reflect.Value, variant, variantGroupPath string) {
795 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
796 if !src.IsValid() {
797 ctx.ModuleErrorf("field %q does not exist", variantGroupPath+"."+variant)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700798 }
799
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700800 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
801 if err != nil {
802 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
803 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
804 } else {
805 panic(err)
806 }
807 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700808}
809
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700810func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
811 cert := android.SrcIsModule(String(a.properties.Certificate))
812 if cert != "" {
813 ctx.AddDependency(ctx.Module(), certificateTag, cert)
814 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700815
Paul Duffin250e6192019-06-07 10:44:37 +0100816 a.usesLibrary.deps(ctx, true)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700817}
818
819func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
820 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
821 rule := android.NewRuleBuilder()
822 rule.Command().
823 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
824 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
825 FlagWithInput("-i ", inputPath).
826 FlagWithOutput("-o ", outputPath).
827 FlagWithArg("-0 ", "'lib/**/*.so'").
828 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
829 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
830}
831
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700832// Returns whether this module should have the dex file stored uncompressed in the APK.
833func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
834 if ctx.Config().UnbundledBuild() {
835 return false
836 }
837
838 // Uncompress dex in APKs of privileged apps
839 if ctx.Config().UncompressPrivAppDex() && Bool(a.properties.Privileged) {
840 return true
841 }
842
843 return shouldUncompressDex(ctx, &a.dexpreopter)
844}
845
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700846func (a *AndroidAppImport) uncompressDex(
847 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
848 rule := android.NewRuleBuilder()
849 rule.Command().
850 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
851 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
852 FlagWithInput("-i ", inputPath).
853 FlagWithOutput("-o ", outputPath).
854 FlagWithArg("-0 ", "'classes*.dex'").
855 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
856 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
857}
858
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700859func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
860 if String(a.properties.Certificate) == "" && !Bool(a.properties.Presigned) {
861 ctx.PropertyErrorf("certificate", "No certificate specified for prebuilt")
862 }
863 if String(a.properties.Certificate) != "" && Bool(a.properties.Presigned) {
864 ctx.PropertyErrorf("certificate", "Certificate can't be specified for presigned modules")
865 }
866
867 _, certificates := collectAppDeps(ctx)
868
869 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700870 // TODO: LOCAL_PACKAGE_SPLITS
871
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700872 srcApk := a.prebuilt.SingleSourcePath(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700873
874 if a.usesLibrary.enforceUsesLibraries() {
875 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
876 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700877
878 // TODO: Install or embed JNI libraries
879
880 // Uncompress JNI libraries in the apk
881 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
882 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
883
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700884 installDir := android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
885 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
886 a.dexpreopter.isInstallable = true
887 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700888 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700889
890 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
891 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
892 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
893 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
894
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700895 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700896 if a.dexpreopter.uncompressedDex {
897 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
898 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
899 dexOutput = dexUncompressed
900 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700901
902 // Sign or align the package
903 // TODO: Handle EXTERNAL
904 if !Bool(a.properties.Presigned) {
905 certificates = processMainCert(a.ModuleBase, *a.properties.Certificate, certificates, ctx)
906 if len(certificates) != 1 {
907 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
908 }
909 a.certificate = &certificates[0]
910 signed := android.PathForModuleOut(ctx, "signed", ctx.ModuleName()+".apk")
911 SignAppPackage(ctx, signed, dexOutput, certificates)
912 a.outputFile = signed
913 } else {
914 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", ctx.ModuleName()+".apk")
915 TransformZipAlign(ctx, alignedApk, dexOutput)
916 a.outputFile = alignedApk
917 }
918
919 // TODO: Optionally compress the output apk.
920
Jaewoong Jung8aae22e2019-07-17 10:21:49 -0700921 a.installPath = ctx.InstallFile(installDir,
922 proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk"), a.outputFile)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700923
924 // TODO: androidmk converter jni libs
925}
926
927func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
928 return &a.prebuilt
929}
930
931func (a *AndroidAppImport) Name() string {
932 return a.prebuilt.Name(a.ModuleBase.Name())
933}
934
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700935// Populates dpi_variants property and its fields at creation time.
936func (a *AndroidAppImport) addDpiVariants() {
937 // TODO(jungjw): Do we want to do some filtering here?
938 props := reflect.ValueOf(&a.properties).Type()
939
940 dpiFields := make([]reflect.StructField, len(supportedDpis))
941 for i, dpi := range supportedDpis {
942 dpiFields[i] = reflect.StructField{
943 Name: proptools.FieldNameForProperty(dpi),
944 Type: props,
945 }
946 }
947 dpiStruct := reflect.StructOf(dpiFields)
948 a.dpiVariants = reflect.New(reflect.StructOf([]reflect.StructField{
949 {
950 Name: "Dpi_variants",
951 Type: dpiStruct,
952 },
953 })).Interface()
954 a.AddProperties(a.dpiVariants)
955}
956
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700957// android_app_import imports a prebuilt apk with additional processing specified in the module.
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700958// DPI-specific apk source files can be specified using dpi_variants. Example:
959//
960// android_app_import {
961// name: "example_import",
962// apk: "prebuilts/example.apk",
963// dpi_variants: {
964// mdpi: {
965// apk: "prebuilts/example_mdpi.apk",
966// },
967// xhdpi: {
968// apk: "prebuilts/example_xhdpi.apk",
969// },
970// },
971// certificate: "PRESIGNED",
972// }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700973func AndroidAppImportFactory() android.Module {
974 module := &AndroidAppImport{}
975 module.AddProperties(&module.properties)
976 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -0700977 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700978 module.addDpiVariants()
979 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
980 module.updateSrcApkPath(ctx)
981 })
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700982
983 InitJavaModule(module, android.DeviceSupported)
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700984 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700985
986 return module
987}
Colin Cross50ddcc42019-05-16 12:28:22 -0700988
989type UsesLibraryProperties struct {
990 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
991 Uses_libs []string
992
993 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
994 // required=false.
995 Optional_uses_libs []string
996
997 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
998 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
999 Enforce_uses_libs *bool
1000}
1001
1002// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
1003// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
1004// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
1005// with knowledge of their shared libraries.
1006type usesLibrary struct {
1007 usesLibraryProperties UsesLibraryProperties
1008}
1009
Paul Duffin250e6192019-06-07 10:44:37 +01001010func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Colin Cross3245b2c2019-06-07 13:18:09 -07001011 if !ctx.Config().UnbundledBuild() {
1012 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
1013 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
Paul Duffin250e6192019-06-07 10:44:37 +01001014 // Only add these extra dependencies if the module depends on framework libs. This avoids
1015 // creating a cyclic dependency:
1016 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1017 if hasFrameworkLibs {
Colin Cross3245b2c2019-06-07 13:18:09 -07001018 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
1019 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
1020 // library to dexpreopt.
1021 ctx.AddVariationDependencies(nil, usesLibTag,
1022 "org.apache.http.legacy",
1023 "android.hidl.base-V1.0-java",
1024 "android.hidl.manager-V1.0-java")
1025 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001026 }
1027}
1028
1029// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1030// build.
1031func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1032 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1033 return optionalUsesLibs
1034}
1035
1036// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
1037func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
1038 usesLibPaths := make(map[string]android.Path)
1039
1040 if !ctx.Config().UnbundledBuild() {
1041 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
1042 if lib, ok := m.(Dependency); ok {
1043 if dexJar := lib.DexJar(); dexJar != nil {
1044 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
1045 } else {
1046 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
1047 ctx.OtherModuleName(m))
1048 }
1049 } else if ctx.Config().AllowMissingDependencies() {
1050 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
1051 } else {
1052 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
1053 ctx.OtherModuleName(m))
1054 }
1055 })
1056 }
1057
1058 return usesLibPaths
1059}
1060
1061// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1062// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1063// unconditionally in the future.
1064func (u *usesLibrary) enforceUsesLibraries() bool {
1065 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1066 len(u.usesLibraryProperties.Optional_uses_libs) > 0
1067 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
1068}
1069
1070// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
1071// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
1072func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1073 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
1074
1075 rule := android.NewRuleBuilder()
1076 cmd := rule.Command().Tool(ctx.Config().HostToolPath(ctx, "manifest_check")).
1077 Flag("--enforce-uses-libraries").
1078 Input(manifest).
1079 FlagWithOutput("-o ", outputFile)
1080
1081 for _, lib := range u.usesLibraryProperties.Uses_libs {
1082 cmd.FlagWithArg("--uses-library ", lib)
1083 }
1084
1085 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1086 cmd.FlagWithArg("--optional-uses-library ", lib)
1087 }
1088
1089 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1090
1091 return outputFile
1092}
1093
1094// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1095// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1096func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1097 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1098
1099 rule := android.NewRuleBuilder()
1100 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1101 rule.Command().
1102 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1103 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1104 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1105 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1106 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1107
1108 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1109
1110 return outputFile
1111}