blob: de291a348d3eab7560b4c8b8ee3ce4d57ec9f929 [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
Colin Crosse1731a52017-12-14 11:22:55 -0800127}
128
Colin Cross89c31582018-04-30 15:55:11 -0700129func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
130 return nil
131}
132
Colin Cross66f78822018-05-02 12:58:28 -0700133func (a *AndroidApp) ExportedStaticPackages() android.Paths {
134 return nil
135}
136
Colin Crossa97c5d32018-03-28 14:58:31 -0700137var _ AndroidLibraryDependency = (*AndroidApp)(nil)
138
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900139type Certificate struct {
140 Pem, Key android.Path
Colin Cross30e076a2015-04-13 13:58:27 -0700141}
142
Colin Cross46c9b8b2017-06-22 16:51:17 -0700143func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
144 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700145
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700146 if String(a.appProperties.Stl) == "c++_shared" && a.sdkVersion() == "" {
147 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
148 }
149
Paul Duffin250e6192019-06-07 10:44:37 +0100150 sdkDep := decodeSdkDep(ctx, sdkContext(a))
151 if sdkDep.hasFrameworkLibs() {
152 a.aapt.deps(ctx, sdkDep)
Colin Cross30e076a2015-04-13 13:58:27 -0700153 }
Colin Crossa4f08812018-10-02 22:03:40 -0700154
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700155 embedJni := a.shouldEmbedJnis(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700156 for _, jniTarget := range ctx.MultiTargets() {
157 variation := []blueprint.Variation{
158 {Mutator: "arch", Variation: jniTarget.String()},
159 {Mutator: "link", Variation: "shared"},
160 }
161 tag := &jniDependencyTag{
162 target: jniTarget,
163 }
164 ctx.AddFarVariationDependencies(variation, tag, a.appProperties.Jni_libs...)
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700165 if String(a.appProperties.Stl) == "c++_shared" {
166 if embedJni {
Jaewoong Jung710756a2019-06-04 11:53:47 -0700167 ctx.AddFarVariationDependencies(variation, tag, "ndk_libc++_shared")
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700168 }
169 }
Colin Crossa4f08812018-10-02 22:03:40 -0700170 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700171
Paul Duffin250e6192019-06-07 10:44:37 +0100172 a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700173}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700174
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700175func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800176 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700177 if cert != "" {
178 ctx.AddDependency(ctx.Module(), certificateTag, cert)
179 }
180
181 for _, cert := range a.appProperties.Additional_certificates {
182 cert = android.SrcIsModule(cert)
183 if cert != "" {
184 ctx.AddDependency(ctx.Module(), certificateTag, cert)
185 } else {
186 ctx.PropertyErrorf("additional_certificates",
187 `must be names of android_app_certificate modules in the form ":module"`)
188 }
189 }
Colin Cross30e076a2015-04-13 13:58:27 -0700190}
191
Colin Cross46c9b8b2017-06-22 16:51:17 -0700192func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sasha Smundak6ad77252019-05-01 13:16:22 -0700193 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
Colin Cross46abdad2019-02-07 13:07:08 -0800194 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700195 a.generateAndroidBuildActions(ctx)
196}
197
Sasha Smundak6ad77252019-05-01 13:16:22 -0700198// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800199// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700200func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Colin Crosse4246ab2019-02-05 21:55:21 -0800201 minSdkVersion, err := sdkVersionToNumber(ctx, a.minSdkVersion())
202 if err != nil {
203 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.minSdkVersion(), err)
204 }
205
206 return minSdkVersion >= 23 && Bool(a.appProperties.Use_embedded_native_libs)
207}
208
Colin Cross43f08db2018-11-12 10:13:39 -0800209// Returns whether this module should have the dex file stored uncompressed in the APK.
210func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800211 if Bool(a.appProperties.Use_embedded_dex) {
212 return true
213 }
214
Colin Cross53a87f52019-06-25 13:35:30 -0700215 // Uncompress dex in APKs of privileged apps (even for unbundled builds, they may
216 // be preinstalled as prebuilts).
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700217 if ctx.Config().UncompressPrivAppDex() && Bool(a.appProperties.Privileged) {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000218 return true
219 }
220
Colin Cross53a87f52019-06-25 13:35:30 -0700221 if ctx.Config().UnbundledBuild() {
222 return false
223 }
224
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700225 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700226}
227
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700228func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
229 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
230 a.appProperties.AlwaysPackageNativeLibs
231}
232
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800233func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
David Brazdild25060a2019-02-18 18:24:16 +0000234 a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
235
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700236 // Ask manifest_fixer to add or update the application element indicating this app has no code.
237 a.aapt.hasNoCode = !a.hasCode(ctx)
238
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800239 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800240
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800241 // 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 -0700242 hasProduct := false
243 for _, f := range a.aaptProperties.Aaptflags {
244 if strings.HasPrefix(f, "--product") {
245 hasProduct = true
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800246 break
Colin Crosse78dcd32018-04-19 15:25:19 -0700247 }
248 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700249 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800250 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700251 }
252
Dan Willemsen72be5902018-10-24 20:24:57 -0700253 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
254 // Product AAPT config
255 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800256 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700257 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700258
Dan Willemsen72be5902018-10-24 20:24:57 -0700259 // Product AAPT preferred config
260 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800261 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700262 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700263 }
264
Jiyong Park7f67f482019-01-05 12:57:48 +0900265 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700266 if overridden || a.overridableAppProperties.Package_name != nil {
267 // The product override variable has a priority over the package_name property.
268 if !overridden {
269 manifestPackageName = *a.overridableAppProperties.Package_name
270 }
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800271 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
Jiyong Park7f67f482019-01-05 12:57:48 +0900272 }
273
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800274 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
275
Colin Crosse560c4a2019-03-19 16:03:11 -0700276 a.aapt.splitNames = a.appProperties.Package_splits
Colin Cross50ddcc42019-05-16 12:28:22 -0700277 a.aapt.sdkLibraries = a.exportedSdkLibs
Colin Crosse560c4a2019-03-19 16:03:11 -0700278
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800279 a.aapt.buildActions(ctx, sdkContext(a), aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700280
Colin Cross46c9b8b2017-06-22 16:51:17 -0700281 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800283}
Colin Cross30e076a2015-04-13 13:58:27 -0700284
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800285func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700286 var staticLibProguardFlagFiles android.Paths
287 ctx.VisitDirectDeps(func(m android.Module) {
288 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
289 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
290 }
291 })
292
293 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
294
295 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
296 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800297}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800298
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800299func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross43f08db2018-11-12 10:13:39 -0800300
301 var installDir string
302 if ctx.ModuleName() == "framework-res" {
303 // framework-res.apk is installed as system/framework/framework-res.apk
304 installDir = "framework"
305 } else if Bool(a.appProperties.Privileged) {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800306 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800307 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800308 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800309 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700310
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800311 a.dexpreopter.installPath = android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000312 a.dexpreopter.isInstallable = Bool(a.properties.Installable)
313 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700314
315 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
316 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
317 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
318 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
319 a.dexpreopter.manifestFile = a.mergedManifestFile
320
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000321 a.deviceProperties.UncompressDex = a.dexpreopter.uncompressedDex
Colin Cross5a0dcd52018-10-05 14:20:06 -0700322
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800323 if ctx.ModuleName() != "framework-res" {
324 a.Module.compile(ctx, a.aaptSrcJar)
325 }
Colin Cross30e076a2015-04-13 13:58:27 -0700326
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800327 return a.maybeStrippedDexJarFile
328}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800329
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800330func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700331 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700332 if len(jniLibs) > 0 {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700333 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700334 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Sasha Smundak6ad77252019-05-01 13:16:22 -0700335 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Colin Crossa4f08812018-10-02 22:03:40 -0700336 } else {
337 a.installJniLibs = jniLibs
338 }
339 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800340 return jniJarFile
341}
Colin Crossa4f08812018-10-02 22:03:40 -0700342
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700343func (a *AndroidApp) noticeBuildActions(ctx android.ModuleContext, installDir android.OutputPath) android.OptionalPath {
344 if !Bool(a.appProperties.Embed_notices) && !ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
345 return android.OptionalPath{}
346 }
347
348 // Collect NOTICE files from all dependencies.
349 seenModules := make(map[android.Module]bool)
350 noticePathSet := make(map[android.Path]bool)
351
352 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
353 // Have we already seen this?
354 if _, ok := seenModules[child]; ok {
355 return false
356 }
357 seenModules[child] = true
358
359 // Skip host modules.
360 if child.Target().Os.Class == android.Host || child.Target().Os.Class == android.HostCross {
361 return false
362 }
363
364 path := child.(android.Module).NoticeFile()
365 if path.Valid() {
366 noticePathSet[path.Path()] = true
367 }
368 return true
369 })
370
371 // If the app has one, add it too.
372 if a.NoticeFile().Valid() {
373 noticePathSet[a.NoticeFile().Path()] = true
374 }
375
376 if len(noticePathSet) == 0 {
377 return android.OptionalPath{}
378 }
379 var noticePaths []android.Path
380 for path := range noticePathSet {
381 noticePaths = append(noticePaths, path)
382 }
383 sort.Slice(noticePaths, func(i, j int) bool {
384 return noticePaths[i].String() < noticePaths[j].String()
385 })
386 noticeFile := android.BuildNoticeOutput(ctx, installDir, a.installApkName+".apk", noticePaths)
387
388 return android.OptionalPathForPath(noticeFile)
389}
390
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700391// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
392// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
393func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
394 if android.SrcIsModule(certPropValue) == "" {
395 var mainCert Certificate
396 if certPropValue != "" {
397 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
398 mainCert = Certificate{
399 defaultDir.Join(ctx, certPropValue+".x509.pem"),
400 defaultDir.Join(ctx, certPropValue+".pk8"),
401 }
402 } else {
403 pem, key := ctx.Config().DefaultAppCertificate(ctx)
404 mainCert = Certificate{pem, key}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700405 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700406 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700407 }
408
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700409 if !m.Platform() {
410 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900411 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
412 if strings.HasPrefix(certPath, systemCertPath) {
413 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
414 whitelist := ctx.Config().EnforceSystemCertificateWhitelist()
415
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700416 if enforceSystemCert && !inList(m.Name(), whitelist) {
Jeongik Chac9464142019-01-07 12:07:27 +0900417 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
418 }
419 }
420 }
421
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700422 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800423}
424
425func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700426 var apkDeps android.Paths
427
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800428 // Check if the install APK name needs to be overridden.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800429 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Name())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800430
Jaewoong Jung5b425e22019-06-17 17:40:56 -0700431 var installDir android.OutputPath
432 if ctx.ModuleName() == "framework-res" {
433 // framework-res.apk is installed as system/framework/framework-res.apk
434 installDir = android.PathForModuleInstall(ctx, "framework")
435 } else if Bool(a.appProperties.Privileged) {
436 installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
437 } else {
438 installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
439 }
440
441 a.aapt.noticeFile = a.noticeBuildActions(ctx, installDir)
442
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 Jungccbb3932019-04-15 09:48:31 -0700739}
740
741type AndroidAppImportProperties struct {
742 // A prebuilt apk to import
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700743 Apk *string
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700744
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700745 // The name of a certificate in the default certificate directory, blank to use the default
746 // product certificate, or an android_app_certificate module name in the form ":module".
747 Certificate *string
748
749 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
750 // be set for presigned modules.
751 Presigned *bool
752
753 // Specifies that this app should be installed to the priv-app directory,
754 // where the system will grant it additional privileges not available to
755 // normal apps.
756 Privileged *bool
757
758 // Names of modules to be overridden. Listed modules can only be other binaries
759 // (in Make or Soong).
760 // This does not completely prevent installation of the overridden binaries, but if both
761 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
762 // from PRODUCT_PACKAGES.
763 Overrides []string
764}
765
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700766// Chooses a source APK path to use based on the module and product specs.
767func (a *AndroidAppImport) updateSrcApkPath(ctx android.LoadHookContext) {
768 config := ctx.Config()
769
770 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
771 // Try DPI variant matches in the reverse-priority order so that the highest priority match
772 // overwrites everything else.
773 // TODO(jungjw): Can we optimize this by making it priority order?
774 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
775 dpi := config.ProductAAPTPrebuiltDPI()[i]
776 if inList(dpi, supportedDpis) {
777 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, dpi, "dpi_variants")
778 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700779 }
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700780 if config.ProductAAPTPreferredConfig() != "" {
781 dpi := config.ProductAAPTPreferredConfig()
782 if inList(dpi, supportedDpis) {
783 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, dpi, "dpi_variants")
784 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700785 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700786}
787
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700788func MergePropertiesFromVariant(ctx android.BaseModuleContext,
789 dst interface{}, variantGroup reflect.Value, variant, variantGroupPath string) {
790 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
791 if !src.IsValid() {
792 ctx.ModuleErrorf("field %q does not exist", variantGroupPath+"."+variant)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700793 }
794
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700795 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
796 if err != nil {
797 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
798 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
799 } else {
800 panic(err)
801 }
802 }
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700803}
804
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700805func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
806 cert := android.SrcIsModule(String(a.properties.Certificate))
807 if cert != "" {
808 ctx.AddDependency(ctx.Module(), certificateTag, cert)
809 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700810
Paul Duffin250e6192019-06-07 10:44:37 +0100811 a.usesLibrary.deps(ctx, true)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700812}
813
814func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
815 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
816 rule := android.NewRuleBuilder()
817 rule.Command().
818 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
819 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
820 FlagWithInput("-i ", inputPath).
821 FlagWithOutput("-o ", outputPath).
822 FlagWithArg("-0 ", "'lib/**/*.so'").
823 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
824 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
825}
826
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700827// Returns whether this module should have the dex file stored uncompressed in the APK.
828func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
829 if ctx.Config().UnbundledBuild() {
830 return false
831 }
832
833 // Uncompress dex in APKs of privileged apps
834 if ctx.Config().UncompressPrivAppDex() && Bool(a.properties.Privileged) {
835 return true
836 }
837
838 return shouldUncompressDex(ctx, &a.dexpreopter)
839}
840
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700841func (a *AndroidAppImport) uncompressDex(
842 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
843 rule := android.NewRuleBuilder()
844 rule.Command().
845 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
846 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
847 FlagWithInput("-i ", inputPath).
848 FlagWithOutput("-o ", outputPath).
849 FlagWithArg("-0 ", "'classes*.dex'").
850 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
851 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
852}
853
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700854func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
855 if String(a.properties.Certificate) == "" && !Bool(a.properties.Presigned) {
856 ctx.PropertyErrorf("certificate", "No certificate specified for prebuilt")
857 }
858 if String(a.properties.Certificate) != "" && Bool(a.properties.Presigned) {
859 ctx.PropertyErrorf("certificate", "Certificate can't be specified for presigned modules")
860 }
861
862 _, certificates := collectAppDeps(ctx)
863
864 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700865 // TODO: LOCAL_PACKAGE_SPLITS
866
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700867 srcApk := a.prebuilt.SingleSourcePath(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700868
869 if a.usesLibrary.enforceUsesLibraries() {
870 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
871 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700872
873 // TODO: Install or embed JNI libraries
874
875 // Uncompress JNI libraries in the apk
876 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
877 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
878
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700879 installDir := android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
880 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
881 a.dexpreopter.isInstallable = true
882 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700883 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700884
885 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
886 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
887 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
888 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
889
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700890 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700891 if a.dexpreopter.uncompressedDex {
892 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
893 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
894 dexOutput = dexUncompressed
895 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700896
897 // Sign or align the package
898 // TODO: Handle EXTERNAL
899 if !Bool(a.properties.Presigned) {
900 certificates = processMainCert(a.ModuleBase, *a.properties.Certificate, certificates, ctx)
901 if len(certificates) != 1 {
902 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
903 }
904 a.certificate = &certificates[0]
905 signed := android.PathForModuleOut(ctx, "signed", ctx.ModuleName()+".apk")
906 SignAppPackage(ctx, signed, dexOutput, certificates)
907 a.outputFile = signed
908 } else {
909 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", ctx.ModuleName()+".apk")
910 TransformZipAlign(ctx, alignedApk, dexOutput)
911 a.outputFile = alignedApk
912 }
913
914 // TODO: Optionally compress the output apk.
915
916 ctx.InstallFile(installDir, a.BaseModuleName()+".apk", a.outputFile)
917
918 // TODO: androidmk converter jni libs
919}
920
921func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
922 return &a.prebuilt
923}
924
925func (a *AndroidAppImport) Name() string {
926 return a.prebuilt.Name(a.ModuleBase.Name())
927}
928
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700929// Populates dpi_variants property and its fields at creation time.
930func (a *AndroidAppImport) addDpiVariants() {
931 // TODO(jungjw): Do we want to do some filtering here?
932 props := reflect.ValueOf(&a.properties).Type()
933
934 dpiFields := make([]reflect.StructField, len(supportedDpis))
935 for i, dpi := range supportedDpis {
936 dpiFields[i] = reflect.StructField{
937 Name: proptools.FieldNameForProperty(dpi),
938 Type: props,
939 }
940 }
941 dpiStruct := reflect.StructOf(dpiFields)
942 a.dpiVariants = reflect.New(reflect.StructOf([]reflect.StructField{
943 {
944 Name: "Dpi_variants",
945 Type: dpiStruct,
946 },
947 })).Interface()
948 a.AddProperties(a.dpiVariants)
949}
950
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700951// android_app_import imports a prebuilt apk with additional processing specified in the module.
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700952// DPI-specific apk source files can be specified using dpi_variants. Example:
953//
954// android_app_import {
955// name: "example_import",
956// apk: "prebuilts/example.apk",
957// dpi_variants: {
958// mdpi: {
959// apk: "prebuilts/example_mdpi.apk",
960// },
961// xhdpi: {
962// apk: "prebuilts/example_xhdpi.apk",
963// },
964// },
965// certificate: "PRESIGNED",
966// }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700967func AndroidAppImportFactory() android.Module {
968 module := &AndroidAppImport{}
969 module.AddProperties(&module.properties)
970 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -0700971 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700972 module.addDpiVariants()
973 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
974 module.updateSrcApkPath(ctx)
975 })
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700976
977 InitJavaModule(module, android.DeviceSupported)
Jaewoong Jung3e18b192019-06-11 12:25:34 -0700978 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700979
980 return module
981}
Colin Cross50ddcc42019-05-16 12:28:22 -0700982
983type UsesLibraryProperties struct {
984 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
985 Uses_libs []string
986
987 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
988 // required=false.
989 Optional_uses_libs []string
990
991 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
992 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
993 Enforce_uses_libs *bool
994}
995
996// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
997// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
998// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
999// with knowledge of their shared libraries.
1000type usesLibrary struct {
1001 usesLibraryProperties UsesLibraryProperties
1002}
1003
Paul Duffin250e6192019-06-07 10:44:37 +01001004func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
Colin Cross3245b2c2019-06-07 13:18:09 -07001005 if !ctx.Config().UnbundledBuild() {
1006 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
1007 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
Paul Duffin250e6192019-06-07 10:44:37 +01001008 // Only add these extra dependencies if the module depends on framework libs. This avoids
1009 // creating a cyclic dependency:
1010 // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
1011 if hasFrameworkLibs {
Colin Cross3245b2c2019-06-07 13:18:09 -07001012 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
1013 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
1014 // library to dexpreopt.
1015 ctx.AddVariationDependencies(nil, usesLibTag,
1016 "org.apache.http.legacy",
1017 "android.hidl.base-V1.0-java",
1018 "android.hidl.manager-V1.0-java")
1019 }
Colin Cross50ddcc42019-05-16 12:28:22 -07001020 }
1021}
1022
1023// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
1024// build.
1025func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
1026 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
1027 return optionalUsesLibs
1028}
1029
1030// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
1031func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
1032 usesLibPaths := make(map[string]android.Path)
1033
1034 if !ctx.Config().UnbundledBuild() {
1035 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
1036 if lib, ok := m.(Dependency); ok {
1037 if dexJar := lib.DexJar(); dexJar != nil {
1038 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
1039 } else {
1040 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
1041 ctx.OtherModuleName(m))
1042 }
1043 } else if ctx.Config().AllowMissingDependencies() {
1044 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
1045 } else {
1046 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
1047 ctx.OtherModuleName(m))
1048 }
1049 })
1050 }
1051
1052 return usesLibPaths
1053}
1054
1055// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
1056// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
1057// unconditionally in the future.
1058func (u *usesLibrary) enforceUsesLibraries() bool {
1059 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
1060 len(u.usesLibraryProperties.Optional_uses_libs) > 0
1061 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
1062}
1063
1064// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
1065// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
1066func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
1067 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
1068
1069 rule := android.NewRuleBuilder()
1070 cmd := rule.Command().Tool(ctx.Config().HostToolPath(ctx, "manifest_check")).
1071 Flag("--enforce-uses-libraries").
1072 Input(manifest).
1073 FlagWithOutput("-o ", outputFile)
1074
1075 for _, lib := range u.usesLibraryProperties.Uses_libs {
1076 cmd.FlagWithArg("--uses-library ", lib)
1077 }
1078
1079 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1080 cmd.FlagWithArg("--optional-uses-library ", lib)
1081 }
1082
1083 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1084
1085 return outputFile
1086}
1087
1088// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1089// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1090func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1091 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1092
1093 rule := android.NewRuleBuilder()
1094 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1095 rule.Command().
1096 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1097 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1098 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1099 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1100 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1101
1102 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1103
1104 return outputFile
1105}