blob: 2054785f580c47601a5aca0cd3d1b4c94254dcaf [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
64 Apk *string
65
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
70 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
71 // be set for presigned modules.
72 Presigned *bool
73
74 // Name of the signing certificate lineage file.
75 Lineage *string
76
77 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
78 // need to either specify a specific certificate or be presigned.
79 Default_dev_cert *bool
80
81 // Specifies that this app should be installed to the priv-app directory,
82 // where the system will grant it additional privileges not available to
83 // normal apps.
84 Privileged *bool
85
86 // Names of modules to be overridden. Listed modules can only be other binaries
87 // (in Make or Soong).
88 // This does not completely prevent installation of the overridden binaries, but if both
89 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
90 // from PRODUCT_PACKAGES.
91 Overrides []string
92
93 // Optional name for the installed app. If unspecified, it is derived from the module name.
94 Filename *string
95}
96
97func (a *AndroidAppImport) IsInstallable() bool {
98 return true
99}
100
101// Updates properties with variant-specific values.
102func (a *AndroidAppImport) processVariants(ctx android.LoadHookContext) {
103 config := ctx.Config()
104
105 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
106 // Try DPI variant matches in the reverse-priority order so that the highest priority match
107 // overwrites everything else.
108 // TODO(jungjw): Can we optimize this by making it priority order?
109 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
110 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
111 }
112 if config.ProductAAPTPreferredConfig() != "" {
113 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
114 }
115
116 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName("Arch")
117 archType := ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType
118 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
119
120 if String(a.properties.Apk) == "" {
121 // Disable this module since the apk property is still empty after processing all matching
122 // variants. This likely means there is no matching variant, and the default variant doesn't
123 // have an apk property value either.
124 a.Disable()
125 }
126}
127
128func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
129 dst interface{}, variantGroup reflect.Value, variant string) {
130 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
131 if !src.IsValid() {
132 return
133 }
134
135 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
136 if err != nil {
137 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
138 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
139 } else {
140 panic(err)
141 }
142 }
143}
144
145func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
146 cert := android.SrcIsModule(String(a.properties.Certificate))
147 if cert != "" {
148 ctx.AddDependency(ctx.Module(), certificateTag, cert)
149 }
150
151 a.usesLibrary.deps(ctx, true)
152}
153
154func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
155 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
156 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
157 // with them may invalidate pre-existing signature data.
158 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || a.preprocessed) {
159 ctx.Build(pctx, android.BuildParams{
160 Rule: android.Cp,
161 Output: outputPath,
162 Input: inputPath,
163 })
164 return
165 }
166 rule := android.NewRuleBuilder(pctx, ctx)
167 rule.Command().
168 Textf(`if (zipinfo %s 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
169 BuiltTool("zip2zip").
170 FlagWithInput("-i ", inputPath).
171 FlagWithOutput("-o ", outputPath).
172 FlagWithArg("-0 ", "'lib/**/*.so'").
173 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
174 rule.Build("uncompress-embedded-jni-libs", "Uncompress embedded JIN libs")
175}
176
177// Returns whether this module should have the dex file stored uncompressed in the APK.
178func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
179 if ctx.Config().UnbundledBuild() || a.preprocessed {
180 return false
181 }
182
183 // Uncompress dex in APKs of privileged apps
184 if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
185 return true
186 }
187
188 return shouldUncompressDex(ctx, &a.dexpreopter)
189}
190
191func (a *AndroidAppImport) uncompressDex(
192 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
193 rule := android.NewRuleBuilder(pctx, ctx)
194 rule.Command().
195 Textf(`if (zipinfo %s '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then`, inputPath).
196 BuiltTool("zip2zip").
197 FlagWithInput("-i ", inputPath).
198 FlagWithOutput("-o ", outputPath).
199 FlagWithArg("-0 ", "'classes*.dex'").
200 Textf(`; else cp -f %s %s; fi`, inputPath, outputPath)
201 rule.Build("uncompress-dex", "Uncompress dex files")
202}
203
204func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
205 a.generateAndroidBuildActions(ctx)
206}
207
208func (a *AndroidAppImport) InstallApkName() string {
209 return a.BaseModuleName()
210}
211
212func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
213 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
214 if !apexInfo.IsForPlatform() {
215 a.hideApexVariantFromMake = true
216 }
217
218 numCertPropsSet := 0
219 if String(a.properties.Certificate) != "" {
220 numCertPropsSet++
221 }
222 if Bool(a.properties.Presigned) {
223 numCertPropsSet++
224 }
225 if Bool(a.properties.Default_dev_cert) {
226 numCertPropsSet++
227 }
228 if numCertPropsSet != 1 {
229 ctx.ModuleErrorf("One and only one of certficate, presigned, and default_dev_cert properties must be set")
230 }
231
232 _, certificates := collectAppDeps(ctx, a, false, false)
233
234 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
235 // TODO: LOCAL_PACKAGE_SPLITS
236
237 srcApk := a.prebuilt.SingleSourcePath(ctx)
238
239 if a.usesLibrary.enforceUsesLibraries() {
240 srcApk = a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
241 }
242
243 // TODO: Install or embed JNI libraries
244
245 // Uncompress JNI libraries in the apk
246 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
247 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
248
249 var installDir android.InstallPath
250 if Bool(a.properties.Privileged) {
251 installDir = android.PathForModuleInstall(ctx, "priv-app", a.BaseModuleName())
252 } else if ctx.InstallInTestcases() {
253 installDir = android.PathForModuleInstall(ctx, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch())
254 } else {
255 installDir = android.PathForModuleInstall(ctx, "app", a.BaseModuleName())
256 }
257
258 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
259 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
260 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
261
262 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
263 a.dexpreopter.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
264
265 a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
266 if a.dexpreopter.uncompressedDex {
267 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
268 a.uncompressDex(ctx, jnisUncompressed, dexUncompressed.OutputPath)
269 jnisUncompressed = dexUncompressed
270 }
271
272 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
273
274 // TODO: Handle EXTERNAL
275
276 // Sign or align the package if package has not been preprocessed
277 if a.preprocessed {
278 a.outputFile = srcApk
279 a.certificate = PresignedCertificate
280 } else if !Bool(a.properties.Presigned) {
281 // If the certificate property is empty at this point, default_dev_cert must be set to true.
282 // Which makes processMainCert's behavior for the empty cert string WAI.
283 certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
284 if len(certificates) != 1 {
285 ctx.ModuleErrorf("Unexpected number of certificates were extracted: %q", certificates)
286 }
287 a.certificate = certificates[0]
288 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
289 var lineageFile android.Path
290 if lineage := String(a.properties.Lineage); lineage != "" {
291 lineageFile = android.PathForModuleSrc(ctx, lineage)
292 }
293 SignAppPackage(ctx, signed, jnisUncompressed, certificates, nil, lineageFile)
294 a.outputFile = signed
295 } else {
296 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
297 TransformZipAlign(ctx, alignedApk, jnisUncompressed)
298 a.outputFile = alignedApk
299 a.certificate = PresignedCertificate
300 }
301
302 // TODO: Optionally compress the output apk.
303
304 if apexInfo.IsForPlatform() {
305 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
306 }
307
308 // TODO: androidmk converter jni libs
309}
310
311func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
312 return &a.prebuilt
313}
314
315func (a *AndroidAppImport) Name() string {
316 return a.prebuilt.Name(a.ModuleBase.Name())
317}
318
319func (a *AndroidAppImport) OutputFile() android.Path {
320 return a.outputFile
321}
322
323func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
324 return nil
325}
326
327func (a *AndroidAppImport) Certificate() Certificate {
328 return a.certificate
329}
330
331var dpiVariantGroupType reflect.Type
332var archVariantGroupType reflect.Type
333var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
334
335func initAndroidAppImportVariantGroupTypes() {
336 dpiVariantGroupType = createVariantGroupType(supportedDpis, "Dpi_variants")
337
338 archNames := make([]string, len(android.ArchTypeList()))
339 for i, archType := range android.ArchTypeList() {
340 archNames[i] = archType.Name
341 }
342 archVariantGroupType = createVariantGroupType(archNames, "Arch")
343}
344
345// Populates all variant struct properties at creation time.
346func (a *AndroidAppImport) populateAllVariantStructs() {
347 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
348 a.AddProperties(a.dpiVariants)
349
350 a.archVariants = reflect.New(archVariantGroupType).Interface()
351 a.AddProperties(a.archVariants)
352}
353
354func (a *AndroidAppImport) Privileged() bool {
355 return Bool(a.properties.Privileged)
356}
357
358func (a *AndroidAppImport) DepIsInSameApex(_ android.BaseModuleContext, _ android.Module) bool {
359 // android_app_import might have extra dependencies via uses_libs property.
360 // Don't track the dependency as we don't automatically add those libraries
361 // to the classpath. It should be explicitly added to java_libs property of APEX
362 return false
363}
364
365func (a *AndroidAppImport) sdkVersion() sdkSpec {
366 return sdkSpecFrom("")
367}
368
369func (a *AndroidAppImport) minSdkVersion() sdkSpec {
370 return sdkSpecFrom("")
371}
372
373var _ android.ApexModule = (*AndroidAppImport)(nil)
374
375// Implements android.ApexModule
376func (j *AndroidAppImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
377 sdkVersion android.ApiLevel) error {
378 // Do not check for prebuilts against the min_sdk_version of enclosing APEX
379 return nil
380}
381
382func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
383 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
384
385 variantFields := make([]reflect.StructField, len(variants))
386 for i, variant := range variants {
387 variantFields[i] = reflect.StructField{
388 Name: proptools.FieldNameForProperty(variant),
389 Type: props,
390 }
391 }
392
393 variantGroupStruct := reflect.StructOf(variantFields)
394 return reflect.StructOf([]reflect.StructField{
395 {
396 Name: variantGroupName,
397 Type: variantGroupStruct,
398 },
399 })
400}
401
402// android_app_import imports a prebuilt apk with additional processing specified in the module.
403// DPI-specific apk source files can be specified using dpi_variants. Example:
404//
405// android_app_import {
406// name: "example_import",
407// apk: "prebuilts/example.apk",
408// dpi_variants: {
409// mdpi: {
410// apk: "prebuilts/example_mdpi.apk",
411// },
412// xhdpi: {
413// apk: "prebuilts/example_xhdpi.apk",
414// },
415// },
416// certificate: "PRESIGNED",
417// }
418func AndroidAppImportFactory() android.Module {
419 module := &AndroidAppImport{}
420 module.AddProperties(&module.properties)
421 module.AddProperties(&module.dexpreoptProperties)
422 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
423 module.populateAllVariantStructs()
424 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
425 module.processVariants(ctx)
426 })
427
428 android.InitApexModule(module)
429 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
430 android.InitDefaultableModule(module)
431 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
432
433 return module
434}
435
436type androidTestImportProperties struct {
437 // Whether the prebuilt apk can be installed without additional processing. Default is false.
438 Preprocessed *bool
439}
440
441type AndroidTestImport struct {
442 AndroidAppImport
443
444 testProperties testProperties
445
446 testImportProperties androidTestImportProperties
447
448 data android.Paths
449}
450
451func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
452 a.preprocessed = Bool(a.testImportProperties.Preprocessed)
453
454 a.generateAndroidBuildActions(ctx)
455
456 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
457}
458
459func (a *AndroidTestImport) InstallInTestcases() bool {
460 return true
461}
462
463// android_test_import imports a prebuilt test apk with additional processing specified in the
464// module. DPI or arch variant configurations can be made as with android_app_import.
465func AndroidTestImportFactory() android.Module {
466 module := &AndroidTestImport{}
467 module.AddProperties(&module.properties)
468 module.AddProperties(&module.dexpreoptProperties)
469 module.AddProperties(&module.testProperties)
470 module.AddProperties(&module.testImportProperties)
471 module.populateAllVariantStructs()
472 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
473 module.processVariants(ctx)
474 })
475
476 module.dexpreopter.isTest = true
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
483 return module
484}