blob: 1718d936c57dccf32298ee76005b68688a710020 [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 (
Colin Cross5368d0b2023-07-07 11:32:32 -070020 "fmt"
Jaewoong Jungf9b44652020-12-21 12:29:12 -080021 "reflect"
22
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
46 uncompressDexRule = pctx.AndroidStaticRule("uncompress-dex", blueprint.RuleParams{
47 Command: `if (zipinfo $in '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then ` +
48 `${config.Zip2ZipCmd} -i $in -o $out -0 'classes*.dex'` +
49 `; else cp -f $in $out; fi`,
50 CommandDeps: []string{"${config.Zip2ZipCmd}"},
51 Description: "Uncompress dex files",
52 })
Cole Faust2f1da162023-04-17 15:06:56 -070053
Cole Faust93b89b42023-07-20 17:31:16 -070054 checkDexLibsAreUncompressedRule = pctx.AndroidStaticRule("check-dex-libs-are-uncompressed", blueprint.RuleParams{
Cole Faust2f1da162023-04-17 15:06:56 -070055 // grep -v ' stor ' will search for lines that don't have ' stor '. stor means the file is stored uncompressed
Cole Faust93b89b42023-07-20 17:31:16 -070056 Command: "if (zipinfo $in '*.dex' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then " +
Cole Faust2f1da162023-04-17 15:06:56 -070057 "echo $in: Contains compressed JNI libraries and/or dex files >&2;" +
58 "exit 1; " +
59 "else " +
60 "touch $out; " +
61 "fi",
62 Description: "Check for compressed JNI libs or dex files",
63 })
Cole Faust93b89b42023-07-20 17:31:16 -070064
65 checkJniLibsAreUncompressedRule = pctx.AndroidStaticRule("check-jni-libs-are-uncompressed", blueprint.RuleParams{
66 // grep -v ' stor ' will search for lines that don't have ' stor '. stor means the file is stored uncompressed
67 Command: "if (zipinfo $in 'lib/*.so' 2>/dev/null | grep -v ' stor ' >/dev/null) ; then " +
68 "echo $in: Contains compressed JNI libraries >&2;" +
69 "exit 1; " +
70 "else " +
71 "touch $out; " +
72 "fi",
73 Description: "Check for compressed JNI libs or dex files",
74 })
Cole Faust4ec178c2023-01-13 12:03:38 -080075)
76
Jaewoong Jungf9b44652020-12-21 12:29:12 -080077func RegisterAppImportBuildComponents(ctx android.RegistrationContext) {
78 ctx.RegisterModuleType("android_app_import", AndroidAppImportFactory)
79 ctx.RegisterModuleType("android_test_import", AndroidTestImportFactory)
80}
81
82type AndroidAppImport struct {
83 android.ModuleBase
84 android.DefaultableModuleBase
85 android.ApexModuleBase
86 prebuilt android.Prebuilt
87
88 properties AndroidAppImportProperties
89 dpiVariants interface{}
90 archVariants interface{}
91
92 outputFile android.Path
93 certificate Certificate
94
95 dexpreopter
96
97 usesLibrary usesLibrary
98
Jaewoong Jungf9b44652020-12-21 12:29:12 -080099 installPath android.InstallPath
100
101 hideApexVariantFromMake bool
Wei Li340ee8e2022-03-18 17:33:24 -0700102
103 provenanceMetaDataFile android.OutputPath
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800104}
105
106type AndroidAppImportProperties struct {
107 // A prebuilt apk to import
Jooyung Hanf05ca9c2021-06-28 21:48:51 +0900108 Apk *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800109
110 // The name of a certificate in the default certificate directory or an android_app_certificate
111 // module name in the form ":module". Should be empty if presigned or default_dev_cert is set.
112 Certificate *string
113
Jaewoong Jung25ae8de2021-03-08 17:37:46 -0800114 // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
115 Additional_certificates []string
116
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800117 // Set this flag to true if the prebuilt apk is already signed. The certificate property must not
118 // be set for presigned modules.
119 Presigned *bool
120
Jaewoong Jung1c1b6e62021-03-09 15:02:31 -0800121 // Name of the signing certificate lineage file or filegroup module.
122 Lineage *string `android:"path"`
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800123
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -0400124 // For overriding the --rotation-min-sdk-version property of apksig
125 RotationMinSdkVersion *string
126
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800127 // Sign with the default system dev certificate. Must be used judiciously. Most imported apps
128 // need to either specify a specific certificate or be presigned.
129 Default_dev_cert *bool
130
131 // Specifies that this app should be installed to the priv-app directory,
132 // where the system will grant it additional privileges not available to
133 // normal apps.
134 Privileged *bool
135
136 // Names of modules to be overridden. Listed modules can only be other binaries
137 // (in Make or Soong).
138 // This does not completely prevent installation of the overridden binaries, but if both
139 // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
140 // from PRODUCT_PACKAGES.
141 Overrides []string
142
143 // Optional name for the installed app. If unspecified, it is derived from the module name.
144 Filename *string
Bill Peckhama036da92021-01-08 16:09:09 -0800145
146 // If set, create package-export.apk, which other packages can
147 // use to get PRODUCT-agnostic resource data like IDs and type definitions.
148 Export_package_resources *bool
Spandan Dasd1fac642021-05-18 17:01:41 +0000149
150 // Optional. Install to a subdirectory of the default install path for the module
151 Relative_install_path *string
Cole Faust2f1da162023-04-17 15:06:56 -0700152
153 // Whether the prebuilt apk can be installed without additional processing. Default is false.
154 Preprocessed *bool
155
156 // Whether or not to skip checking the preprocessed apk for proper alignment and uncompressed
157 // JNI libs and dex files. Default is false
158 Skip_preprocessed_apk_checks *bool
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800159}
160
161func (a *AndroidAppImport) IsInstallable() bool {
162 return true
163}
164
165// Updates properties with variant-specific values.
166func (a *AndroidAppImport) processVariants(ctx android.LoadHookContext) {
167 config := ctx.Config()
168
169 dpiProps := reflect.ValueOf(a.dpiVariants).Elem().FieldByName("Dpi_variants")
170 // Try DPI variant matches in the reverse-priority order so that the highest priority match
171 // overwrites everything else.
172 // TODO(jungjw): Can we optimize this by making it priority order?
173 for i := len(config.ProductAAPTPrebuiltDPI()) - 1; i >= 0; i-- {
174 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPrebuiltDPI()[i])
175 }
176 if config.ProductAAPTPreferredConfig() != "" {
177 MergePropertiesFromVariant(ctx, &a.properties, dpiProps, config.ProductAAPTPreferredConfig())
178 }
179
180 archProps := reflect.ValueOf(a.archVariants).Elem().FieldByName("Arch")
181 archType := ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType
182 MergePropertiesFromVariant(ctx, &a.properties, archProps, archType.Name)
183
184 if String(a.properties.Apk) == "" {
185 // Disable this module since the apk property is still empty after processing all matching
186 // variants. This likely means there is no matching variant, and the default variant doesn't
187 // have an apk property value either.
188 a.Disable()
189 }
190}
191
192func MergePropertiesFromVariant(ctx android.EarlyModuleContext,
193 dst interface{}, variantGroup reflect.Value, variant string) {
194 src := variantGroup.FieldByName(proptools.FieldNameForProperty(variant))
195 if !src.IsValid() {
196 return
197 }
198
199 err := proptools.ExtendMatchingProperties([]interface{}{dst}, src.Interface(), nil, proptools.OrderAppend)
200 if err != nil {
201 if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok {
202 ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error())
203 } else {
204 panic(err)
205 }
206 }
207}
208
209func (a *AndroidAppImport) DepsMutator(ctx android.BottomUpMutatorContext) {
210 cert := android.SrcIsModule(String(a.properties.Certificate))
211 if cert != "" {
212 ctx.AddDependency(ctx.Module(), certificateTag, cert)
213 }
214
Jaewoong Jung25ae8de2021-03-08 17:37:46 -0800215 for _, cert := range a.properties.Additional_certificates {
216 cert = android.SrcIsModule(cert)
217 if cert != "" {
218 ctx.AddDependency(ctx.Module(), certificateTag, cert)
219 } else {
220 ctx.PropertyErrorf("additional_certificates",
221 `must be names of android_app_certificate modules in the form ":module"`)
222 }
223 }
224
Cole Faustd5806132023-04-13 15:43:53 -0700225 a.usesLibrary.deps(ctx, true)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800226}
227
228func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
229 ctx android.ModuleContext, inputPath android.Path, outputPath android.OutputPath) {
230 // Test apps don't need their JNI libraries stored uncompressed. As a matter of fact, messing
231 // with them may invalidate pre-existing signature data.
Cole Faust2f1da162023-04-17 15:06:56 -0700232 if ctx.InstallInTestcases() && (Bool(a.properties.Presigned) || Bool(a.properties.Preprocessed)) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800233 ctx.Build(pctx, android.BuildParams{
234 Rule: android.Cp,
235 Output: outputPath,
236 Input: inputPath,
237 })
238 return
239 }
Cole Faust4ec178c2023-01-13 12:03:38 -0800240
241 ctx.Build(pctx, android.BuildParams{
242 Rule: uncompressEmbeddedJniLibsRule,
243 Input: inputPath,
244 Output: outputPath,
245 })
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800246}
247
248// Returns whether this module should have the dex file stored uncompressed in the APK.
249func (a *AndroidAppImport) shouldUncompressDex(ctx android.ModuleContext) bool {
Cole Faust2f1da162023-04-17 15:06:56 -0700250 if ctx.Config().UnbundledBuild() || proptools.Bool(a.properties.Preprocessed) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800251 return false
252 }
253
Ulya Trafimovich0061c0d2021-09-01 15:40:38 +0100254 // Uncompress dex in APKs of priv-apps if and only if DONT_UNCOMPRESS_PRIV_APPS_DEXS is false.
255 if a.Privileged() {
256 return ctx.Config().UncompressPrivAppDex()
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800257 }
258
259 return shouldUncompressDex(ctx, &a.dexpreopter)
260}
261
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800262func (a *AndroidAppImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
263 a.generateAndroidBuildActions(ctx)
264}
265
266func (a *AndroidAppImport) InstallApkName() string {
267 return a.BaseModuleName()
268}
269
270func (a *AndroidAppImport) generateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faustd5806132023-04-13 15:43:53 -0700271 if a.Name() == "prebuilt_framework-res" {
272 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.")
273 }
274
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800275 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
276 if !apexInfo.IsForPlatform() {
277 a.hideApexVariantFromMake = true
278 }
279
Cole Faust61585282023-07-14 16:23:39 -0700280 if Bool(a.properties.Preprocessed) {
281 if a.properties.Presigned != nil && !*a.properties.Presigned {
282 ctx.ModuleErrorf("Setting preprocessed: true implies presigned: true, so you cannot set presigned to false")
283 }
284 t := true
285 a.properties.Presigned = &t
286 }
287
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800288 numCertPropsSet := 0
289 if String(a.properties.Certificate) != "" {
290 numCertPropsSet++
291 }
292 if Bool(a.properties.Presigned) {
293 numCertPropsSet++
294 }
295 if Bool(a.properties.Default_dev_cert) {
296 numCertPropsSet++
297 }
298 if numCertPropsSet != 1 {
Cole Faust61585282023-07-14 16:23:39 -0700299 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 -0800300 }
301
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800302 // TODO: LOCAL_EXTRACT_APK/LOCAL_EXTRACT_DPI_APK
303 // TODO: LOCAL_PACKAGE_SPLITS
304
305 srcApk := a.prebuilt.SingleSourcePath(ctx)
306
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800307 // TODO: Install or embed JNI libraries
308
309 // Uncompress JNI libraries in the apk
310 jnisUncompressed := android.PathForModuleOut(ctx, "jnis-uncompressed", ctx.ModuleName()+".apk")
311 a.uncompressEmbeddedJniLibs(ctx, srcApk, jnisUncompressed.OutputPath)
312
Spandan Dasd1fac642021-05-18 17:01:41 +0000313 var pathFragments []string
314 relInstallPath := String(a.properties.Relative_install_path)
Bill Peckhama036da92021-01-08 16:09:09 -0800315
Cole Faustd5806132023-04-13 15:43:53 -0700316 if Bool(a.properties.Privileged) {
Spandan Dasd1fac642021-05-18 17:01:41 +0000317 pathFragments = []string{"priv-app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800318 } else if ctx.InstallInTestcases() {
Spandan Dasd1fac642021-05-18 17:01:41 +0000319 pathFragments = []string{relInstallPath, a.BaseModuleName(), ctx.DeviceConfig().DeviceArch()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800320 } else {
Spandan Dasd1fac642021-05-18 17:01:41 +0000321 pathFragments = []string{"app", relInstallPath, a.BaseModuleName()}
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800322 }
323
Spandan Dasd1fac642021-05-18 17:01:41 +0000324 installDir := android.PathForModuleInstall(ctx, pathFragments...)
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000325 a.dexpreopter.isApp = true
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800326 a.dexpreopter.installPath = installDir.Join(ctx, a.BaseModuleName()+".apk")
327 a.dexpreopter.isPresignedPrebuilt = Bool(a.properties.Presigned)
328 a.dexpreopter.uncompressedDex = a.shouldUncompressDex(ctx)
329
330 a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
331 a.dexpreopter.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
332
Ulya Trafimovichfe927a22021-02-26 14:36:48 +0000333 if a.usesLibrary.enforceUsesLibraries() {
Cole Faust2f1da162023-04-17 15:06:56 -0700334 a.usesLibrary.verifyUsesLibrariesAPK(ctx, srcApk)
Ulya Trafimovichfe927a22021-02-26 14:36:48 +0000335 }
336
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800337 a.dexpreopter.dexpreopt(ctx, jnisUncompressed)
338 if a.dexpreopter.uncompressedDex {
339 dexUncompressed := android.PathForModuleOut(ctx, "dex-uncompressed", ctx.ModuleName()+".apk")
Cole Faust4ec178c2023-01-13 12:03:38 -0800340 ctx.Build(pctx, android.BuildParams{
341 Rule: uncompressDexRule,
342 Input: jnisUncompressed,
343 Output: dexUncompressed,
344 })
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800345 jnisUncompressed = dexUncompressed
346 }
347
348 apkFilename := proptools.StringDefault(a.properties.Filename, a.BaseModuleName()+".apk")
349
350 // TODO: Handle EXTERNAL
351
352 // Sign or align the package if package has not been preprocessed
Bill Peckhama036da92021-01-08 16:09:09 -0800353
Cole Faust2f1da162023-04-17 15:06:56 -0700354 if proptools.Bool(a.properties.Preprocessed) {
Colin Cross5780d572023-07-10 15:15:27 -0700355 var output android.WritablePath
Cole Faustccb20f42023-05-04 12:38:24 -0700356 if !proptools.Bool(a.properties.Skip_preprocessed_apk_checks) {
Colin Cross5780d572023-07-10 15:15:27 -0700357 output = android.PathForModuleOut(ctx, "validated-prebuilt", apkFilename)
358 a.validatePreprocessedApk(ctx, srcApk, output)
359 } else {
360 // If using the input APK unmodified, still make a copy of it so that the output filename has the
361 // right basename.
362 output = android.PathForModuleOut(ctx, apkFilename)
363 ctx.Build(pctx, android.BuildParams{
364 Rule: android.Cp,
365 Input: srcApk,
366 Output: output,
367 })
Cole Faustccb20f42023-05-04 12:38:24 -0700368 }
Cole Faust2f1da162023-04-17 15:06:56 -0700369 a.outputFile = output
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800370 a.certificate = PresignedCertificate
371 } else if !Bool(a.properties.Presigned) {
372 // If the certificate property is empty at this point, default_dev_cert must be set to true.
373 // Which makes processMainCert's behavior for the empty cert string WAI.
Cole Faust61585282023-07-14 16:23:39 -0700374 _, _, certificates := collectAppDeps(ctx, a, false, false)
Colin Crossbc2c8a72022-09-14 12:45:42 -0700375 a.certificate, certificates = processMainCert(a.ModuleBase, String(a.properties.Certificate), certificates, ctx)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800376 signed := android.PathForModuleOut(ctx, "signed", apkFilename)
377 var lineageFile android.Path
378 if lineage := String(a.properties.Lineage); lineage != "" {
379 lineageFile = android.PathForModuleSrc(ctx, lineage)
380 }
Rupert Shuttleworth8eab8692021-11-03 10:39:39 -0400381
382 rotationMinSdkVersion := String(a.properties.RotationMinSdkVersion)
383
384 SignAppPackage(ctx, signed, jnisUncompressed, certificates, nil, lineageFile, rotationMinSdkVersion)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800385 a.outputFile = signed
386 } else {
Cole Faust61585282023-07-14 16:23:39 -0700387 // Presigned without Preprocessed shouldn't really be a thing, currently we disallow
388 // it for apps with targetSdk >= 30, because on those targetSdks you must be using signature
389 // v2 or later, and signature v2 would be wrecked by uncompressing libs / zipaligning.
390 // But ideally we would disallow it for all prebuilt apks, and remove the presigned property.
391 targetSdkCheck := a.validateTargetSdkLessThan30(ctx, srcApk)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800392 alignedApk := android.PathForModuleOut(ctx, "zip-aligned", apkFilename)
Cole Faust61585282023-07-14 16:23:39 -0700393 TransformZipAlign(ctx, alignedApk, jnisUncompressed, []android.Path{targetSdkCheck})
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800394 a.outputFile = alignedApk
395 a.certificate = PresignedCertificate
396 }
397
398 // TODO: Optionally compress the output apk.
399
400 if apexInfo.IsForPlatform() {
401 a.installPath = ctx.InstallFile(installDir, apkFilename, a.outputFile)
Wei Li340ee8e2022-03-18 17:33:24 -0700402 artifactPath := android.PathForModuleSrc(ctx, *a.properties.Apk)
403 a.provenanceMetaDataFile = provenance.GenerateArtifactProvenanceMetaData(ctx, artifactPath, a.installPath)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800404 }
405
406 // TODO: androidmk converter jni libs
407}
408
Cole Faust2f1da162023-04-17 15:06:56 -0700409func (a *AndroidAppImport) validatePreprocessedApk(ctx android.ModuleContext, srcApk android.Path, dstApk android.WritablePath) {
Cole Faust93b89b42023-07-20 17:31:16 -0700410 var validations android.Paths
411
Cole Faust2f1da162023-04-17 15:06:56 -0700412 alignmentStamp := android.PathForModuleOut(ctx, "validated-prebuilt", "alignment.stamp")
413 ctx.Build(pctx, android.BuildParams{
414 Rule: checkZipAlignment,
415 Input: srcApk,
416 Output: alignmentStamp,
417 })
Cole Faust93b89b42023-07-20 17:31:16 -0700418
419 validations = append(validations, alignmentStamp)
420 jniCompressionStamp := android.PathForModuleOut(ctx, "validated-prebuilt", "jni_compression.stamp")
Cole Faust2f1da162023-04-17 15:06:56 -0700421 ctx.Build(pctx, android.BuildParams{
Cole Faust93b89b42023-07-20 17:31:16 -0700422 Rule: checkJniLibsAreUncompressedRule,
Cole Faust2f1da162023-04-17 15:06:56 -0700423 Input: srcApk,
Cole Faust93b89b42023-07-20 17:31:16 -0700424 Output: jniCompressionStamp,
Cole Faust2f1da162023-04-17 15:06:56 -0700425 })
Cole Faust93b89b42023-07-20 17:31:16 -0700426 validations = append(validations, jniCompressionStamp)
427
428 if a.Privileged() {
429 // It's ok for non-privileged apps to have compressed dex files, see go/gms-uncompressed-jni-slides
430 dexCompressionStamp := android.PathForModuleOut(ctx, "validated-prebuilt", "dex_compression.stamp")
431 ctx.Build(pctx, android.BuildParams{
432 Rule: checkDexLibsAreUncompressedRule,
433 Input: srcApk,
434 Output: dexCompressionStamp,
435 })
436 validations = append(validations, dexCompressionStamp)
437 }
438
Cole Faust2f1da162023-04-17 15:06:56 -0700439 ctx.Build(pctx, android.BuildParams{
Cole Faust93b89b42023-07-20 17:31:16 -0700440 Rule: android.Cp,
441 Input: srcApk,
442 Output: dstApk,
443 Validations: validations,
Cole Faust2f1da162023-04-17 15:06:56 -0700444 })
445}
446
Cole Faust61585282023-07-14 16:23:39 -0700447func (a *AndroidAppImport) validateTargetSdkLessThan30(ctx android.ModuleContext, srcApk android.Path) android.Path {
448 alignmentStamp := android.PathForModuleOut(ctx, "validated-prebuilt", "old_target_sdk.stamp")
449 ctx.Build(pctx, android.BuildParams{
450 Rule: checkBelowTargetSdk30ForNonPreprocessedApks,
451 Input: srcApk,
452 Output: alignmentStamp,
453 })
454 return alignmentStamp
455}
456
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800457func (a *AndroidAppImport) Prebuilt() *android.Prebuilt {
458 return &a.prebuilt
459}
460
461func (a *AndroidAppImport) Name() string {
462 return a.prebuilt.Name(a.ModuleBase.Name())
463}
464
465func (a *AndroidAppImport) OutputFile() android.Path {
466 return a.outputFile
467}
468
Colin Cross5368d0b2023-07-07 11:32:32 -0700469func (a *AndroidAppImport) OutputFiles(tag string) (android.Paths, error) {
470 switch tag {
471 case "":
472 return []android.Path{a.outputFile}, nil
473 default:
474 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
475 }
476}
477
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800478func (a *AndroidAppImport) JacocoReportClassesFile() android.Path {
479 return nil
480}
481
482func (a *AndroidAppImport) Certificate() Certificate {
483 return a.certificate
484}
485
Wei Li340ee8e2022-03-18 17:33:24 -0700486func (a *AndroidAppImport) ProvenanceMetaDataFile() android.OutputPath {
487 return a.provenanceMetaDataFile
488}
489
Andrei Onea580636b2022-08-17 16:53:46 +0000490func (a *AndroidAppImport) PrivAppAllowlist() android.OptionalPath {
491 return android.OptionalPath{}
492}
493
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800494var dpiVariantGroupType reflect.Type
495var archVariantGroupType reflect.Type
496var supportedDpis = []string{"ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"}
497
498func initAndroidAppImportVariantGroupTypes() {
499 dpiVariantGroupType = createVariantGroupType(supportedDpis, "Dpi_variants")
500
501 archNames := make([]string, len(android.ArchTypeList()))
502 for i, archType := range android.ArchTypeList() {
503 archNames[i] = archType.Name
504 }
505 archVariantGroupType = createVariantGroupType(archNames, "Arch")
506}
507
508// Populates all variant struct properties at creation time.
509func (a *AndroidAppImport) populateAllVariantStructs() {
510 a.dpiVariants = reflect.New(dpiVariantGroupType).Interface()
511 a.AddProperties(a.dpiVariants)
512
513 a.archVariants = reflect.New(archVariantGroupType).Interface()
514 a.AddProperties(a.archVariants)
515}
516
517func (a *AndroidAppImport) Privileged() bool {
518 return Bool(a.properties.Privileged)
519}
520
521func (a *AndroidAppImport) DepIsInSameApex(_ android.BaseModuleContext, _ android.Module) bool {
522 // android_app_import might have extra dependencies via uses_libs property.
523 // Don't track the dependency as we don't automatically add those libraries
524 // to the classpath. It should be explicitly added to java_libs property of APEX
525 return false
526}
527
Jiyong Park92315372021-04-02 08:45:46 +0900528func (a *AndroidAppImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
529 return android.SdkSpecPrivate
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800530}
531
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000532func (a *AndroidAppImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
533 return android.SdkSpecPrivate.ApiLevel
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800534}
535
Colin Cross8355c152021-08-10 19:24:07 -0700536func (a *AndroidAppImport) LintDepSets() LintDepSets {
537 return LintDepSets{}
538}
539
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800540var _ android.ApexModule = (*AndroidAppImport)(nil)
541
542// Implements android.ApexModule
543func (j *AndroidAppImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
544 sdkVersion android.ApiLevel) error {
545 // Do not check for prebuilts against the min_sdk_version of enclosing APEX
546 return nil
547}
548
549func createVariantGroupType(variants []string, variantGroupName string) reflect.Type {
550 props := reflect.TypeOf((*AndroidAppImportProperties)(nil))
551
552 variantFields := make([]reflect.StructField, len(variants))
553 for i, variant := range variants {
554 variantFields[i] = reflect.StructField{
555 Name: proptools.FieldNameForProperty(variant),
556 Type: props,
557 }
558 }
559
560 variantGroupStruct := reflect.StructOf(variantFields)
561 return reflect.StructOf([]reflect.StructField{
562 {
563 Name: variantGroupName,
564 Type: variantGroupStruct,
565 },
566 })
567}
568
569// android_app_import imports a prebuilt apk with additional processing specified in the module.
570// DPI-specific apk source files can be specified using dpi_variants. Example:
571//
Colin Crossd079e0b2022-08-16 10:27:33 -0700572// android_app_import {
573// name: "example_import",
574// apk: "prebuilts/example.apk",
575// dpi_variants: {
576// mdpi: {
577// apk: "prebuilts/example_mdpi.apk",
578// },
579// xhdpi: {
580// apk: "prebuilts/example_xhdpi.apk",
581// },
582// },
583// presigned: true,
584// }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800585func AndroidAppImportFactory() android.Module {
586 module := &AndroidAppImport{}
587 module.AddProperties(&module.properties)
588 module.AddProperties(&module.dexpreoptProperties)
589 module.AddProperties(&module.usesLibrary.usesLibraryProperties)
590 module.populateAllVariantStructs()
591 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
592 module.processVariants(ctx)
593 })
594
595 android.InitApexModule(module)
596 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
597 android.InitDefaultableModule(module)
598 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
599
Ulya Trafimovich22890c42021-01-05 12:04:17 +0000600 module.usesLibrary.enforce = true
601
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800602 return module
603}
604
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800605type AndroidTestImport struct {
606 AndroidAppImport
607
Jiyong Park2f83b312022-10-20 20:18:35 +0900608 testProperties struct {
609 // list of compatibility suites (for example "cts", "vts") that the module should be
610 // installed into.
611 Test_suites []string `android:"arch_variant"`
612
613 // list of files or filegroup modules that provide data that should be installed alongside
614 // the test
615 Data []string `android:"path"`
616
617 // Install the test into a folder named for the module in all test suites.
618 Per_testcase_directory *bool
619 }
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800620
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800621 data android.Paths
622}
623
624func (a *AndroidTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800625 a.generateAndroidBuildActions(ctx)
626
627 a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
628}
629
630func (a *AndroidTestImport) InstallInTestcases() bool {
631 return true
632}
633
634// android_test_import imports a prebuilt test apk with additional processing specified in the
635// module. DPI or arch variant configurations can be made as with android_app_import.
636func AndroidTestImportFactory() android.Module {
637 module := &AndroidTestImport{}
638 module.AddProperties(&module.properties)
639 module.AddProperties(&module.dexpreoptProperties)
640 module.AddProperties(&module.testProperties)
Jaewoong Jungf9b44652020-12-21 12:29:12 -0800641 module.populateAllVariantStructs()
642 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
643 module.processVariants(ctx)
644 })
645
646 module.dexpreopter.isTest = true
647
648 android.InitApexModule(module)
649 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
650 android.InitDefaultableModule(module)
651 android.InitSingleSourcePrebuiltModule(module, &module.properties, "Apk")
652
653 return module
654}