blob: 2d817fe58d2e45ae34ca9be3ec6a2a7f8924a462 [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"
22 "strings"
Colin Cross30e076a2015-04-13 13:58:27 -070023
Colin Cross50ddcc42019-05-16 12:28:22 -070024 "github.com/google/blueprint"
25 "github.com/google/blueprint/proptools"
26
Colin Cross635c3b02016-05-18 15:37:25 -070027 "android/soong/android"
Colin Crossa4f08812018-10-02 22:03:40 -070028 "android/soong/cc"
Colin Cross303e21f2018-08-07 16:49:25 -070029 "android/soong/tradefed"
Colin Cross30e076a2015-04-13 13:58:27 -070030)
31
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070032var supportedDpis = [...]string{"Ldpi", "Mdpi", "Hdpi", "Xhdpi", "Xxhdpi", "Xxxhdpi"}
33var dpiVariantsStruct reflect.Type
34
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)
Jaewoong Junga5e5abc2019-04-26 14:31:50 -070042
43 // Dynamically construct a struct for the dpi_variants property in android_app_import.
44 perDpiStruct := reflect.StructOf([]reflect.StructField{
45 {
46 Name: "Apk",
47 Type: reflect.TypeOf((*string)(nil)),
48 },
49 })
50 dpiVariantsFields := make([]reflect.StructField, len(supportedDpis))
51 for i, dpi := range supportedDpis {
52 dpiVariantsFields[i] = reflect.StructField{
53 Name: string(dpi),
54 Type: perDpiStruct,
55 }
56 }
57 dpiVariantsStruct = reflect.StructOf(dpiVariantsFields)
Colin Cross3bc7ffa2017-11-22 16:19:37 -080058}
59
Colin Cross30e076a2015-04-13 13:58:27 -070060// AndroidManifest.xml merging
61// package splits
62
Colin Crossfabb6082018-02-20 17:22:23 -080063type appProperties struct {
Colin Crossbd01e2a2018-10-04 15:21:03 -070064 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
Colin Cross7d5136f2015-05-11 13:39:40 -070065 Additional_certificates []string
66
67 // If set, create package-export.apk, which other packages can
68 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
Nan Zhangea568a42017-11-08 21:20:04 -080069 Export_package_resources *bool
Colin Cross7d5136f2015-05-11 13:39:40 -070070
Colin Cross16056062017-12-13 22:46:28 -080071 // Specifies that this app should be installed to the priv-app directory,
72 // where the system will grant it additional privileges not available to
73 // normal apps.
74 Privileged *bool
Colin Crossa97c5d32018-03-28 14:58:31 -070075
76 // list of resource labels to generate individual resource packages
77 Package_splits []string
Jason Monkd4122be2018-08-10 09:33:36 -040078
79 // Names of modules to be overridden. Listed modules can only be other binaries
80 // (in Make or Soong).
81 // This does not completely prevent installation of the overridden binaries, but if both
82 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
83 // from PRODUCT_PACKAGES.
84 Overrides []string
Colin Crossa4f08812018-10-02 22:03:40 -070085
86 // list of native libraries that will be provided in or alongside the resulting jar
87 Jni_libs []string `android:"arch_variant"`
88
Jaewoong Jungbc625cd2019-05-06 15:48:44 -070089 // STL library to use for JNI libraries.
90 Stl *string `android:"arch_variant"`
91
Colin Crosse4246ab2019-02-05 21:55:21 -080092 // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
93 // flag so that they are used from inside the APK at runtime. Defaults to true for android_test modules unless
94 // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to false for other
95 // module types where the native libraries are generally preinstalled outside the APK.
96 Use_embedded_native_libs *bool
Colin Cross46abdad2019-02-07 13:07:08 -080097
98 // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
99 // they are used from inside the APK at runtime.
100 Use_embedded_dex *bool
Colin Cross47fa9d32019-03-26 10:51:39 -0700101
102 // Forces native libraries to always be packaged into the APK,
103 // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
104 // True for android_test* modules.
105 AlwaysPackageNativeLibs bool `blueprint:"mutated"`
Colin Cross7d5136f2015-05-11 13:39:40 -0700106}
107
Jaewoong Jung525443a2019-02-28 15:35:54 -0800108// android_app properties that can be overridden by override_android_app
109type overridableAppProperties struct {
110 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
111 // or an android_app_certificate module name in the form ":module".
112 Certificate *string
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700113
114 // the package name of this app. The package name in the manifest file is used if one was not given.
115 Package_name *string
Jaewoong Jung525443a2019-02-28 15:35:54 -0800116}
117
Colin Cross30e076a2015-04-13 13:58:27 -0700118type AndroidApp struct {
Colin Crossa97c5d32018-03-28 14:58:31 -0700119 Library
120 aapt
Jaewoong Jung525443a2019-02-28 15:35:54 -0800121 android.OverridableModuleBase
Colin Crossa97c5d32018-03-28 14:58:31 -0700122
Colin Cross50ddcc42019-05-16 12:28:22 -0700123 usesLibrary usesLibrary
124
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900125 certificate Certificate
Colin Cross30e076a2015-04-13 13:58:27 -0700126
Colin Crossfabb6082018-02-20 17:22:23 -0800127 appProperties appProperties
Colin Crossae5caf52018-05-22 11:11:52 -0700128
Jaewoong Jung525443a2019-02-28 15:35:54 -0800129 overridableAppProperties overridableAppProperties
130
Colin Crossa4f08812018-10-02 22:03:40 -0700131 installJniLibs []jniLib
Colin Crossf6237212018-10-29 23:14:58 -0700132
133 bundleFile android.Path
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800134
135 // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
136 installApkName string
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800137
138 additionalAaptFlags []string
Colin Crosse1731a52017-12-14 11:22:55 -0800139}
140
Colin Cross89c31582018-04-30 15:55:11 -0700141func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
142 return nil
143}
144
Colin Cross66f78822018-05-02 12:58:28 -0700145func (a *AndroidApp) ExportedStaticPackages() android.Paths {
146 return nil
147}
148
Colin Crossa97c5d32018-03-28 14:58:31 -0700149var _ AndroidLibraryDependency = (*AndroidApp)(nil)
150
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900151type Certificate struct {
152 Pem, Key android.Path
Colin Cross30e076a2015-04-13 13:58:27 -0700153}
154
Colin Cross46c9b8b2017-06-22 16:51:17 -0700155func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
156 a.Module.deps(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700157
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700158 if String(a.appProperties.Stl) == "c++_shared" && a.sdkVersion() == "" {
159 ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
160 }
161
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800162 if !Bool(a.properties.No_framework_libs) && !Bool(a.properties.No_standard_libs) {
Colin Cross83bb3162018-06-25 15:48:06 -0700163 a.aapt.deps(ctx, sdkContext(a))
Colin Cross30e076a2015-04-13 13:58:27 -0700164 }
Colin Crossa4f08812018-10-02 22:03:40 -0700165
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700166 embedJni := a.shouldEmbedJnis(ctx)
Colin Crossa4f08812018-10-02 22:03:40 -0700167 for _, jniTarget := range ctx.MultiTargets() {
168 variation := []blueprint.Variation{
169 {Mutator: "arch", Variation: jniTarget.String()},
170 {Mutator: "link", Variation: "shared"},
171 }
172 tag := &jniDependencyTag{
173 target: jniTarget,
174 }
175 ctx.AddFarVariationDependencies(variation, tag, a.appProperties.Jni_libs...)
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700176 if String(a.appProperties.Stl) == "c++_shared" {
177 if embedJni {
178 ctx.AddFarVariationDependencies(variation, tag, "libc++")
179 }
180 }
Colin Crossa4f08812018-10-02 22:03:40 -0700181 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700182
183 a.usesLibrary.deps(ctx, Bool(a.properties.No_framework_libs))
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700184}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700185
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700186func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800187 cert := android.SrcIsModule(a.getCertString(ctx))
Colin Crossbd01e2a2018-10-04 15:21:03 -0700188 if cert != "" {
189 ctx.AddDependency(ctx.Module(), certificateTag, cert)
190 }
191
192 for _, cert := range a.appProperties.Additional_certificates {
193 cert = android.SrcIsModule(cert)
194 if cert != "" {
195 ctx.AddDependency(ctx.Module(), certificateTag, cert)
196 } else {
197 ctx.PropertyErrorf("additional_certificates",
198 `must be names of android_app_certificate modules in the form ":module"`)
199 }
200 }
Colin Cross30e076a2015-04-13 13:58:27 -0700201}
202
Colin Cross46c9b8b2017-06-22 16:51:17 -0700203func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sasha Smundak6ad77252019-05-01 13:16:22 -0700204 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
Colin Cross46abdad2019-02-07 13:07:08 -0800205 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700206 a.generateAndroidBuildActions(ctx)
207}
208
Sasha Smundak6ad77252019-05-01 13:16:22 -0700209// Returns true if the native libraries should be stored in the APK uncompressed and the
Colin Crosse4246ab2019-02-05 21:55:21 -0800210// extractNativeLibs application flag should be set to false in the manifest.
Sasha Smundak6ad77252019-05-01 13:16:22 -0700211func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
Colin Crosse4246ab2019-02-05 21:55:21 -0800212 minSdkVersion, err := sdkVersionToNumber(ctx, a.minSdkVersion())
213 if err != nil {
214 ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.minSdkVersion(), err)
215 }
216
217 return minSdkVersion >= 23 && Bool(a.appProperties.Use_embedded_native_libs)
218}
219
Colin Cross43f08db2018-11-12 10:13:39 -0800220// Returns whether this module should have the dex file stored uncompressed in the APK.
221func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
Colin Cross46abdad2019-02-07 13:07:08 -0800222 if Bool(a.appProperties.Use_embedded_dex) {
223 return true
224 }
225
Colin Cross5a0dcd52018-10-05 14:20:06 -0700226 if ctx.Config().UnbundledBuild() {
Colin Cross43f08db2018-11-12 10:13:39 -0800227 return false
Colin Cross5a0dcd52018-10-05 14:20:06 -0700228 }
229
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700230 // Uncompress dex in APKs of privileged apps
231 if ctx.Config().UncompressPrivAppDex() && Bool(a.appProperties.Privileged) {
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000232 return true
233 }
234
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700235 return shouldUncompressDex(ctx, &a.dexpreopter)
Colin Cross5a0dcd52018-10-05 14:20:06 -0700236}
237
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700238func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
239 return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
240 a.appProperties.AlwaysPackageNativeLibs
241}
242
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800243func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
David Brazdild25060a2019-02-18 18:24:16 +0000244 a.aapt.usesNonSdkApis = Bool(a.Module.deviceProperties.Platform_apis)
245
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800246 aaptLinkFlags := []string{}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800247
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800248 // 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 -0700249 hasProduct := false
250 for _, f := range a.aaptProperties.Aaptflags {
251 if strings.HasPrefix(f, "--product") {
252 hasProduct = true
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800253 break
Colin Crosse78dcd32018-04-19 15:25:19 -0700254 }
255 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700256 if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800257 aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
Colin Crosse78dcd32018-04-19 15:25:19 -0700258 }
259
Dan Willemsen72be5902018-10-24 20:24:57 -0700260 if !Bool(a.aaptProperties.Aapt_include_all_resources) {
261 // Product AAPT config
262 for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800263 aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
Dan Willemsen72be5902018-10-24 20:24:57 -0700264 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700265
Dan Willemsen72be5902018-10-24 20:24:57 -0700266 // Product AAPT preferred config
267 if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800268 aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
Dan Willemsen72be5902018-10-24 20:24:57 -0700269 }
Colin Crosse78dcd32018-04-19 15:25:19 -0700270 }
271
Jiyong Park7f67f482019-01-05 12:57:48 +0900272 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jaewoong Jung6f373f62019-03-13 10:13:24 -0700273 if overridden || a.overridableAppProperties.Package_name != nil {
274 // The product override variable has a priority over the package_name property.
275 if !overridden {
276 manifestPackageName = *a.overridableAppProperties.Package_name
277 }
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800278 aaptLinkFlags = append(aaptLinkFlags, "--rename-manifest-package "+manifestPackageName)
Jiyong Park7f67f482019-01-05 12:57:48 +0900279 }
280
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800281 aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
282
Colin Crosse560c4a2019-03-19 16:03:11 -0700283 a.aapt.splitNames = a.appProperties.Package_splits
Colin Cross50ddcc42019-05-16 12:28:22 -0700284 a.aapt.sdkLibraries = a.exportedSdkLibs
Colin Crosse560c4a2019-03-19 16:03:11 -0700285
Jaewoong Jungde4c02f2019-01-22 11:19:56 -0800286 a.aapt.buildActions(ctx, sdkContext(a), aaptLinkFlags...)
Colin Cross30e076a2015-04-13 13:58:27 -0700287
Colin Cross46c9b8b2017-06-22 16:51:17 -0700288 // apps manifests are handled by aapt, don't let Module see them
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700289 a.properties.Manifest = nil
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800290}
Colin Cross30e076a2015-04-13 13:58:27 -0700291
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800292func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
Colin Cross89c31582018-04-30 15:55:11 -0700293 var staticLibProguardFlagFiles android.Paths
294 ctx.VisitDirectDeps(func(m android.Module) {
295 if lib, ok := m.(AndroidLibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
296 staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
297 }
298 })
299
300 staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
301
302 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
303 a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800304}
Colin Cross66dbc0b2017-12-28 12:23:20 -0800305
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800306func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
Colin Cross43f08db2018-11-12 10:13:39 -0800307
308 var installDir string
309 if ctx.ModuleName() == "framework-res" {
310 // framework-res.apk is installed as system/framework/framework-res.apk
311 installDir = "framework"
312 } else if Bool(a.appProperties.Privileged) {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800313 installDir = filepath.Join("priv-app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800314 } else {
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800315 installDir = filepath.Join("app", a.installApkName)
Colin Cross43f08db2018-11-12 10:13:39 -0800316 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700317
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800318 a.dexpreopter.installPath = android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000319 a.dexpreopter.isInstallable = Bool(a.properties.Installable)
320 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700321
322 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
323 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
324 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
325 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
326 a.dexpreopter.manifestFile = a.mergedManifestFile
327
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000328 a.deviceProperties.UncompressDex = a.dexpreopter.uncompressedDex
Colin Cross5a0dcd52018-10-05 14:20:06 -0700329
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800330 if ctx.ModuleName() != "framework-res" {
331 a.Module.compile(ctx, a.aaptSrcJar)
332 }
Colin Cross30e076a2015-04-13 13:58:27 -0700333
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800334 return a.maybeStrippedDexJarFile
335}
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800336
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800337func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, ctx android.ModuleContext) android.WritablePath {
Colin Crossa4f08812018-10-02 22:03:40 -0700338 var jniJarFile android.WritablePath
Colin Crossa4f08812018-10-02 22:03:40 -0700339 if len(jniLibs) > 0 {
Jaewoong Jungbc625cd2019-05-06 15:48:44 -0700340 if a.shouldEmbedJnis(ctx) {
Colin Crossa4f08812018-10-02 22:03:40 -0700341 jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
Sasha Smundak6ad77252019-05-01 13:16:22 -0700342 TransformJniLibsToJar(ctx, jniJarFile, jniLibs, a.useEmbeddedNativeLibs(ctx))
Colin Crossa4f08812018-10-02 22:03:40 -0700343 } else {
344 a.installJniLibs = jniLibs
345 }
346 }
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800347 return jniJarFile
348}
Colin Crossa4f08812018-10-02 22:03:40 -0700349
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700350// Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
351// isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
352func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate, ctx android.ModuleContext) []Certificate {
353 if android.SrcIsModule(certPropValue) == "" {
354 var mainCert Certificate
355 if certPropValue != "" {
356 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
357 mainCert = Certificate{
358 defaultDir.Join(ctx, certPropValue+".x509.pem"),
359 defaultDir.Join(ctx, certPropValue+".pk8"),
360 }
361 } else {
362 pem, key := ctx.Config().DefaultAppCertificate(ctx)
363 mainCert = Certificate{pem, key}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700364 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700365 certificates = append([]Certificate{mainCert}, certificates...)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700366 }
367
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700368 if !m.Platform() {
369 certPath := certificates[0].Pem.String()
Jeongik Chac9464142019-01-07 12:07:27 +0900370 systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
371 if strings.HasPrefix(certPath, systemCertPath) {
372 enforceSystemCert := ctx.Config().EnforceSystemCertificate()
373 whitelist := ctx.Config().EnforceSystemCertificateWhitelist()
374
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700375 if enforceSystemCert && !inList(m.Name(), whitelist) {
Jeongik Chac9464142019-01-07 12:07:27 +0900376 ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
377 }
378 }
379 }
380
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700381 return certificates
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800382}
383
384func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross50ddcc42019-05-16 12:28:22 -0700385 var apkDeps android.Paths
386
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800387 // Check if the install APK name needs to be overridden.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800388 a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Name())
Jaewoong Jung9d22a912019-01-23 16:27:47 -0800389
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800390 // Process all building blocks, from AAPT to certificates.
391 a.aaptBuildActions(ctx)
392
Colin Cross50ddcc42019-05-16 12:28:22 -0700393 if a.usesLibrary.enforceUsesLibraries() {
394 manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
395 apkDeps = append(apkDeps, manifestCheckFile)
396 }
397
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800398 a.proguardBuildActions(ctx)
399
400 dexJarFile := a.dexBuildActions(ctx)
401
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700402 jniLibs, certificateDeps := collectAppDeps(ctx)
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800403 jniJarFile := a.jniBuildActions(jniLibs, ctx)
404
405 if ctx.Failed() {
406 return
407 }
408
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700409 certificates := processMainCert(a.ModuleBase, a.getCertString(ctx), certificateDeps, ctx)
410 a.certificate = certificates[0]
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800411
412 // Build a final signed app package.
Jaewoong Jung525443a2019-02-28 15:35:54 -0800413 // TODO(jungjw): Consider changing this to installApkName.
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800414 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700415 CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800416 a.outputFile = packageFile
417
Colin Crosse560c4a2019-03-19 16:03:11 -0700418 for _, split := range a.aapt.splits {
419 // Sign the split APKs
420 packageFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"_"+split.suffix+".apk")
Colin Cross50ddcc42019-05-16 12:28:22 -0700421 CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps)
Colin Crosse560c4a2019-03-19 16:03:11 -0700422 a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
423 }
424
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800425 // Build an app bundle.
Colin Crossf6237212018-10-29 23:14:58 -0700426 bundleFile := android.PathForModuleOut(ctx, "base.zip")
427 BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
428 a.bundleFile = bundleFile
429
Jaewoong Jung590b1ae2019-01-22 16:40:58 -0800430 // Install the app package.
Colin Crosse560c4a2019-03-19 16:03:11 -0700431 var installDir android.OutputPath
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800432 if ctx.ModuleName() == "framework-res" {
433 // framework-res.apk is installed as system/framework/framework-res.apk
Colin Crosse560c4a2019-03-19 16:03:11 -0700434 installDir = android.PathForModuleInstall(ctx, "framework")
Colin Cross16056062017-12-13 22:46:28 -0800435 } else if Bool(a.appProperties.Privileged) {
Colin Crosse560c4a2019-03-19 16:03:11 -0700436 installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800437 } else {
Colin Crosse560c4a2019-03-19 16:03:11 -0700438 installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
439 }
440
441 ctx.InstallFile(installDir, a.installApkName+".apk", a.outputFile)
442 for _, split := range a.aapt.splits {
443 ctx.InstallFile(installDir, a.installApkName+"_"+split.suffix+".apk", split.path)
Colin Cross5ab4e6d2017-11-22 16:20:45 -0800444 }
Colin Cross30e076a2015-04-13 13:58:27 -0700445}
446
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700447func collectAppDeps(ctx android.ModuleContext) ([]jniLib, []Certificate) {
Colin Crossa4f08812018-10-02 22:03:40 -0700448 var jniLibs []jniLib
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900449 var certificates []Certificate
Colin Crossa4f08812018-10-02 22:03:40 -0700450
451 ctx.VisitDirectDeps(func(module android.Module) {
452 otherName := ctx.OtherModuleName(module)
453 tag := ctx.OtherModuleDependencyTag(module)
454
455 if jniTag, ok := tag.(*jniDependencyTag); ok {
456 if dep, ok := module.(*cc.Module); ok {
457 lib := dep.OutputFile()
458 if lib.Valid() {
459 jniLibs = append(jniLibs, jniLib{
460 name: ctx.OtherModuleName(module),
461 path: lib.Path(),
462 target: jniTag.target,
463 })
464 } else {
465 ctx.ModuleErrorf("dependency %q missing output file", otherName)
466 }
467 } else {
468 ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
Colin Crossa4f08812018-10-02 22:03:40 -0700469 }
Colin Crossbd01e2a2018-10-04 15:21:03 -0700470 } else if tag == certificateTag {
471 if dep, ok := module.(*AndroidAppCertificate); ok {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900472 certificates = append(certificates, dep.Certificate)
Colin Crossbd01e2a2018-10-04 15:21:03 -0700473 } else {
474 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
475 }
Colin Crossa4f08812018-10-02 22:03:40 -0700476 }
477 })
478
Colin Crossbd01e2a2018-10-04 15:21:03 -0700479 return jniLibs, certificates
Colin Crossa4f08812018-10-02 22:03:40 -0700480}
481
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800482func (a *AndroidApp) getCertString(ctx android.BaseContext) string {
483 certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
484 if overridden {
Jaewoong Jungacb6db32019-02-28 16:22:30 +0000485 return ":" + certificate
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800486 }
Jaewoong Jung525443a2019-02-28 15:35:54 -0800487 return String(a.overridableAppProperties.Certificate)
Jaewoong Jung2ad817c2019-01-18 14:27:16 -0800488}
489
Colin Cross1b16b0e2019-02-12 14:41:32 -0800490// android_app compiles sources and Android resources into an Android application package `.apk` file.
Colin Cross36242852017-06-23 15:06:31 -0700491func AndroidAppFactory() android.Module {
Colin Cross30e076a2015-04-13 13:58:27 -0700492 module := &AndroidApp{}
493
Sasha Smundak2057f822019-04-16 17:16:58 -0700494 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross66dbc0b2017-12-28 12:23:20 -0800495 module.Module.deviceProperties.Optimize.Shrink = proptools.BoolPtr(true)
496
Colin Crossae5caf52018-05-22 11:11:52 -0700497 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700498 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crossae5caf52018-05-22 11:11:52 -0700499
Colin Cross36242852017-06-23 15:06:31 -0700500 module.AddProperties(
Colin Cross540eff82017-06-22 17:01:52 -0700501 &module.Module.properties,
502 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800503 &module.Module.dexpreoptProperties,
Colin Crossa97c5d32018-03-28 14:58:31 -0700504 &module.Module.protoProperties,
505 &module.aaptProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800506 &module.appProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700507 &module.overridableAppProperties,
508 &module.usesLibrary.usesLibraryProperties)
Colin Cross36242852017-06-23 15:06:31 -0700509
Colin Crossa9d8bee2018-10-02 13:59:46 -0700510 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
511 return class == android.Device && ctx.Config().DevicePrefer32BitApps()
512 })
513
Colin Crossa4f08812018-10-02 22:03:40 -0700514 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
515 android.InitDefaultableModule(module)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800516 android.InitOverridableModule(module, &module.appProperties.Overrides)
Colin Crossa4f08812018-10-02 22:03:40 -0700517
Colin Cross36242852017-06-23 15:06:31 -0700518 return module
Colin Cross30e076a2015-04-13 13:58:27 -0700519}
Colin Crossae5caf52018-05-22 11:11:52 -0700520
521type appTestProperties struct {
522 Instrumentation_for *string
523}
524
525type AndroidTest struct {
526 AndroidApp
527
528 appTestProperties appTestProperties
529
530 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700531
532 testConfig android.Path
Colin Crossd96ca352018-08-10 16:06:24 -0700533 data android.Paths
Colin Crossae5caf52018-05-22 11:11:52 -0700534}
535
536func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jung4102e5d2019-02-27 16:26:28 -0800537 // Check if the instrumentation target package is overridden before generating build actions.
538 if a.appTestProperties.Instrumentation_for != nil {
539 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
540 if overridden {
541 a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
542 }
543 }
Sasha Smundak6ad77252019-05-01 13:16:22 -0700544 a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
545 a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
Colin Crossae5caf52018-05-22 11:11:52 -0700546 a.generateAndroidBuildActions(ctx)
Colin Cross303e21f2018-08-07 16:49:25 -0700547
yangbill4f41bc22019-02-13 21:45:47 +0800548 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 -0800549 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700550}
551
552func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross303e21f2018-08-07 16:49:25 -0700553 a.AndroidApp.DepsMutator(ctx)
Colin Cross4b964c02018-10-15 16:18:06 -0700554 if a.appTestProperties.Instrumentation_for != nil {
555 // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
556 // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
557 // use instrumentationForTag instead of libTag.
558 ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
559 }
Colin Crossae5caf52018-05-22 11:11:52 -0700560}
561
Colin Cross1b16b0e2019-02-12 14:41:32 -0800562// android_test compiles test sources and Android resources into an Android application package `.apk` file and
563// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
Colin Crossae5caf52018-05-22 11:11:52 -0700564func AndroidTestFactory() android.Module {
565 module := &AndroidTest{}
566
Sasha Smundak2057f822019-04-16 17:16:58 -0700567 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross5067db92018-09-17 16:46:35 -0700568
569 module.Module.properties.Instrument = true
Colin Cross9ae1b922018-06-26 17:59:05 -0700570 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800571 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700572 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800573 module.Module.dexpreopter.isTest = true
Colin Crossae5caf52018-05-22 11:11:52 -0700574
575 module.AddProperties(
576 &module.Module.properties,
577 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800578 &module.Module.dexpreoptProperties,
Colin Crossae5caf52018-05-22 11:11:52 -0700579 &module.Module.protoProperties,
580 &module.aaptProperties,
581 &module.appProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700582 &module.appTestProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800583 &module.overridableAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700584 &module.usesLibrary.usesLibraryProperties,
Dan Willemsenf5531d22018-07-16 17:21:19 -0700585 &module.testProperties)
Colin Crossae5caf52018-05-22 11:11:52 -0700586
Colin Crossa4f08812018-10-02 22:03:40 -0700587 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
588 android.InitDefaultableModule(module)
Colin Crossae5caf52018-05-22 11:11:52 -0700589 return module
590}
Colin Crossbd01e2a2018-10-04 15:21:03 -0700591
Colin Cross252fc6f2018-10-04 15:22:03 -0700592type appTestHelperAppProperties struct {
593 // list of compatibility suites (for example "cts", "vts") that the module should be
594 // installed into.
595 Test_suites []string `android:"arch_variant"`
596}
597
598type AndroidTestHelperApp struct {
599 AndroidApp
600
601 appTestHelperAppProperties appTestHelperAppProperties
602}
603
Colin Cross1b16b0e2019-02-12 14:41:32 -0800604// android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
605// will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
606// test.
Colin Cross252fc6f2018-10-04 15:22:03 -0700607func AndroidTestHelperAppFactory() android.Module {
608 module := &AndroidTestHelperApp{}
609
Sasha Smundak2057f822019-04-16 17:16:58 -0700610 module.Module.deviceProperties.Optimize.EnabledByDefault = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700611
612 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse4246ab2019-02-05 21:55:21 -0800613 module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
Colin Cross47fa9d32019-03-26 10:51:39 -0700614 module.appProperties.AlwaysPackageNativeLibs = true
Colin Cross43f08db2018-11-12 10:13:39 -0800615 module.Module.dexpreopter.isTest = true
Colin Cross252fc6f2018-10-04 15:22:03 -0700616
617 module.AddProperties(
618 &module.Module.properties,
619 &module.Module.deviceProperties,
Colin Cross43f08db2018-11-12 10:13:39 -0800620 &module.Module.dexpreoptProperties,
Colin Cross252fc6f2018-10-04 15:22:03 -0700621 &module.Module.protoProperties,
622 &module.aaptProperties,
623 &module.appProperties,
Jaewoong Jung525443a2019-02-28 15:35:54 -0800624 &module.appTestHelperAppProperties,
Colin Cross50ddcc42019-05-16 12:28:22 -0700625 &module.overridableAppProperties,
626 &module.usesLibrary.usesLibraryProperties)
Colin Cross252fc6f2018-10-04 15:22:03 -0700627
628 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
629 android.InitDefaultableModule(module)
630 return module
631}
632
Colin Crossbd01e2a2018-10-04 15:21:03 -0700633type AndroidAppCertificate struct {
634 android.ModuleBase
635 properties AndroidAppCertificateProperties
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900636 Certificate Certificate
Colin Crossbd01e2a2018-10-04 15:21:03 -0700637}
638
639type AndroidAppCertificateProperties struct {
640 // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
641 Certificate *string
642}
643
Colin Cross1b16b0e2019-02-12 14:41:32 -0800644// android_app_certificate modules can be referenced by the certificates property of android_app modules to select
645// the signing key.
Colin Crossbd01e2a2018-10-04 15:21:03 -0700646func AndroidAppCertificateFactory() android.Module {
647 module := &AndroidAppCertificate{}
648 module.AddProperties(&module.properties)
649 android.InitAndroidModule(module)
650 return module
651}
652
Colin Crossbd01e2a2018-10-04 15:21:03 -0700653func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
654 cert := String(c.properties.Certificate)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900655 c.Certificate = Certificate{
Colin Crossbd01e2a2018-10-04 15:21:03 -0700656 android.PathForModuleSrc(ctx, cert+".x509.pem"),
657 android.PathForModuleSrc(ctx, cert+".pk8"),
658 }
659}
Jaewoong Jung525443a2019-02-28 15:35:54 -0800660
661type OverrideAndroidApp struct {
662 android.ModuleBase
663 android.OverrideModuleBase
664}
665
666func (i *OverrideAndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
667 // All the overrides happen in the base module.
668 // TODO(jungjw): Check the base module type.
669}
670
671// override_android_app is used to create an android_app module based on another android_app by overriding
672// some of its properties.
673func OverrideAndroidAppModuleFactory() android.Module {
674 m := &OverrideAndroidApp{}
675 m.AddProperties(&overridableAppProperties{})
676
Jaewoong Jungb639a6a2019-05-10 15:16:29 -0700677 android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
Jaewoong Jung525443a2019-02-28 15:35:54 -0800678 android.InitOverrideModule(m)
679 return m
680}
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700681
682type AndroidAppImport struct {
683 android.ModuleBase
684 android.DefaultableModuleBase
685 prebuilt android.Prebuilt
686
687 properties AndroidAppImportProperties
688
689 outputFile android.Path
690 certificate *Certificate
691
692 dexpreopter
Colin Cross50ddcc42019-05-16 12:28:22 -0700693
694 usesLibrary usesLibrary
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700695}
696
697type AndroidAppImportProperties struct {
698 // A prebuilt apk to import
699 Apk string
700
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700701 // Per-DPI settings. This property makes it possible to specify a different source apk path for
702 // each DPI.
703 //
704 // Example:
705 //
706 // android_app_import {
707 // name: "example_import",
708 // apk: "prebuilts/example.apk",
709 // dpi_variants: {
710 // mdpi: {
711 // apk: "prebuilts/example_mdpi.apk",
712 // },
713 // xhdpi: {
714 // apk: "prebuilts/example_xhdpi.apk",
715 // },
716 // },
717 // certificate: "PRESIGNED",
718 // }
719 Dpi_variants interface{}
720
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700721 // The name of a certificate in the default certificate directory, blank to use the default
722 // product certificate, or an android_app_certificate module name in the form ":module".
723 Certificate *string
724
725 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
726 // be set for presigned modules.
727 Presigned *bool
728
729 // Specifies that this app should be installed to the priv-app directory,
730 // where the system will grant it additional privileges not available to
731 // normal apps.
732 Privileged *bool
733
734 // Names of modules to be overridden. Listed modules can only be other binaries
735 // (in Make or Soong).
736 // This does not completely prevent installation of the overridden binaries, but if both
737 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
738 // from PRODUCT_PACKAGES.
739 Overrides []string
740}
741
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700742func getApkPathForDpi(dpiVariantsValue reflect.Value, dpi string) string {
743 dpiField := dpiVariantsValue.FieldByName(proptools.FieldNameForProperty(dpi))
744 if !dpiField.IsValid() {
745 return ""
746 }
747 apkValue := dpiField.FieldByName("Apk").Elem()
748 if apkValue.IsValid() {
749 return apkValue.String()
750 }
751 return ""
752}
753
754// Chooses a source APK path to use based on the module's per-DPI settings and the product config.
755func (a *AndroidAppImport) getSrcApkPath(ctx android.ModuleContext) string {
756 config := ctx.Config()
757 dpiVariantsValue := reflect.ValueOf(a.properties.Dpi_variants).Elem()
758 if !dpiVariantsValue.IsValid() {
759 return a.properties.Apk
760 }
761 // Match PRODUCT_AAPT_PREF_CONFIG first and then PRODUCT_AAPT_PREBUILT_DPI.
762 if config.ProductAAPTPreferredConfig() != "" {
763 if apk := getApkPathForDpi(dpiVariantsValue, config.ProductAAPTPreferredConfig()); apk != "" {
764 return apk
765 }
766 }
767 for _, dpi := range config.ProductAAPTPrebuiltDPI() {
768 if apk := getApkPathForDpi(dpiVariantsValue, dpi); apk != "" {
769 return apk
770 }
771 }
772
773 // No match. Use the generic one.
774 return a.properties.Apk
775}
776
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700777func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
778 cert := android.SrcIsModule(String(a.properties.Certificate))
779 if cert != "" {
780 ctx.AddDependency(ctx.Module(), certificateTag, cert)
781 }
Colin Cross50ddcc42019-05-16 12:28:22 -0700782
783 a.usesLibrary.deps(ctx, false)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700784}
785
786func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
787 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
788 rule := android.NewRuleBuilder()
789 rule.Command().
790 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
791 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
792 FlagWithInput("-i ", inputPath).
793 FlagWithOutput("-o ", outputPath).
794 FlagWithArg("-0 ", "'lib/**/*.so'").
795 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
796 rule.Build(pctx, ctx, "uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
797}
798
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700799// Returns whether this module should have the dex file stored uncompressed in the APK.
800func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
801 if ctx.Config().UnbundledBuild() {
802 return false
803 }
804
805 // Uncompress dex in APKs of privileged apps
806 if ctx.Config().UncompressPrivAppDex() && Bool(a.properties.Privileged) {
807 return true
808 }
809
810 return shouldUncompressDex(ctx, &a.dexpreopter)
811}
812
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700813func (a *AndroidAppImport) uncompressDex(
814 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
815 rule := android.NewRuleBuilder()
816 rule.Command().
817 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
818 Tool(ctx.Config().HostToolPath(ctx, "zip2zip")).
819 FlagWithInput("-i ", inputPath).
820 FlagWithOutput("-o ", outputPath).
821 FlagWithArg("-0 ", "'classes*.dex'").
822 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
823 rule.Build(pctx, ctx, "uncompress-dex", "Uncompress dex files")
824}
825
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700826func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
827 if String(a.properties.Certificate) == "" && !Bool(a.properties.Presigned) {
828 ctx.PropertyErrorf("certificate", "No certificate specified for prebuilt")
829 }
830 if String(a.properties.Certificate) != "" && Bool(a.properties.Presigned) {
831 ctx.PropertyErrorf("certificate", "Certificate can't be specified for presigned modules")
832 }
833
834 _, certificates := collectAppDeps(ctx)
835
836 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700837 // TODO: LOCAL_PACKAGE_SPLITS
838
Colin Cross50ddcc42019-05-16 12:28:22 -0700839 var srcApk android.Path
840 srcApk = android.PathForModuleSrc(ctx, a.getSrcApkPath(ctx))
841
842 if a.usesLibrary.enforceUsesLibraries() {
843 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
844 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700845
846 // TODO: Install or embed JNI libraries
847
848 // Uncompress JNI libraries in the apk
849 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
850 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
851
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700852 installDir := android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
853 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
854 a.dexpreopter.isInstallable = true
855 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
Jaewoong Jungacf18d72019-05-02 14:55:29 -0700856 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
Colin Cross50ddcc42019-05-16 12:28:22 -0700857
858 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
859 a.dexpreopter.usesLibs = a.usesLibrary.usesLibraryProperties.Uses_libs
860 a.dexpreopter.optionalUsesLibs = a.usesLibrary.presentOptionalUsesLibs(ctx)
861 a.dexpreopter.libraryPaths = a.usesLibrary.usesLibraryPaths(ctx)
862
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700863 dexOutput := a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
Jaewoong Jungea1bdb02019-05-09 14:36:34 -0700864 if a.dexpreopter.uncompressedDex {
865 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
866 a.uncompressDex(ctx, dexOutput, dexUncompressed.OutputPath)
867 dexOutput = dexUncompressed
868 }
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700869
870 // Sign or align the package
871 // TODO: Handle EXTERNAL
872 if !Bool(a.properties.Presigned) {
873 certificates = processMainCert(a.ModuleBase, *a.properties.Certificate, certificates, ctx)
874 if len(certificates) != 1 {
875 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
876 }
877 a.certificate = &certificates[0]
878 signed := android.PathForModuleOut(ctx, "signed", ctx.ModuleName()+".apk")
879 SignAppPackage(ctx, signed, dexOutput, certificates)
880 a.outputFile = signed
881 } else {
882 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", ctx.ModuleName()+".apk")
883 TransformZipAlign(ctx, alignedApk, dexOutput)
884 a.outputFile = alignedApk
885 }
886
887 // TODO: Optionally compress the output apk.
888
889 ctx.InstallFile(installDir, a.BaseModuleName()+".apk", a.outputFile)
890
891 // TODO: androidmk converter jni libs
892}
893
894func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
895 return &a.prebuilt
896}
897
898func (a *AndroidAppImport) Name() string {
899 return a.prebuilt.Name(a.ModuleBase.Name())
900}
901
902// android_app_import imports a prebuilt apk with additional processing specified in the module.
903func AndroidAppImportFactory() android.Module {
904 module := &AndroidAppImport{}
Jaewoong Junga5e5abc2019-04-26 14:31:50 -0700905 module.properties.Dpi_variants = reflect.New(dpiVariantsStruct).Interface()
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700906 module.AddProperties(&module.properties)
907 module.AddProperties(&module.dexpreoptProperties)
Colin Cross50ddcc42019-05-16 12:28:22 -0700908 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
Jaewoong Jungccbb3932019-04-15 09:48:31 -0700909
910 InitJavaModule(module, android.DeviceSupported)
911 android.InitSingleSourcePrebuiltModule(module, &module.properties.Apk)
912
913 return module
914}
Colin Cross50ddcc42019-05-16 12:28:22 -0700915
916type UsesLibraryProperties struct {
917 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
918 Uses_libs []string
919
920 // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
921 // required=false.
922 Optional_uses_libs []string
923
924 // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
925 // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
926 Enforce_uses_libs *bool
927}
928
929// usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
930// <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
931// uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
932// with knowledge of their shared libraries.
933type usesLibrary struct {
934 usesLibraryProperties UsesLibraryProperties
935}
936
937func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, noFrameworkLibs bool) {
938 ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
939 ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
940 if !noFrameworkLibs {
941 // dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
942 // to pass them to dex2oat. Add them as a dependency so we can determine the path to the dex jar of each
943 // library to dexpreopt.
944 ctx.AddVariationDependencies(nil, usesLibTag,
945 "org.apache.http.legacy",
946 "android.hidl.base-V1.0-java",
947 "android.hidl.manager-V1.0-java")
948 }
949}
950
951// presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
952// build.
953func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
954 optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
955 return optionalUsesLibs
956}
957
958// usesLibraryPaths returns a map of module names of shared library dependencies to the paths to their dex jars.
959func (u *usesLibrary) usesLibraryPaths(ctx android.ModuleContext) map[string]android.Path {
960 usesLibPaths := make(map[string]android.Path)
961
962 if !ctx.Config().UnbundledBuild() {
963 ctx.VisitDirectDepsWithTag(usesLibTag, func(m android.Module) {
964 if lib, ok := m.(Dependency); ok {
965 if dexJar := lib.DexJar(); dexJar != nil {
966 usesLibPaths[ctx.OtherModuleName(m)] = dexJar
967 } else {
968 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must produce a dex jar, does it have installable: true?",
969 ctx.OtherModuleName(m))
970 }
971 } else if ctx.Config().AllowMissingDependencies() {
972 ctx.AddMissingDependencies([]string{ctx.OtherModuleName(m)})
973 } else {
974 ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library",
975 ctx.OtherModuleName(m))
976 }
977 })
978 }
979
980 return usesLibPaths
981}
982
983// enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
984// properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
985// unconditionally in the future.
986func (u *usesLibrary) enforceUsesLibraries() bool {
987 defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
988 len(u.usesLibraryProperties.Optional_uses_libs) > 0
989 return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, defaultEnforceUsesLibs)
990}
991
992// verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against the ones specified
993// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the manifest.
994func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
995 outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
996
997 rule := android.NewRuleBuilder()
998 cmd := rule.Command().Tool(ctx.Config().HostToolPath(ctx, "manifest_check")).
999 Flag("--enforce-uses-libraries").
1000 Input(manifest).
1001 FlagWithOutput("-o ", outputFile)
1002
1003 for _, lib := range u.usesLibraryProperties.Uses_libs {
1004 cmd.FlagWithArg("--uses-library ", lib)
1005 }
1006
1007 for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
1008 cmd.FlagWithArg("--optional-uses-library ", lib)
1009 }
1010
1011 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1012
1013 return outputFile
1014}
1015
1016// verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the ones specified
1017// in the uses_libs and optional_uses_libs properties. It returns the path to a copy of the APK.
1018func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) android.Path {
1019 outputFile := android.PathForModuleOut(ctx, "verify_uses_libraries", apk.Base())
1020
1021 rule := android.NewRuleBuilder()
1022 aapt := ctx.Config().HostToolPath(ctx, "aapt")
1023 rule.Command().
1024 Textf("aapt_binary=%s", aapt.String()).Implicit(aapt).
1025 Textf(`uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Uses_libs, " ")).
1026 Textf(`optional_uses_library_names="%s"`, strings.Join(u.usesLibraryProperties.Optional_uses_libs, " ")).
1027 Tool(android.PathForSource(ctx, "build/make/core/verify_uses_libraries.sh")).Input(apk)
1028 rule.Command().Text("cp -f").Input(apk).Output(outputFile)
1029
1030 rule.Build(pctx, ctx, "verify_uses_libraries", "verify <uses-library>")
1031
1032 return outputFile
1033}