blob: 35a054fa070da0de930cb2791f23aab0583eb5f5 [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"
Cole Faust9c5c09f2023-09-06 16:11:44 -070021 "strings"
Jaewoong Jungf9b44652020-12-21 12:29:12 -080022
Cole Faustd5806132023-04-13 15:43:53 -070023 "github.com/google/blueprint"
24
Jaewoong Jungf9b44652020-12-21 12:29:12 -080025 "github.com/google/blueprint/proptools"
26
27 "android/soong/android"
Wei Li340ee8e2022-03-18 17:33:24 -070028 "android/soong/provenance"
Jaewoong Jungf9b44652020-12-21 12:29:12 -080029)
30
31func init() {
32 RegisterAppImportBuildComponents(android.InitRegistrationContext)
33
34 initAndroidAppImportVariantGroupTypes()
35}
36
Cole Faust4ec178c2023-01-13 12:03:38 -080037var (
38 uncompressEmbeddedJniLibsRule = pctx.AndroidStaticRule("uncompress-embedded-jni-libs", blueprint.RuleParams{
39 Command: `if (zipinfo $in 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then ` +
40 `${config.Zip2ZipCmd} -i $in -o $out -0 'lib/**/*.so'` +
41 `; else cp -f $in $out; fi`,
42 CommandDeps: []string{"${config.Zip2ZipCmd}"},
43 Description: "Uncompress embedded JNI libs",
44 })
45
Jim Tang6c4ecd02024-12-17 22:06:12 +080046 stripEmbeddedJniLibsUnusedArchRule = pctx.AndroidStaticRule("strip-embedded-jni-libs-from-unused-arch", blueprint.RuleParams{
47 Command: `${config.Zip2ZipCmd} -i $in -o $out -x 'lib/**/*.so' $extraArgs`,
48 CommandDeps: []string{"${config.Zip2ZipCmd}"},
49 Description: "Remove all JNI libs from unused architectures",
50 }, "extraArgs")
51
Cole Faust4ec178c2023-01-13 12:03:38 -080052 uncompressDexRule = pctx.AndroidStaticRule("uncompress-dex", blueprint.RuleParams{
53 Command: `if (zipinfo $in '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then ` +
54 `${config.Zip2ZipCmd} -i $in -o $out -0 'classes*.dex'` +
55 `; else cp -f $in $out; fi`,
56 CommandDeps: []string{"${config.Zip2ZipCmd}"},
57 Description: "Uncompress dex files",
58 })
Cole Faust2f1da162023-04-17 15:06:56 -070059
Cole Faust9c5c09f2023-09-06 16:11:44 -070060 checkPresignedApkRule = pctx.AndroidStaticRule("check-presigned-apk", blueprint.RuleParams{
61 Command: "build/soong/scripts/check_prebuilt_presigned_apk.py --aapt2 ${config.Aapt2Cmd} --zipalign ${config.ZipAlign} $extraArgs $in $out",
62 CommandDeps: []string{"build/soong/scripts/check_prebuilt_presigned_apk.py", "${config.Aapt2Cmd}", "${config.ZipAlign}"},
63 Description: "Check presigned apk",
64 }, "extraArgs")
Cole Faust4ec178c2023-01-13 12:03:38 -080065)
66
Jaewoong Jungf9b44652020-12-21 12:29:12 -080067func RegisterAppImportBuildComponents(ctx android.RegistrationContext) {
68 ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
69 ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
Cole Faustc71b1752024-10-14 12:14:54 -070070 ctx.PreArchMutators(func(ctx android.RegisterMutatorsContext) {
71 ctx.BottomUp("disable_prebuilts_without_apk", disablePrebuiltsWithoutApkMutator)
72 })
Jaewoong Jungf9b44652020-12-21 12:29:12 -080073}
74
75type AndroidAppImport struct {
76 android.ModuleBase
77 android.DefaultableModuleBase
78 android.ApexModuleBase
79 prebuilt android.Prebuilt
80
Herbert Xue04354ae2024-01-29 13:57:51 +080081 properties AndroidAppImportProperties
82 dpiVariants interface{}
83 archVariants interface{}
84 arch_dpiVariants interface{}
Jaewoong Jungf9b44652020-12-21 12:29:12 -080085
86 outputFile android.Path
87 certificate Certificate
88
89 dexpreopter
90
91 usesLibrary usesLibrary
92
Jaewoong Jungf9b44652020-12-21 12:29:12 -080093 installPath android.InstallPath
94
95 hideApexVariantFromMake bool
Wei Li340ee8e2022-03-18 17:33:24 -070096
Cole Faust4e9f5922024-11-13 16:09:23 -080097 provenanceMetaDataFile android.Path
Jaewoong Jungf9b44652020-12-21 12:29:12 -080098}
99
100type AndroidAppImportProperties struct {
101 // A prebuilt apk to import
Cole Faustc71b1752024-10-14 12:14:54 -0700102 Apk proptools.Configurable[string] `android:"path,replace_instead_of_append"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800103
104 // The name of a certificate in the default certificate directory or an android_app_certificate
105 // module name in the form ":module". Should be empty if presigned or default_dev_cert is set.
Cole Fausteb9c1482024-11-18 16:49:19 -0800106 Certificate proptools.Configurable[string] `android:"replace_instead_of_append"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800107
Jaewoong Jung25ae8de2021-03-08 17:37:46 -0800108 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
109 Additional_certificates []string
110
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800111 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
112 // be set for presigned modules.
113 Presigned *bool
114
Jaewoong Jung1c1b6e62021-03-09 15:02:31 -0800115 // Name of the signing certificate lineage file or filegroup module.
116 Lineage *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800117
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -0400118 // For overriding the --rotation-min-sdk-version property of apksig
119 RotationMinSdkVersion *string
120
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800121 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
122 // need to either specify a specific certificate or be presigned.
123 Default_dev_cert *bool
124
125 // Specifies that this app should be installed to the priv-app directory,
126 // where the system will grant it additional privileges not available to
127 // normal apps.
128 Privileged *bool
129
130 // Names of modules to be overridden. Listed modules can only be other binaries
131 // (in Make or Soong).
132 // This does not completely prevent installation of the overridden binaries, but if both
133 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
134 // from PRODUCT_PACKAGES.
135 Overrides []string
136
137 // Optional name for the installed app. If unspecified, it is derived from the module name.
138 Filename *string
Bill Peckhama036da92021-01-08 16:09:09 -0800139
140 // If set, create package-export.apk, which other packages can
141 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
142 Export_package_resources *bool
Spandan Dasd1fac642021-05-18 17:01:41 +0000143
144 // Optional. Install to a subdirectory of the default install path for the module
145 Relative_install_path *string
Cole Faust2f1da162023-04-17 15:06:56 -0700146
147 // Whether the prebuilt apk can be installed without additional processing. Default is false.
148 Preprocessed *bool
149
150 // Whether or not to skip checking the preprocessed apk for proper alignment and uncompressed
151 // JNI libs and dex files. Default is false
152 Skip_preprocessed_apk_checks *bool
Spandan Dasefa14652024-02-27 18:19:16 +0000153
154 // Name of the source soong module that gets shadowed by this prebuilt
155 // If unspecified, follows the naming convention that the source module of
156 // the prebuilt is Name() without "prebuilt_" prefix
157 Source_module_name *string
Spandan Das3490dfd2024-03-11 21:37:25 +0000158
Jim Tang6c4ecd02024-12-17 22:06:12 +0800159 // Whether stripping all libraries from unused architectures.
160 Strip_unused_jni_arch *bool
161
Spandan Das3490dfd2024-03-11 21:37:25 +0000162 // Path to the .prebuilt_info file of the prebuilt app.
163 // In case of mainline modules, the .prebuilt_info file contains the build_id that was used
164 // to generate the prebuilt.
165 Prebuilt_info *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800166}
167
168func (a *AndroidAppImport) IsInstallable() bool {
169 return true
170}
171
172// Updates properties with variant-specific values.
Cole Faust97494b12024-01-12 14:02:47 -0800173// This happens as a DefaultableHook instead of a LoadHook because we want to run it after
174// soong config variables are applied.
175func (a *AndroidAppImport) processVariants(ctx android.DefaultableHookContext) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800176 config := ctx.Config()
Herbert Xue04354ae2024-01-29 13:57:51 +0800177 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName(DpiGroupName)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800178
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800179 // Try DPI variant matches in the reverse-priority order so that the highest priority match
180 // overwrites everything else.
181 // TODO(jungjw): Can we optimize this by making it priority order?
182 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
183 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
184 }
185 if config.ProductAAPTPreferredConfig() != "" {
186 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
187 }
Herbert Xue04354ae2024-01-29 13:57:51 +0800188 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName(ArchGroupName)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800189 archType := ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType
190 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
191
Herbert Xue04354ae2024-01-29 13:57:51 +0800192 // Process "arch" includes "dpi_variants"
193 archStructPtr := reflect.ValueOf(a.arch_dpiVariants).Elem().FieldByName(ArchGroupName)
194 if archStruct := archStructPtr.Elem(); archStruct.IsValid() {
195 archPartPropsPtr := archStruct.FieldByName(proptools.FieldNameForProperty(archType.Name))
196 if archPartProps := archPartPropsPtr.Elem(); archPartProps.IsValid() {
197 archDpiPropsPtr := archPartProps.FieldByName(DpiGroupName)
198 if archDpiProps := archDpiPropsPtr.Elem(); archDpiProps.IsValid() {
199 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
200 MergePropertiesFromVariant(ctx, &a.properties, archDpiProps, config.ProductAAPTPrebuiltDPI()[i])
201 }
202 if config.ProductAAPTPreferredConfig() != "" {
203 MergePropertiesFromVariant(ctx, &a.properties, archDpiProps, config.ProductAAPTPreferredConfig())
204 }
205 }
206 }
207 }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800208}
209
210func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
211 dst interface{}, variantGroup reflect.Value, variant string) {
212 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
213 if !src.IsValid() {
214 return
215 }
216
217 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
218 if err != nil {
219 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
220 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
221 } else {
222 panic(err)
223 }
224 }
225}
226
Cole Faustc71b1752024-10-14 12:14:54 -0700227// disablePrebuiltsWithoutApkMutator is a pre-arch mutator that disables AndroidAppImport or
228// AndroidTestImport modules that don't have an apk set. We need this separate mutator instead
229// of doing it in processVariants because processVariants is a defaultable hook, and configurable
230// properties can only be evaluated after the defaults (and eventually, base configurabtion)
231// mutators.
232func disablePrebuiltsWithoutApkMutator(ctx android.BottomUpMutatorContext) {
233 switch a := ctx.Module().(type) {
234 case *AndroidAppImport:
235 if a.properties.Apk.GetOrDefault(ctx, "") == "" {
236 // Disable this module since the apk property is still empty after processing all
237 // matching variants. This likely means there is no matching variant, and the default
238 // variant doesn't have an apk property value either.
239 a.Disable()
240 }
241 case *AndroidTestImport:
242 if a.properties.Apk.GetOrDefault(ctx, "") == "" {
243 // Disable this module since the apk property is still empty after processing all
244 // matching variants. This likely means there is no matching variant, and the default
245 // variant doesn't have an apk property value either.
246 a.Disable()
247 }
248 }
249}
250
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800251func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
Cole Fausteb9c1482024-11-18 16:49:19 -0800252 cert := android.SrcIsModule(a.properties.Certificate.GetOrDefault(ctx, ""))
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800253 if cert != "" {
254 ctx.AddDependency(ctx.Module(), certificateTag, cert)
255 }
256
Jaewoong Jung25ae8de2021-03-08 17:37:46 -0800257 for _, cert := range a.properties.Additional_certificates {
258 cert = android.SrcIsModule(cert)
259 if cert != "" {
260 ctx.AddDependency(ctx.Module(), certificateTag, cert)
261 } else {
262 ctx.PropertyErrorf("additional_certificates",
263 `must be names of android_app_certificate modules in the form ":module"`)
264 }
265 }
266
Cole Faustd5806132023-04-13 15:43:53 -0700267 a.usesLibrary.deps(ctx, true)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800268}
269
270func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
Cole Faust4e9f5922024-11-13 16:09:23 -0800271 ctx android.ModuleContext, inputPath android.Path, outputPath android.WritablePath) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800272 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
273 // with them may invalidate pre-existing signature data.
Cole Faust2f1da162023-04-17 15:06:56 -0700274 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || Bool(a.properties.Preprocessed)) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800275 ctx.Build(pctx, android.BuildParams{
276 Rule: android.Cp,
277 Output: outputPath,
278 Input: inputPath,
279 })
280 return
281 }
Cole Faust4ec178c2023-01-13 12:03:38 -0800282
283 ctx.Build(pctx, android.BuildParams{
284 Rule: uncompressEmbeddedJniLibsRule,
285 Input: inputPath,
286 Output: outputPath,
287 })
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800288}
289
290// Returns whether this module should have the dex file stored uncompressed in the APK.
291func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
Cole Faust2f1da162023-04-17 15:06:56 -0700292 if ctx.Config().UnbundledBuild() || proptools.Bool(a.properties.Preprocessed) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800293 return false
294 }
295
Ulya Trafimovich0061c0d2021-09-01 15:40:38 +0100296 // Uncompress dex in APKs of priv-apps if and only if DONT_UNCOMPRESS_PRIV_APPS_DEXS is false.
297 if a.Privileged() {
298 return ctx.Config().UncompressPrivAppDex()
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800299 }
300
Spandan Dase21a8d42024-01-23 23:56:29 +0000301 return shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &a.dexpreopter)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800302}
303
Jim Tang6c4ecd02024-12-17 22:06:12 +0800304func (a *AndroidAppImport) stripEmbeddedJniLibsUnusedArch(
305 ctx android.ModuleContext, inputPath android.Path, outputPath android.WritablePath) {
306 var wantedJniLibSlice []string
307 for _, target := range ctx.MultiTargets() {
308 supported_abis := target.Arch.Abi
309 for _, arch := range supported_abis {
310 wantedJniLibSlice = append(wantedJniLibSlice, " -X lib/"+arch+"/*.so")
311 }
312 }
313 wantedJniLibString := strings.Join(wantedJniLibSlice, " ")
314 ctx.Build(pctx, android.BuildParams{
315 Rule: stripEmbeddedJniLibsUnusedArchRule,
316 Input: inputPath,
317 Output: outputPath,
318 Args: map[string]string{
319 "extraArgs": wantedJniLibString,
320 },
321 })
322}
323
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800324func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
325 a.generateAndroidBuildActions(ctx)
326}
327
328func (a *AndroidAppImport) InstallApkName() string {
329 return a.BaseModuleName()
330}
331
Spandan Dasefa14652024-02-27 18:19:16 +0000332func (a *AndroidAppImport) BaseModuleName() string {
333 return proptools.StringDefault(a.properties.Source_module_name, a.ModuleBase.Name())
334}
335
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800336func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faustd5806132023-04-13 15:43:53 -0700337 if a.Name() == "prebuilt_framework-res" {
338 ctx.ModuleErrorf("prebuilt_framework-res found. This used to have special handling in soong, but was removed due to prebuilt_framework-res no longer existing. This check is to ensure it doesn't come back without readding the special handling.")
339 }
340
Colin Crossff694a82023-12-13 15:54:49 -0800341 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800342 if !apexInfo.IsForPlatform() {
343 a.hideApexVariantFromMake = true
344 }
345
Cole Faust61585282023-07-14 16:23:39 -0700346 if Bool(a.properties.Preprocessed) {
347 if a.properties.Presigned != nil && !*a.properties.Presigned {
348 ctx.ModuleErrorf("Setting preprocessed: true implies presigned: true, so you cannot set presigned to false")
349 }
350 t := true
351 a.properties.Presigned = &t
352 }
353
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800354 numCertPropsSet := 0
Cole Fausteb9c1482024-11-18 16:49:19 -0800355 if a.properties.Certificate.GetOrDefault(ctx, "") != "" {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800356 numCertPropsSet++
357 }
358 if Bool(a.properties.Presigned) {
359 numCertPropsSet++
360 }
361 if Bool(a.properties.Default_dev_cert) {
362 numCertPropsSet++
363 }
364 if numCertPropsSet != 1 {
Cole Faust61585282023-07-14 16:23:39 -0700365 ctx.ModuleErrorf("One and only one of certficate, presigned (implied by preprocessed), and default_dev_cert properties must be set")
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800366 }
367
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800368 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
369 // TODO: LOCAL_PACKAGE_SPLITS
370
371 srcApk := a.prebuilt.SingleSourcePath(ctx)
372
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800373 // TODO: Install or embed JNI libraries
374
375 // Uncompress JNI libraries in the apk
376 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
Cole Faust4e9f5922024-11-13 16:09:23 -0800377 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800378
Jim Tang6c4ecd02024-12-17 22:06:12 +0800379 // Strip all embedded JNI libs and include only required ones accordingly to the module's compile_multilib
380 if Bool(a.properties.Strip_unused_jni_arch) {
381 jnisStripped := android.PathForModuleOut(ctx, "jnis-stripped", ctx.ModuleName()+".apk")
382 a.stripEmbeddedJniLibsUnusedArch(ctx, jnisUncompressed, jnisStripped)
383 jnisUncompressed = jnisStripped
384 }
385
Spandan Dasd1fac642021-05-18 17:01:41 +0000386 var pathFragments []string
387 relInstallPath := String(a.properties.Relative_install_path)
Bill Peckhama036da92021-01-08 16:09:09 -0800388
Cole Faustd5806132023-04-13 15:43:53 -0700389 if Bool(a.properties.Privileged) {
Spandan Dasd1fac642021-05-18 17:01:41 +0000390 pathFragments = []string{"priv-app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800391 } else if ctx.InstallInTestcases() {
Spandan Dasd1fac642021-05-18 17:01:41 +0000392 pathFragments = []string{relInstallPath, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800393 } else {
Spandan Dasd1fac642021-05-18 17:01:41 +0000394 pathFragments = []string{"app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800395 }
396
Spandan Dasd1fac642021-05-18 17:01:41 +0000397 installDir := android.PathForModuleInstall(ctx, pathFragments...)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000398 a.dexpreopter.isApp = true
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800399 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
400 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
401 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
402
Cole Faust64f2d842024-10-17 13:28:34 -0700403 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries(ctx)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800404 a.dexpreopter.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Spandan Das0727ba72024-02-13 16:37:43 +0000405 if a.usesLibrary.shouldDisableDexpreopt {
406 a.dexpreopter.disableDexpreopt()
407 }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800408
Cole Faust64f2d842024-10-17 13:28:34 -0700409 if a.usesLibrary.enforceUsesLibraries(ctx) {
Jiakai Zhangf98da192024-04-15 11:15:41 +0000410 a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk, &a.dexpreopter.classLoaderContexts)
Ulya Trafimovichfe927a22021-02-26 14:36:48 +0000411 }
412
Spandan Dase21a8d42024-01-23 23:56:29 +0000413 a.dexpreopter.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), jnisUncompressed)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800414 if a.dexpreopter.uncompressedDex {
415 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
Cole Faust4ec178c2023-01-13 12:03:38 -0800416 ctx.Build(pctx, android.BuildParams{
417 Rule: uncompressDexRule,
418 Input: jnisUncompressed,
419 Output: dexUncompressed,
420 })
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800421 jnisUncompressed = dexUncompressed
422 }
423
424 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
425
426 // TODO: Handle EXTERNAL
427
428 // Sign or align the package if package has not been preprocessed
Bill Peckhama036da92021-01-08 16:09:09 -0800429
Cole Faust2f1da162023-04-17 15:06:56 -0700430 if proptools.Bool(a.properties.Preprocessed) {
Cole Faust9c5c09f2023-09-06 16:11:44 -0700431 validationStamp := a.validatePresignedApk(ctx, srcApk)
432 output := android.PathForModuleOut(ctx, apkFilename)
433 ctx.Build(pctx, android.BuildParams{
434 Rule: android.Cp,
435 Input: srcApk,
436 Output: output,
437 Validation: validationStamp,
438 })
Cole Faust2f1da162023-04-17 15:06:56 -0700439 a.outputFile = output
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800440 a.certificate = PresignedCertificate
441 } else if !Bool(a.properties.Presigned) {
442 // If the certificate property is empty at this point, default_dev_cert must be set to true.
443 // Which makes processMainCert's behavior for the empty cert string WAI.
Cole Faust61585282023-07-14 16:23:39 -0700444 _, _, certificates := collectAppDeps(ctx, a, false, false)
Cole Fausteb9c1482024-11-18 16:49:19 -0800445 a.certificate, certificates = processMainCert(a.ModuleBase, a.properties.Certificate.GetOrDefault(ctx, ""), certificates, ctx)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800446 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
447 var lineageFile android.Path
448 if lineage := String(a.properties.Lineage); lineage != "" {
449 lineageFile = android.PathForModuleSrc(ctx, lineage)
450 }
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -0400451
452 rotationMinSdkVersion := String(a.properties.RotationMinSdkVersion)
453
454 SignAppPackage(ctx, signed, jnisUncompressed, certificates, nil, lineageFile, rotationMinSdkVersion)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800455 a.outputFile = signed
456 } else {
Cole Faust9c5c09f2023-09-06 16:11:44 -0700457 validationStamp := a.validatePresignedApk(ctx, srcApk)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800458 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
Cole Faust9c5c09f2023-09-06 16:11:44 -0700459 TransformZipAlign(ctx, alignedApk, jnisUncompressed, []android.Path{validationStamp})
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800460 a.outputFile = alignedApk
461 a.certificate = PresignedCertificate
462 }
463
464 // TODO: Optionally compress the output apk.
465
466 if apexInfo.IsForPlatform() {
467 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
Cole Faustc71b1752024-10-14 12:14:54 -0700468 artifactPath := android.PathForModuleSrc(ctx, a.properties.Apk.GetOrDefault(ctx, ""))
Wei Li340ee8e2022-03-18 17:33:24 -0700469 a.provenanceMetaDataFile = provenance.GenerateArtifactProvenanceMetaData(ctx, artifactPath, a.installPath)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800470 }
471
Spandan Das3490dfd2024-03-11 21:37:25 +0000472 providePrebuiltInfo(ctx,
473 prebuiltInfoProps{
474 baseModuleName: a.BaseModuleName(),
475 isPrebuilt: true,
476 prebuiltInfo: a.properties.Prebuilt_info,
477 },
478 )
479
mrziwang68786d82024-07-09 10:41:55 -0700480 ctx.SetOutputFiles([]android.Path{a.outputFile}, "")
481
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800482 // TODO: androidmk converter jni libs
483}
484
Cole Faust9c5c09f2023-09-06 16:11:44 -0700485func (a *AndroidAppImport) validatePresignedApk(ctx android.ModuleContext, srcApk android.Path) android.Path {
486 stamp := android.PathForModuleOut(ctx, "validated-prebuilt", "check.stamp")
487 var extraArgs []string
Cole Faust93b89b42023-07-20 17:31:16 -0700488 if a.Privileged() {
Cole Faust9c5c09f2023-09-06 16:11:44 -0700489 extraArgs = append(extraArgs, "--privileged")
Rashid Zaman3bd28702024-07-23 17:23:05 -0700490 if ctx.Config().UncompressPrivAppDex() {
491 extraArgs = append(extraArgs, "--uncompress-priv-app-dex")
492 }
Cole Faust9c5c09f2023-09-06 16:11:44 -0700493 }
494 if proptools.Bool(a.properties.Skip_preprocessed_apk_checks) {
495 extraArgs = append(extraArgs, "--skip-preprocessed-apk-checks")
496 }
497 if proptools.Bool(a.properties.Preprocessed) {
498 extraArgs = append(extraArgs, "--preprocessed")
Cole Faust93b89b42023-07-20 17:31:16 -0700499 }
500
Cole Faust2f1da162023-04-17 15:06:56 -0700501 ctx.Build(pctx, android.BuildParams{
Cole Faust9c5c09f2023-09-06 16:11:44 -0700502 Rule: checkPresignedApkRule,
Cole Faust61585282023-07-14 16:23:39 -0700503 Input: srcApk,
Cole Faust9c5c09f2023-09-06 16:11:44 -0700504 Output: stamp,
505 Args: map[string]string{
506 "extraArgs": strings.Join(extraArgs, " "),
507 },
Cole Faust61585282023-07-14 16:23:39 -0700508 })
Cole Faust9c5c09f2023-09-06 16:11:44 -0700509 return stamp
Cole Faust61585282023-07-14 16:23:39 -0700510}
511
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800512func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
513 return &a.prebuilt
514}
515
516func (a *AndroidAppImport) Name() string {
517 return a.prebuilt.Name(a.ModuleBase.Name())
518}
519
520func (a *AndroidAppImport) OutputFile() android.Path {
521 return a.outputFile
522}
523
524func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
525 return nil
526}
527
528func (a *AndroidAppImport) Certificate() Certificate {
529 return a.certificate
530}
531
Cole Faust4e9f5922024-11-13 16:09:23 -0800532func (a *AndroidAppImport) ProvenanceMetaDataFile() android.Path {
Wei Li340ee8e2022-03-18 17:33:24 -0700533 return a.provenanceMetaDataFile
534}
535
Andrei Onea580636b2022-08-17 16:53:46 +0000536func (a *AndroidAppImport) PrivAppAllowlist() android.OptionalPath {
537 return android.OptionalPath{}
538}
539
Herbert Xue04354ae2024-01-29 13:57:51 +0800540const (
541 ArchGroupName = "Arch"
542 DpiGroupName = "Dpi_variants"
543)
544
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800545var dpiVariantGroupType reflect.Type
546var archVariantGroupType reflect.Type
Herbert Xue04354ae2024-01-29 13:57:51 +0800547var archdpiVariantGroupType reflect.Type
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800548var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
549
550func initAndroidAppImportVariantGroupTypes() {
Herbert Xue04354ae2024-01-29 13:57:51 +0800551 dpiVariantGroupType = createVariantGroupType(supportedDpis, DpiGroupName)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800552
553 archNames := make([]string, len(android.ArchTypeList()))
554 for i, archType := range android.ArchTypeList() {
555 archNames[i] = archType.Name
556 }
Herbert Xue04354ae2024-01-29 13:57:51 +0800557 archVariantGroupType = createVariantGroupType(archNames, ArchGroupName)
558 archdpiVariantGroupType = createArchDpiVariantGroupType(archNames, supportedDpis)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800559}
560
561// Populates all variant struct properties at creation time.
562func (a *AndroidAppImport) populateAllVariantStructs() {
563 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
564 a.AddProperties(a.dpiVariants)
565
566 a.archVariants = reflect.New(archVariantGroupType).Interface()
567 a.AddProperties(a.archVariants)
Herbert Xue04354ae2024-01-29 13:57:51 +0800568
569 a.arch_dpiVariants = reflect.New(archdpiVariantGroupType).Interface()
570 a.AddProperties(a.arch_dpiVariants)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800571}
572
573func (a *AndroidAppImport) Privileged() bool {
574 return Bool(a.properties.Privileged)
575}
576
Colin Crossf7bbd2f2024-12-05 13:57:10 -0800577func (a *AndroidAppImport) OutgoingDepIsInSameApex(tag blueprint.DependencyTag) bool {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800578 // android_app_import might have extra dependencies via uses_libs property.
579 // Don't track the dependency as we don't automatically add those libraries
580 // to the classpath. It should be explicitly added to java_libs property of APEX
581 return false
582}
583
Jiyong Park92315372021-04-02 08:45:46 +0900584func (a *AndroidAppImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
585 return android.SdkSpecPrivate
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800586}
587
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000588func (a *AndroidAppImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
589 return android.SdkSpecPrivate.ApiLevel
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800590}
591
592var _ android.ApexModule = (*AndroidAppImport)(nil)
593
594// Implements android.ApexModule
595func (j *AndroidAppImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
596 sdkVersion android.ApiLevel) error {
597 // Do not check for prebuilts against the min_sdk_version of enclosing APEX
598 return nil
599}
600
601func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
602 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
603
604 variantFields := make([]reflect.StructField, len(variants))
605 for i, variant := range variants {
606 variantFields[i] = reflect.StructField{
607 Name: proptools.FieldNameForProperty(variant),
608 Type: props,
609 }
610 }
611
612 variantGroupStruct := reflect.StructOf(variantFields)
613 return reflect.StructOf([]reflect.StructField{
614 {
615 Name: variantGroupName,
616 Type: variantGroupStruct,
617 },
618 })
619}
620
Herbert Xue04354ae2024-01-29 13:57:51 +0800621func createArchDpiVariantGroupType(archNames []string, dpiNames []string) reflect.Type {
622 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
623
624 dpiVariantFields := make([]reflect.StructField, len(dpiNames))
625 for i, variant_dpi := range dpiNames {
626 dpiVariantFields[i] = reflect.StructField{
627 Name: proptools.FieldNameForProperty(variant_dpi),
628 Type: props,
629 }
630 }
631 dpiVariantGroupStruct := reflect.StructOf(dpiVariantFields)
632 dpi_struct := reflect.StructOf([]reflect.StructField{
633 {
634 Name: DpiGroupName,
635 Type: reflect.PointerTo(dpiVariantGroupStruct),
636 },
637 })
638
639 archVariantFields := make([]reflect.StructField, len(archNames))
640 for i, variant_arch := range archNames {
641 archVariantFields[i] = reflect.StructField{
642 Name: proptools.FieldNameForProperty(variant_arch),
643 Type: reflect.PointerTo(dpi_struct),
644 }
645 }
646 archVariantGroupStruct := reflect.StructOf(archVariantFields)
647
648 return_struct := reflect.StructOf([]reflect.StructField{
649 {
650 Name: ArchGroupName,
651 Type: reflect.PointerTo(archVariantGroupStruct),
652 },
653 })
654 return return_struct
655}
656
Jiakai Zhangf98da192024-04-15 11:15:41 +0000657func (a *AndroidAppImport) UsesLibrary() *usesLibrary {
658 return &a.usesLibrary
659}
660
661var _ ModuleWithUsesLibrary = (*AndroidAppImport)(nil)
662
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800663// android_app_import imports a prebuilt apk with additional processing specified in the module.
664// DPI-specific apk source files can be specified using dpi_variants. Example:
665//
Colin Crossd079e0b2022-08-16 10:27:33 -0700666// android_app_import {
667// name: "example_import",
668// apk: "prebuilts/example.apk",
669// dpi_variants: {
670// mdpi: {
671// apk: "prebuilts/example_mdpi.apk",
672// },
673// xhdpi: {
674// apk: "prebuilts/example_xhdpi.apk",
675// },
676// },
677// presigned: true,
678// }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800679func AndroidAppImportFactory() android.Module {
680 module := &AndroidAppImport{}
681 module.AddProperties(&module.properties)
682 module.AddProperties(&module.dexpreoptProperties)
683 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
684 module.populateAllVariantStructs()
Cole Faust97494b12024-01-12 14:02:47 -0800685 module.SetDefaultableHook(func(ctx android.DefaultableHookContext) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800686 module.processVariants(ctx)
687 })
688
689 android.InitApexModule(module)
690 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
691 android.InitDefaultableModule(module)
Cole Faustc71b1752024-10-14 12:14:54 -0700692 android.InitConfigurablePrebuiltModuleString(module, &module.properties.Apk, "Apk")
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800693
Ulya Trafimovich22890c42021-01-05 12:04:17 +0000694 module.usesLibrary.enforce = true
695
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800696 return module
697}
698
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800699type AndroidTestImport struct {
700 AndroidAppImport
701
Jiyong Park2f83b312022-10-20 20:18:35 +0900702 testProperties struct {
703 // list of compatibility suites (for example "cts", "vts") that the module should be
704 // installed into.
705 Test_suites []string `android:"arch_variant"`
706
707 // list of files or filegroup modules that provide data that should be installed alongside
708 // the test
709 Data []string `android:"path"`
710
711 // Install the test into a folder named for the module in all test suites.
712 Per_testcase_directory *bool
713 }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800714
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800715 data android.Paths
716}
717
718func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800719 a.generateAndroidBuildActions(ctx)
720
721 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
722}
723
724func (a *AndroidTestImport) InstallInTestcases() bool {
725 return true
726}
727
728// android_test_import imports a prebuilt test apk with additional processing specified in the
729// module. DPI or arch variant configurations can be made as with android_app_import.
730func AndroidTestImportFactory() android.Module {
731 module := &AndroidTestImport{}
732 module.AddProperties(&module.properties)
733 module.AddProperties(&module.dexpreoptProperties)
734 module.AddProperties(&module.testProperties)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800735 module.populateAllVariantStructs()
Cole Faust97494b12024-01-12 14:02:47 -0800736 module.SetDefaultableHook(func(ctx android.DefaultableHookContext) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800737 module.processVariants(ctx)
738 })
739
740 module.dexpreopter.isTest = true
741
742 android.InitApexModule(module)
743 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
744 android.InitDefaultableModule(module)
Cole Faustc71b1752024-10-14 12:14:54 -0700745 android.InitConfigurablePrebuiltModuleString(module, &module.properties.Apk, "Apk")
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800746
747 return module
748}