blob: faf47163488a1d088224ac5f4abb3ca398c277a8 [file] [log] [blame]
Jaewoong Jungf9b44652020-12-21 12:29:12 -08001// Copyright 2020 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 implementations for android_app_import and android_test_import.
18
19import (
20 "reflect"
21
22 "github.com/google/blueprint/proptools"
23
24 "android/soong/android"
25)
26
27func init() {
28 RegisterAppImportBuildComponents(android.InitRegistrationContext)
29
30 initAndroidAppImportVariantGroupTypes()
31}
32
33func RegisterAppImportBuildComponents(ctx android.RegistrationContext) {
34 ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
35 ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
36}
37
38type AndroidAppImport struct {
39 android.ModuleBase
40 android.DefaultableModuleBase
41 android.ApexModuleBase
42 prebuilt android.Prebuilt
43
44 properties AndroidAppImportProperties
45 dpiVariants interface{}
46 archVariants interface{}
47
48 outputFile android.Path
49 certificate Certificate
50
51 dexpreopter
52
53 usesLibrary usesLibrary
54
55 preprocessed bool
56
57 installPath android.InstallPath
58
59 hideApexVariantFromMake bool
60}
61
62type AndroidAppImportProperties struct {
63 // A prebuilt apk to import
Jooyung Hanf05ca9c2021-06-28 21:48:51 +090064 Apk *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -080065
66 // The name of a certificate in the default certificate directory or an android_app_certificate
67 // module name in the form ":module". Should be empty if presigned or default_dev_cert is set.
68 Certificate *string
69
Jaewoong Jung25ae8de2021-03-08 17:37:46 -080070 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
71 Additional_certificates []string
72
Jaewoong Jungf9b44652020-12-21 12:29:12 -080073 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
74 // be set for presigned modules.
75 Presigned *bool
76
Jaewoong Jung1c1b6e62021-03-09 15:02:31 -080077 // Name of the signing certificate lineage file or filegroup module.
78 Lineage *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -080079
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -040080 // For overriding the --rotation-min-sdk-version property of apksig
81 RotationMinSdkVersion *string
82
Jaewoong Jungf9b44652020-12-21 12:29:12 -080083 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
84 // need to either specify a specific certificate or be presigned.
85 Default_dev_cert *bool
86
87 // Specifies that this app should be installed to the priv-app directory,
88 // where the system will grant it additional privileges not available to
89 // normal apps.
90 Privileged *bool
91
92 // Names of modules to be overridden. Listed modules can only be other binaries
93 // (in Make or Soong).
94 // This does not completely prevent installation of the overridden binaries, but if both
95 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
96 // from PRODUCT_PACKAGES.
97 Overrides []string
98
99 // Optional name for the installed app. If unspecified, it is derived from the module name.
100 Filename *string
Bill Peckhama036da92021-01-08 16:09:09 -0800101
102 // If set, create package-export.apk, which other packages can
103 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
104 Export_package_resources *bool
Spandan Dasd1fac642021-05-18 17:01:41 +0000105
106 // Optional. Install to a subdirectory of the default install path for the module
107 Relative_install_path *string
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800108}
109
110func (a *AndroidAppImport) IsInstallable() bool {
111 return true
112}
113
114// Updates properties with variant-specific values.
115func (a *AndroidAppImport) processVariants(ctx android.LoadHookContext) {
116 config := ctx.Config()
117
118 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
119 // Try DPI variant matches in the reverse-priority order so that the highest priority match
120 // overwrites everything else.
121 // TODO(jungjw): Can we optimize this by making it priority order?
122 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
123 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
124 }
125 if config.ProductAAPTPreferredConfig() != "" {
126 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
127 }
128
129 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName("Arch")
130 archType := ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType
131 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
132
133 if String(a.properties.Apk) == "" {
134 // Disable this module since the apk property is still empty after processing all matching
135 // variants. This likely means there is no matching variant, and the default variant doesn't
136 // have an apk property value either.
137 a.Disable()
138 }
139}
140
141func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
142 dst interface{}, variantGroup reflect.Value, variant string) {
143 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
144 if !src.IsValid() {
145 return
146 }
147
148 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
149 if err != nil {
150 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
151 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
152 } else {
153 panic(err)
154 }
155 }
156}
157
Bill Peckhama036da92021-01-08 16:09:09 -0800158func (a *AndroidAppImport) isPrebuiltFrameworkRes() bool {
159 return a.Name() == "prebuilt_framework-res"
160}
161
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800162func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
163 cert := android.SrcIsModule(String(a.properties.Certificate))
164 if cert != "" {
165 ctx.AddDependency(ctx.Module(), certificateTag, cert)
166 }
167
Jaewoong Jung25ae8de2021-03-08 17:37:46 -0800168 for _, cert := range a.properties.Additional_certificates {
169 cert = android.SrcIsModule(cert)
170 if cert != "" {
171 ctx.AddDependency(ctx.Module(), certificateTag, cert)
172 } else {
173 ctx.PropertyErrorf("additional_certificates",
174 `must be names of android_app_certificate modules in the form ":module"`)
175 }
176 }
177
Bill Peckhama036da92021-01-08 16:09:09 -0800178 a.usesLibrary.deps(ctx, !a.isPrebuiltFrameworkRes())
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800179}
180
181func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
182 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
183 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
184 // with them may invalidate pre-existing signature data.
185 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || a.preprocessed) {
186 ctx.Build(pctx, android.BuildParams{
187 Rule: android.Cp,
188 Output: outputPath,
189 Input: inputPath,
190 })
191 return
192 }
193 rule := android.NewRuleBuilder(pctx, ctx)
194 rule.Command().
195 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
196 BuiltTool("zip2zip").
197 FlagWithInput("-i ", inputPath).
198 FlagWithOutput("-o ", outputPath).
199 FlagWithArg("-0 ", "'lib/**/*.so'").
200 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
201 rule.Build("uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
202}
203
204// Returns whether this module should have the dex file stored uncompressed in the APK.
205func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
206 if ctx.Config().UnbundledBuild() || a.preprocessed {
207 return false
208 }
209
Ulya Trafimovich0061c0d2021-09-01 15:40:38 +0100210 // Uncompress dex in APKs of priv-apps if and only if DONT_UNCOMPRESS_PRIV_APPS_DEXS is false.
211 if a.Privileged() {
212 return ctx.Config().UncompressPrivAppDex()
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800213 }
214
215 return shouldUncompressDex(ctx, &a.dexpreopter)
216}
217
218func (a *AndroidAppImport) uncompressDex(
219 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
220 rule := android.NewRuleBuilder(pctx, ctx)
221 rule.Command().
222 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
223 BuiltTool("zip2zip").
224 FlagWithInput("-i ", inputPath).
225 FlagWithOutput("-o ", outputPath).
226 FlagWithArg("-0 ", "'classes*.dex'").
227 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
228 rule.Build("uncompress-dex", "Uncompress dex files")
229}
230
231func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
232 a.generateAndroidBuildActions(ctx)
233}
234
235func (a *AndroidAppImport) InstallApkName() string {
236 return a.BaseModuleName()
237}
238
239func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
240 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
241 if !apexInfo.IsForPlatform() {
242 a.hideApexVariantFromMake = true
243 }
244
245 numCertPropsSet := 0
246 if String(a.properties.Certificate) != "" {
247 numCertPropsSet++
248 }
249 if Bool(a.properties.Presigned) {
250 numCertPropsSet++
251 }
252 if Bool(a.properties.Default_dev_cert) {
253 numCertPropsSet++
254 }
255 if numCertPropsSet != 1 {
256 ctx.ModuleErrorf("One and only one of certficate, presigned, and default_dev_cert properties must be set")
257 }
258
259 _, certificates := collectAppDeps(ctx, a, false, false)
260
261 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
262 // TODO: LOCAL_PACKAGE_SPLITS
263
264 srcApk := a.prebuilt.SingleSourcePath(ctx)
265
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800266 // TODO: Install or embed JNI libraries
267
268 // Uncompress JNI libraries in the apk
269 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
270 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
271
Spandan Dasd1fac642021-05-18 17:01:41 +0000272 var pathFragments []string
273 relInstallPath := String(a.properties.Relative_install_path)
Bill Peckhama036da92021-01-08 16:09:09 -0800274
275 if a.isPrebuiltFrameworkRes() {
276 // framework-res.apk is installed as system/framework/framework-res.apk
Spandan Dasd1fac642021-05-18 17:01:41 +0000277 if relInstallPath != "" {
278 ctx.PropertyErrorf("relative_install_path", "Relative_install_path cannot be set for framework-res")
279 }
280 pathFragments = []string{"framework"}
Bill Peckhama036da92021-01-08 16:09:09 -0800281 a.preprocessed = true
282 } else if Bool(a.properties.Privileged) {
Spandan Dasd1fac642021-05-18 17:01:41 +0000283 pathFragments = []string{"priv-app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800284 } else if ctx.InstallInTestcases() {
Spandan Dasd1fac642021-05-18 17:01:41 +0000285 pathFragments = []string{relInstallPath, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800286 } else {
Spandan Dasd1fac642021-05-18 17:01:41 +0000287 pathFragments = []string{"app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800288 }
289
Spandan Dasd1fac642021-05-18 17:01:41 +0000290 installDir := android.PathForModuleInstall(ctx, pathFragments...)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000291 a.dexpreopter.isApp = true
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800292 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
293 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
294 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
295
296 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
297 a.dexpreopter.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
298
Ulya Trafimovichfe927a22021-02-26 14:36:48 +0000299 if a.usesLibrary.enforceUsesLibraries() {
300 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
301 }
302
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800303 a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
304 if a.dexpreopter.uncompressedDex {
305 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
306 a.uncompressDex(ctx, jnisUncompressed, dexUncompressed.OutputPath)
307 jnisUncompressed = dexUncompressed
308 }
309
310 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
311
312 // TODO: Handle EXTERNAL
313
314 // Sign or align the package if package has not been preprocessed
Bill Peckhama036da92021-01-08 16:09:09 -0800315
316 if a.isPrebuiltFrameworkRes() {
317 a.outputFile = srcApk
318 certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
319 if len(certificates) != 1 {
320 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
321 }
322 a.certificate = certificates[0]
323 } else if a.preprocessed {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800324 a.outputFile = srcApk
325 a.certificate = PresignedCertificate
326 } else if !Bool(a.properties.Presigned) {
327 // If the certificate property is empty at this point, default_dev_cert must be set to true.
328 // Which makes processMainCert's behavior for the empty cert string WAI.
329 certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800330 a.certificate = certificates[0]
331 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
332 var lineageFile android.Path
333 if lineage := String(a.properties.Lineage); lineage != "" {
334 lineageFile = android.PathForModuleSrc(ctx, lineage)
335 }
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -0400336
337 rotationMinSdkVersion := String(a.properties.RotationMinSdkVersion)
338
339 SignAppPackage(ctx, signed, jnisUncompressed, certificates, nil, lineageFile, rotationMinSdkVersion)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800340 a.outputFile = signed
341 } else {
342 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
343 TransformZipAlign(ctx, alignedApk, jnisUncompressed)
344 a.outputFile = alignedApk
345 a.certificate = PresignedCertificate
346 }
347
348 // TODO: Optionally compress the output apk.
349
350 if apexInfo.IsForPlatform() {
351 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
352 }
353
354 // TODO: androidmk converter jni libs
355}
356
357func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
358 return &a.prebuilt
359}
360
361func (a *AndroidAppImport) Name() string {
362 return a.prebuilt.Name(a.ModuleBase.Name())
363}
364
365func (a *AndroidAppImport) OutputFile() android.Path {
366 return a.outputFile
367}
368
369func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
370 return nil
371}
372
373func (a *AndroidAppImport) Certificate() Certificate {
374 return a.certificate
375}
376
377var dpiVariantGroupType reflect.Type
378var archVariantGroupType reflect.Type
379var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
380
381func initAndroidAppImportVariantGroupTypes() {
382 dpiVariantGroupType = createVariantGroupType(supportedDpis, "Dpi_variants")
383
384 archNames := make([]string, len(android.ArchTypeList()))
385 for i, archType := range android.ArchTypeList() {
386 archNames[i] = archType.Name
387 }
388 archVariantGroupType = createVariantGroupType(archNames, "Arch")
389}
390
391// Populates all variant struct properties at creation time.
392func (a *AndroidAppImport) populateAllVariantStructs() {
393 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
394 a.AddProperties(a.dpiVariants)
395
396 a.archVariants = reflect.New(archVariantGroupType).Interface()
397 a.AddProperties(a.archVariants)
398}
399
400func (a *AndroidAppImport) Privileged() bool {
401 return Bool(a.properties.Privileged)
402}
403
404func (a *AndroidAppImport) DepIsInSameApex(_ android.BaseModuleContext, _ android.Module) bool {
405 // android_app_import might have extra dependencies via uses_libs property.
406 // Don't track the dependency as we don't automatically add those libraries
407 // to the classpath. It should be explicitly added to java_libs property of APEX
408 return false
409}
410
Jiyong Park92315372021-04-02 08:45:46 +0900411func (a *AndroidAppImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
412 return android.SdkSpecPrivate
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800413}
414
Jiyong Park92315372021-04-02 08:45:46 +0900415func (a *AndroidAppImport) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
416 return android.SdkSpecPrivate
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800417}
418
Colin Cross8355c152021-08-10 19:24:07 -0700419func (a *AndroidAppImport) LintDepSets() LintDepSets {
420 return LintDepSets{}
421}
422
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800423var _ android.ApexModule = (*AndroidAppImport)(nil)
424
425// Implements android.ApexModule
426func (j *AndroidAppImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
427 sdkVersion android.ApiLevel) error {
428 // Do not check for prebuilts against the min_sdk_version of enclosing APEX
429 return nil
430}
431
432func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
433 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
434
435 variantFields := make([]reflect.StructField, len(variants))
436 for i, variant := range variants {
437 variantFields[i] = reflect.StructField{
438 Name: proptools.FieldNameForProperty(variant),
439 Type: props,
440 }
441 }
442
443 variantGroupStruct := reflect.StructOf(variantFields)
444 return reflect.StructOf([]reflect.StructField{
445 {
446 Name: variantGroupName,
447 Type: variantGroupStruct,
448 },
449 })
450}
451
452// android_app_import imports a prebuilt apk with additional processing specified in the module.
453// DPI-specific apk source files can be specified using dpi_variants. Example:
454//
455// android_app_import {
456// name: "example_import",
457// apk: "prebuilts/example.apk",
458// dpi_variants: {
459// mdpi: {
460// apk: "prebuilts/example_mdpi.apk",
461// },
462// xhdpi: {
463// apk: "prebuilts/example_xhdpi.apk",
464// },
465// },
466// certificate: "PRESIGNED",
467// }
468func AndroidAppImportFactory() android.Module {
469 module := &AndroidAppImport{}
470 module.AddProperties(&module.properties)
471 module.AddProperties(&module.dexpreoptProperties)
472 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
473 module.populateAllVariantStructs()
474 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
475 module.processVariants(ctx)
476 })
477
478 android.InitApexModule(module)
479 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
480 android.InitDefaultableModule(module)
481 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
482
Ulya Trafimovich22890c42021-01-05 12:04:17 +0000483 module.usesLibrary.enforce = true
484
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800485 return module
486}
487
488type androidTestImportProperties struct {
489 // Whether the prebuilt apk can be installed without additional processing. Default is false.
490 Preprocessed *bool
491}
492
493type AndroidTestImport struct {
494 AndroidAppImport
495
496 testProperties testProperties
497
498 testImportProperties androidTestImportProperties
499
500 data android.Paths
501}
502
503func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
504 a.preprocessed = Bool(a.testImportProperties.Preprocessed)
505
506 a.generateAndroidBuildActions(ctx)
507
508 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
509}
510
511func (a *AndroidTestImport) InstallInTestcases() bool {
512 return true
513}
514
515// android_test_import imports a prebuilt test apk with additional processing specified in the
516// module. DPI or arch variant configurations can be made as with android_app_import.
517func AndroidTestImportFactory() android.Module {
518 module := &AndroidTestImport{}
519 module.AddProperties(&module.properties)
520 module.AddProperties(&module.dexpreoptProperties)
521 module.AddProperties(&module.testProperties)
522 module.AddProperties(&module.testImportProperties)
523 module.populateAllVariantStructs()
524 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
525 module.processVariants(ctx)
526 })
527
528 module.dexpreopter.isTest = true
529
530 android.InitApexModule(module)
531 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
532 android.InitDefaultableModule(module)
533 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
534
535 return module
536}