app.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642
  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package java
  15. // This file contains the module implementations for android_app, android_test, and some more
  16. // related module types, including their override variants.
  17. import (
  18. "path/filepath"
  19. "strings"
  20. "github.com/google/blueprint"
  21. "github.com/google/blueprint/proptools"
  22. "android/soong/android"
  23. "android/soong/bazel"
  24. "android/soong/cc"
  25. "android/soong/dexpreopt"
  26. "android/soong/tradefed"
  27. )
  28. func init() {
  29. RegisterAppBuildComponents(android.InitRegistrationContext)
  30. pctx.HostBinToolVariable("ModifyAllowlistCmd", "modify_permissions_allowlist")
  31. }
  32. var (
  33. modifyAllowlist = pctx.AndroidStaticRule("modifyAllowlist",
  34. blueprint.RuleParams{
  35. Command: "${ModifyAllowlistCmd} $in $packageName $out",
  36. CommandDeps: []string{"${ModifyAllowlistCmd}"},
  37. }, "packageName")
  38. )
  39. func RegisterAppBuildComponents(ctx android.RegistrationContext) {
  40. ctx.RegisterModuleType("android_app", AndroidAppFactory)
  41. ctx.RegisterModuleType("android_test", AndroidTestFactory)
  42. ctx.RegisterModuleType("android_test_helper_app", AndroidTestHelperAppFactory)
  43. ctx.RegisterModuleType("android_app_certificate", AndroidAppCertificateFactory)
  44. ctx.RegisterModuleType("override_android_app", OverrideAndroidAppModuleFactory)
  45. ctx.RegisterModuleType("override_android_test", OverrideAndroidTestModuleFactory)
  46. }
  47. // AndroidManifest.xml merging
  48. // package splits
  49. type appProperties struct {
  50. // Names of extra android_app_certificate modules to sign the apk with in the form ":module".
  51. Additional_certificates []string
  52. // If set, create package-export.apk, which other packages can
  53. // use to get PRODUCT-agnostic resource data like IDs and type definitions.
  54. Export_package_resources *bool
  55. // Specifies that this app should be installed to the priv-app directory,
  56. // where the system will grant it additional privileges not available to
  57. // normal apps.
  58. Privileged *bool
  59. // list of resource labels to generate individual resource packages
  60. Package_splits []string
  61. // list of native libraries that will be provided in or alongside the resulting jar
  62. Jni_libs []string `android:"arch_variant"`
  63. // if true, use JNI libraries that link against platform APIs even if this module sets
  64. // sdk_version.
  65. Jni_uses_platform_apis *bool
  66. // if true, use JNI libraries that link against SDK APIs even if this module does not set
  67. // sdk_version.
  68. Jni_uses_sdk_apis *bool
  69. // STL library to use for JNI libraries.
  70. Stl *string `android:"arch_variant"`
  71. // Store native libraries uncompressed in the APK and set the android:extractNativeLibs="false" manifest
  72. // flag so that they are used from inside the APK at runtime. Defaults to true for android_test modules unless
  73. // sdk_version or min_sdk_version is set to a version that doesn't support it (<23), defaults to true for
  74. // android_app modules that are embedded to APEXes, defaults to false for other module types where the native
  75. // libraries are generally preinstalled outside the APK.
  76. Use_embedded_native_libs *bool
  77. // Store dex files uncompressed in the APK and set the android:useEmbeddedDex="true" manifest attribute so that
  78. // they are used from inside the APK at runtime.
  79. Use_embedded_dex *bool
  80. // Forces native libraries to always be packaged into the APK,
  81. // Use_embedded_native_libs still selects whether they are stored uncompressed and aligned or compressed.
  82. // True for android_test* modules.
  83. AlwaysPackageNativeLibs bool `blueprint:"mutated"`
  84. // If set, find and merge all NOTICE files that this module and its dependencies have and store
  85. // it in the APK as an asset.
  86. Embed_notices *bool
  87. // cc.Coverage related properties
  88. PreventInstall bool `blueprint:"mutated"`
  89. IsCoverageVariant bool `blueprint:"mutated"`
  90. // It can be set to test the behaviour of default target sdk version.
  91. // Only required when updatable: false. It is an error if updatable: true and this is false.
  92. Enforce_default_target_sdk_version *bool
  93. // If set, the targetSdkVersion for the target is set to the latest default API level.
  94. // This would be by default false, unless updatable: true or
  95. // enforce_default_target_sdk_version: true in which case this defaults to true.
  96. EnforceDefaultTargetSdkVersion bool `blueprint:"mutated"`
  97. // Whether this app is considered mainline updatable or not. When set to true, this will enforce
  98. // additional rules to make sure an app can safely be updated. Default is false.
  99. // Prefer using other specific properties if build behaviour must be changed; avoid using this
  100. // flag for anything but neverallow rules (unless the behaviour change is invisible to owners).
  101. Updatable *bool
  102. // Specifies the file that contains the allowlist for this app.
  103. Privapp_allowlist *string `android:"path"`
  104. }
  105. // android_app properties that can be overridden by override_android_app
  106. type overridableAppProperties struct {
  107. // The name of a certificate in the default certificate directory, blank to use the default product certificate,
  108. // or an android_app_certificate module name in the form ":module".
  109. Certificate *string
  110. // Name of the signing certificate lineage file or filegroup module.
  111. Lineage *string `android:"path"`
  112. // For overriding the --rotation-min-sdk-version property of apksig
  113. RotationMinSdkVersion *string
  114. // the package name of this app. The package name in the manifest file is used if one was not given.
  115. Package_name *string
  116. // the logging parent of this app.
  117. Logging_parent *string
  118. // Whether to rename the package in resources to the override name rather than the base name. Defaults to true.
  119. Rename_resources_package *bool
  120. // Names of modules to be overridden. Listed modules can only be other binaries
  121. // (in Make or Soong).
  122. // This does not completely prevent installation of the overridden binaries, but if both
  123. // binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
  124. // from PRODUCT_PACKAGES.
  125. Overrides []string
  126. }
  127. type AndroidApp struct {
  128. android.BazelModuleBase
  129. Library
  130. aapt
  131. android.OverridableModuleBase
  132. certificate Certificate
  133. appProperties appProperties
  134. overridableAppProperties overridableAppProperties
  135. jniLibs []jniLib
  136. installPathForJNISymbols android.Path
  137. embeddedJniLibs bool
  138. jniCoverageOutputs android.Paths
  139. bundleFile android.Path
  140. // the install APK name is normally the same as the module name, but can be overridden with PRODUCT_PACKAGE_NAME_OVERRIDES.
  141. installApkName string
  142. installDir android.InstallPath
  143. onDeviceDir string
  144. additionalAaptFlags []string
  145. overriddenManifestPackageName string
  146. android.ApexBundleDepsInfo
  147. javaApiUsedByOutputFile android.ModuleOutPath
  148. privAppAllowlist android.OptionalPath
  149. }
  150. func (a *AndroidApp) IsInstallable() bool {
  151. return Bool(a.properties.Installable)
  152. }
  153. func (a *AndroidApp) ExportedProguardFlagFiles() android.Paths {
  154. return nil
  155. }
  156. func (a *AndroidApp) ExportedStaticPackages() android.Paths {
  157. return nil
  158. }
  159. func (a *AndroidApp) OutputFile() android.Path {
  160. return a.outputFile
  161. }
  162. func (a *AndroidApp) Certificate() Certificate {
  163. return a.certificate
  164. }
  165. func (a *AndroidApp) JniCoverageOutputs() android.Paths {
  166. return a.jniCoverageOutputs
  167. }
  168. func (a *AndroidApp) PrivAppAllowlist() android.OptionalPath {
  169. return a.privAppAllowlist
  170. }
  171. var _ AndroidLibraryDependency = (*AndroidApp)(nil)
  172. type Certificate struct {
  173. Pem, Key android.Path
  174. presigned bool
  175. }
  176. var PresignedCertificate = Certificate{presigned: true}
  177. func (c Certificate) AndroidMkString() string {
  178. if c.presigned {
  179. return "PRESIGNED"
  180. } else {
  181. return c.Pem.String()
  182. }
  183. }
  184. func (a *AndroidApp) DepsMutator(ctx android.BottomUpMutatorContext) {
  185. a.Module.deps(ctx)
  186. if String(a.appProperties.Stl) == "c++_shared" && !a.SdkVersion(ctx).Specified() {
  187. ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
  188. }
  189. sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
  190. if sdkDep.hasFrameworkLibs() {
  191. a.aapt.deps(ctx, sdkDep)
  192. }
  193. usesSDK := a.SdkVersion(ctx).Specified() && a.SdkVersion(ctx).Kind != android.SdkCorePlatform
  194. if usesSDK && Bool(a.appProperties.Jni_uses_sdk_apis) {
  195. ctx.PropertyErrorf("jni_uses_sdk_apis",
  196. "can only be set for modules that do not set sdk_version")
  197. } else if !usesSDK && Bool(a.appProperties.Jni_uses_platform_apis) {
  198. ctx.PropertyErrorf("jni_uses_platform_apis",
  199. "can only be set for modules that set sdk_version")
  200. }
  201. for _, jniTarget := range ctx.MultiTargets() {
  202. variation := append(jniTarget.Variations(),
  203. blueprint.Variation{Mutator: "link", Variation: "shared"})
  204. // If the app builds against an Android SDK use the SDK variant of JNI dependencies
  205. // unless jni_uses_platform_apis is set.
  206. // Don't require the SDK variant for apps that are shipped on vendor, etc., as they already
  207. // have stable APIs through the VNDK.
  208. if (usesSDK && !a.RequiresStableAPIs(ctx) &&
  209. !Bool(a.appProperties.Jni_uses_platform_apis)) ||
  210. Bool(a.appProperties.Jni_uses_sdk_apis) {
  211. variation = append(variation, blueprint.Variation{Mutator: "sdk", Variation: "sdk"})
  212. }
  213. ctx.AddFarVariationDependencies(variation, jniLibTag, a.appProperties.Jni_libs...)
  214. }
  215. a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
  216. }
  217. func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
  218. cert := android.SrcIsModule(a.getCertString(ctx))
  219. if cert != "" {
  220. ctx.AddDependency(ctx.Module(), certificateTag, cert)
  221. }
  222. if a.appProperties.Privapp_allowlist != nil && !Bool(a.appProperties.Privileged) {
  223. ctx.PropertyErrorf("privapp_allowlist", "privileged must be set in order to use privapp_allowlist")
  224. }
  225. for _, cert := range a.appProperties.Additional_certificates {
  226. cert = android.SrcIsModule(cert)
  227. if cert != "" {
  228. ctx.AddDependency(ctx.Module(), certificateTag, cert)
  229. } else {
  230. ctx.PropertyErrorf("additional_certificates",
  231. `must be names of android_app_certificate modules in the form ":module"`)
  232. }
  233. }
  234. }
  235. func (a *AndroidTestHelperApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  236. a.generateAndroidBuildActions(ctx)
  237. }
  238. func (a *AndroidApp) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  239. a.checkAppSdkVersions(ctx)
  240. a.generateAndroidBuildActions(ctx)
  241. a.generateJavaUsedByApex(ctx)
  242. }
  243. func (a *AndroidApp) checkAppSdkVersions(ctx android.ModuleContext) {
  244. if a.Updatable() {
  245. if !a.SdkVersion(ctx).Stable() {
  246. ctx.PropertyErrorf("sdk_version", "Updatable apps must use stable SDKs, found %v", a.SdkVersion(ctx))
  247. }
  248. if String(a.deviceProperties.Min_sdk_version) == "" {
  249. ctx.PropertyErrorf("updatable", "updatable apps must set min_sdk_version.")
  250. }
  251. if minSdkVersion, err := a.MinSdkVersion(ctx).EffectiveVersion(ctx); err == nil {
  252. a.checkJniLibsSdkVersion(ctx, minSdkVersion)
  253. android.CheckMinSdkVersion(ctx, minSdkVersion, a.WalkPayloadDeps)
  254. } else {
  255. ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
  256. }
  257. if !BoolDefault(a.appProperties.Enforce_default_target_sdk_version, true) {
  258. ctx.PropertyErrorf("enforce_default_target_sdk_version", "Updatable apps must enforce default target sdk version")
  259. }
  260. // TODO(b/227460469) after all the modules removes the target sdk version, throw an error if the target sdk version is explicitly set.
  261. if a.deviceProperties.Target_sdk_version == nil {
  262. a.SetEnforceDefaultTargetSdkVersion(true)
  263. }
  264. }
  265. a.checkPlatformAPI(ctx)
  266. a.checkSdkVersions(ctx)
  267. }
  268. // If an updatable APK sets min_sdk_version, min_sdk_vesion of JNI libs should match with it.
  269. // This check is enforced for "updatable" APKs (including APK-in-APEX).
  270. func (a *AndroidApp) checkJniLibsSdkVersion(ctx android.ModuleContext, minSdkVersion android.ApiLevel) {
  271. // It's enough to check direct JNI deps' sdk_version because all transitive deps from JNI deps are checked in cc.checkLinkType()
  272. ctx.VisitDirectDeps(func(m android.Module) {
  273. if !IsJniDepTag(ctx.OtherModuleDependencyTag(m)) {
  274. return
  275. }
  276. dep, _ := m.(*cc.Module)
  277. // The domain of cc.sdk_version is "current" and <number>
  278. // We can rely on android.SdkSpec to convert it to <number> so that "current" is
  279. // handled properly regardless of sdk finalization.
  280. jniSdkVersion, err := android.SdkSpecFrom(ctx, dep.MinSdkVersion()).EffectiveVersion(ctx)
  281. if err != nil || minSdkVersion.LessThan(jniSdkVersion) {
  282. ctx.OtherModuleErrorf(dep, "min_sdk_version(%v) is higher than min_sdk_version(%v) of the containing android_app(%v)",
  283. dep.MinSdkVersion(), minSdkVersion, ctx.ModuleName())
  284. return
  285. }
  286. })
  287. }
  288. // Returns true if the native libraries should be stored in the APK uncompressed and the
  289. // extractNativeLibs application flag should be set to false in the manifest.
  290. func (a *AndroidApp) useEmbeddedNativeLibs(ctx android.ModuleContext) bool {
  291. minSdkVersion, err := a.MinSdkVersion(ctx).EffectiveVersion(ctx)
  292. if err != nil {
  293. ctx.PropertyErrorf("min_sdk_version", "invalid value %q: %s", a.MinSdkVersion(ctx), err)
  294. }
  295. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  296. return (minSdkVersion.FinalOrFutureInt() >= 23 && Bool(a.appProperties.Use_embedded_native_libs)) ||
  297. !apexInfo.IsForPlatform()
  298. }
  299. // Returns whether this module should have the dex file stored uncompressed in the APK.
  300. func (a *AndroidApp) shouldUncompressDex(ctx android.ModuleContext) bool {
  301. if Bool(a.appProperties.Use_embedded_dex) {
  302. return true
  303. }
  304. // Uncompress dex in APKs of privileged apps (even for unbundled builds, they may
  305. // be preinstalled as prebuilts).
  306. if ctx.Config().UncompressPrivAppDex() && a.Privileged() {
  307. return true
  308. }
  309. if ctx.Config().UnbundledBuild() {
  310. return false
  311. }
  312. return shouldUncompressDex(ctx, &a.dexpreopter)
  313. }
  314. func (a *AndroidApp) shouldEmbedJnis(ctx android.BaseModuleContext) bool {
  315. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  316. return ctx.Config().UnbundledBuild() || Bool(a.appProperties.Use_embedded_native_libs) ||
  317. !apexInfo.IsForPlatform() || a.appProperties.AlwaysPackageNativeLibs
  318. }
  319. func generateAaptRenamePackageFlags(packageName string, renameResourcesPackage bool) []string {
  320. aaptFlags := []string{"--rename-manifest-package " + packageName}
  321. if renameResourcesPackage {
  322. // Required to rename the package name in the resources table.
  323. aaptFlags = append(aaptFlags, "--rename-resources-package "+packageName)
  324. }
  325. return aaptFlags
  326. }
  327. func (a *AndroidApp) OverriddenManifestPackageName() string {
  328. return a.overriddenManifestPackageName
  329. }
  330. func (a *AndroidApp) renameResourcesPackage() bool {
  331. return proptools.BoolDefault(a.overridableAppProperties.Rename_resources_package, true)
  332. }
  333. func (a *AndroidApp) aaptBuildActions(ctx android.ModuleContext) {
  334. usePlatformAPI := proptools.Bool(a.Module.deviceProperties.Platform_apis)
  335. if ctx.Module().(android.SdkContext).SdkVersion(ctx).Kind == android.SdkModule {
  336. usePlatformAPI = true
  337. }
  338. a.aapt.usesNonSdkApis = usePlatformAPI
  339. // Ask manifest_fixer to add or update the application element indicating this app has no code.
  340. a.aapt.hasNoCode = !a.hasCode(ctx)
  341. aaptLinkFlags := []string{}
  342. // Add TARGET_AAPT_CHARACTERISTICS values to AAPT link flags if they exist and --product flags were not provided.
  343. hasProduct := android.PrefixInList(a.aaptProperties.Aaptflags, "--product")
  344. if !hasProduct && len(ctx.Config().ProductAAPTCharacteristics()) > 0 {
  345. aaptLinkFlags = append(aaptLinkFlags, "--product", ctx.Config().ProductAAPTCharacteristics())
  346. }
  347. if !Bool(a.aaptProperties.Aapt_include_all_resources) {
  348. // Product AAPT config
  349. for _, aaptConfig := range ctx.Config().ProductAAPTConfig() {
  350. aaptLinkFlags = append(aaptLinkFlags, "-c", aaptConfig)
  351. }
  352. // Product AAPT preferred config
  353. if len(ctx.Config().ProductAAPTPreferredConfig()) > 0 {
  354. aaptLinkFlags = append(aaptLinkFlags, "--preferred-density", ctx.Config().ProductAAPTPreferredConfig())
  355. }
  356. }
  357. manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
  358. if overridden || a.overridableAppProperties.Package_name != nil {
  359. // The product override variable has a priority over the package_name property.
  360. if !overridden {
  361. manifestPackageName = *a.overridableAppProperties.Package_name
  362. }
  363. aaptLinkFlags = append(aaptLinkFlags, generateAaptRenamePackageFlags(manifestPackageName, a.renameResourcesPackage())...)
  364. a.overriddenManifestPackageName = manifestPackageName
  365. }
  366. aaptLinkFlags = append(aaptLinkFlags, a.additionalAaptFlags...)
  367. a.aapt.splitNames = a.appProperties.Package_splits
  368. a.aapt.LoggingParent = String(a.overridableAppProperties.Logging_parent)
  369. if a.Updatable() {
  370. a.aapt.defaultManifestVersion = android.DefaultUpdatableModuleVersion
  371. }
  372. a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts,
  373. a.usesLibraryProperties.Exclude_uses_libs, a.enforceDefaultTargetSdkVersion(), aaptLinkFlags...)
  374. // apps manifests are handled by aapt, don't let Module see them
  375. a.properties.Manifest = nil
  376. }
  377. func (a *AndroidApp) proguardBuildActions(ctx android.ModuleContext) {
  378. var staticLibProguardFlagFiles android.Paths
  379. ctx.VisitDirectDeps(func(m android.Module) {
  380. if lib, ok := m.(LibraryDependency); ok && ctx.OtherModuleDependencyTag(m) == staticLibTag {
  381. staticLibProguardFlagFiles = append(staticLibProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
  382. }
  383. })
  384. staticLibProguardFlagFiles = android.FirstUniquePaths(staticLibProguardFlagFiles)
  385. a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, staticLibProguardFlagFiles...)
  386. a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles, a.proguardOptionsFile)
  387. }
  388. func (a *AndroidApp) installPath(ctx android.ModuleContext) android.InstallPath {
  389. var installDir string
  390. if ctx.ModuleName() == "framework-res" {
  391. // framework-res.apk is installed as system/framework/framework-res.apk
  392. installDir = "framework"
  393. } else if a.Privileged() {
  394. installDir = filepath.Join("priv-app", a.installApkName)
  395. } else {
  396. installDir = filepath.Join("app", a.installApkName)
  397. }
  398. return android.PathForModuleInstall(ctx, installDir, a.installApkName+".apk")
  399. }
  400. func (a *AndroidApp) dexBuildActions(ctx android.ModuleContext) android.Path {
  401. a.dexpreopter.installPath = a.installPath(ctx)
  402. a.dexpreopter.isApp = true
  403. if a.dexProperties.Uncompress_dex == nil {
  404. // If the value was not force-set by the user, use reasonable default based on the module.
  405. a.dexProperties.Uncompress_dex = proptools.BoolPtr(a.shouldUncompressDex(ctx))
  406. }
  407. a.dexpreopter.uncompressedDex = *a.dexProperties.Uncompress_dex
  408. a.dexpreopter.enforceUsesLibs = a.usesLibrary.enforceUsesLibraries()
  409. a.dexpreopter.classLoaderContexts = a.classLoaderContexts
  410. a.dexpreopter.manifestFile = a.mergedManifestFile
  411. a.dexpreopter.preventInstall = a.appProperties.PreventInstall
  412. if ctx.ModuleName() != "framework-res" {
  413. a.Module.compile(ctx, a.aaptSrcJar)
  414. }
  415. return a.dexJarFile.PathOrNil()
  416. }
  417. func (a *AndroidApp) jniBuildActions(jniLibs []jniLib, prebuiltJniPackages android.Paths, ctx android.ModuleContext) android.WritablePath {
  418. var jniJarFile android.WritablePath
  419. if len(jniLibs) > 0 || len(prebuiltJniPackages) > 0 {
  420. a.jniLibs = jniLibs
  421. if a.shouldEmbedJnis(ctx) {
  422. jniJarFile = android.PathForModuleOut(ctx, "jnilibs.zip")
  423. a.installPathForJNISymbols = a.installPath(ctx)
  424. TransformJniLibsToJar(ctx, jniJarFile, jniLibs, prebuiltJniPackages, a.useEmbeddedNativeLibs(ctx))
  425. for _, jni := range jniLibs {
  426. if jni.coverageFile.Valid() {
  427. // Only collect coverage for the first target arch if this is a multilib target.
  428. // TODO(jungjw): Ideally, we want to collect both reports, but that would cause coverage
  429. // data file path collisions since the current coverage file path format doesn't contain
  430. // arch-related strings. This is fine for now though; the code coverage team doesn't use
  431. // multi-arch targets such as test_suite_* for coverage collections yet.
  432. //
  433. // Work with the team to come up with a new format that handles multilib modules properly
  434. // and change this.
  435. if len(ctx.Config().Targets[android.Android]) == 1 ||
  436. ctx.Config().AndroidFirstDeviceTarget.Arch.ArchType == jni.target.Arch.ArchType {
  437. a.jniCoverageOutputs = append(a.jniCoverageOutputs, jni.coverageFile.Path())
  438. }
  439. }
  440. }
  441. a.embeddedJniLibs = true
  442. }
  443. }
  444. return jniJarFile
  445. }
  446. func (a *AndroidApp) JNISymbolsInstalls(installPath string) android.RuleBuilderInstalls {
  447. var jniSymbols android.RuleBuilderInstalls
  448. for _, jniLib := range a.jniLibs {
  449. if jniLib.unstrippedFile != nil {
  450. jniSymbols = append(jniSymbols, android.RuleBuilderInstall{
  451. From: jniLib.unstrippedFile,
  452. To: filepath.Join(installPath, targetToJniDir(jniLib.target), jniLib.unstrippedFile.Base()),
  453. })
  454. }
  455. }
  456. return jniSymbols
  457. }
  458. // Reads and prepends a main cert from the default cert dir if it hasn't been set already, i.e. it
  459. // isn't a cert module reference. Also checks and enforces system cert restriction if applicable.
  460. func processMainCert(m android.ModuleBase, certPropValue string, certificates []Certificate,
  461. ctx android.ModuleContext) (mainCertificate Certificate, allCertificates []Certificate) {
  462. if android.SrcIsModule(certPropValue) == "" {
  463. var mainCert Certificate
  464. if certPropValue != "" {
  465. defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
  466. mainCert = Certificate{
  467. Pem: defaultDir.Join(ctx, certPropValue+".x509.pem"),
  468. Key: defaultDir.Join(ctx, certPropValue+".pk8"),
  469. }
  470. } else {
  471. pem, key := ctx.Config().DefaultAppCertificate(ctx)
  472. mainCert = Certificate{
  473. Pem: pem,
  474. Key: key,
  475. }
  476. }
  477. certificates = append([]Certificate{mainCert}, certificates...)
  478. }
  479. if len(certificates) > 0 {
  480. mainCertificate = certificates[0]
  481. } else {
  482. // This can be reached with an empty certificate list if AllowMissingDependencies is set
  483. // and the certificate property for this module is a module reference to a missing module.
  484. if !ctx.Config().AllowMissingDependencies() && len(ctx.GetMissingDependencies()) > 0 {
  485. panic("Should only get here if AllowMissingDependencies set and there are missing dependencies")
  486. }
  487. // Set a certificate to avoid panics later when accessing it.
  488. mainCertificate = Certificate{
  489. Key: android.PathForModuleOut(ctx, "missing.pk8"),
  490. Pem: android.PathForModuleOut(ctx, "missing.x509.pem"),
  491. }
  492. }
  493. if !m.Platform() {
  494. certPath := mainCertificate.Pem.String()
  495. systemCertPath := ctx.Config().DefaultAppCertificateDir(ctx).String()
  496. if strings.HasPrefix(certPath, systemCertPath) {
  497. enforceSystemCert := ctx.Config().EnforceSystemCertificate()
  498. allowed := ctx.Config().EnforceSystemCertificateAllowList()
  499. if enforceSystemCert && !inList(m.Name(), allowed) {
  500. ctx.PropertyErrorf("certificate", "The module in product partition cannot be signed with certificate in system.")
  501. }
  502. }
  503. }
  504. return mainCertificate, certificates
  505. }
  506. func (a *AndroidApp) InstallApkName() string {
  507. return a.installApkName
  508. }
  509. func (a *AndroidApp) createPrivappAllowlist(ctx android.ModuleContext) android.Path {
  510. if a.appProperties.Privapp_allowlist == nil {
  511. return nil
  512. }
  513. isOverrideApp := a.GetOverriddenBy() != ""
  514. if !isOverrideApp {
  515. // if this is not an override, we don't need to rewrite the existing privapp allowlist
  516. return android.PathForModuleSrc(ctx, *a.appProperties.Privapp_allowlist)
  517. }
  518. if a.overridableAppProperties.Package_name == nil {
  519. ctx.PropertyErrorf("privapp_allowlist", "package_name must be set to use privapp_allowlist")
  520. }
  521. packageName := *a.overridableAppProperties.Package_name
  522. fileName := "privapp_allowlist_" + packageName + ".xml"
  523. outPath := android.PathForModuleOut(ctx, fileName).OutputPath
  524. ctx.Build(pctx, android.BuildParams{
  525. Rule: modifyAllowlist,
  526. Input: android.PathForModuleSrc(ctx, *a.appProperties.Privapp_allowlist),
  527. Output: outPath,
  528. Args: map[string]string{
  529. "packageName": packageName,
  530. },
  531. })
  532. return &outPath
  533. }
  534. func (a *AndroidApp) generateAndroidBuildActions(ctx android.ModuleContext) {
  535. var apkDeps android.Paths
  536. if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
  537. a.hideApexVariantFromMake = true
  538. }
  539. a.aapt.useEmbeddedNativeLibs = a.useEmbeddedNativeLibs(ctx)
  540. a.aapt.useEmbeddedDex = Bool(a.appProperties.Use_embedded_dex)
  541. // Check if the install APK name needs to be overridden.
  542. a.installApkName = ctx.DeviceConfig().OverridePackageNameFor(a.Stem())
  543. if ctx.ModuleName() == "framework-res" {
  544. // framework-res.apk is installed as system/framework/framework-res.apk
  545. a.installDir = android.PathForModuleInstall(ctx, "framework")
  546. } else if a.Privileged() {
  547. a.installDir = android.PathForModuleInstall(ctx, "priv-app", a.installApkName)
  548. } else if ctx.InstallInTestcases() {
  549. a.installDir = android.PathForModuleInstall(ctx, a.installApkName, ctx.DeviceConfig().DeviceArch())
  550. } else {
  551. a.installDir = android.PathForModuleInstall(ctx, "app", a.installApkName)
  552. }
  553. a.onDeviceDir = android.InstallPathToOnDevicePath(ctx, a.installDir)
  554. a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  555. var noticeAssetPath android.WritablePath
  556. if Bool(a.appProperties.Embed_notices) || ctx.Config().IsEnvTrue("ALWAYS_EMBED_NOTICES") {
  557. // The rule to create the notice file can't be generated yet, as the final output path
  558. // for the apk isn't known yet. Add the path where the notice file will be generated to the
  559. // aapt rules now before calling aaptBuildActions, the rule to create the notice file will
  560. // be generated later.
  561. noticeAssetPath = android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
  562. a.aapt.noticeFile = android.OptionalPathForPath(noticeAssetPath)
  563. }
  564. // For apps targeting latest target_sdk_version
  565. if Bool(a.appProperties.Enforce_default_target_sdk_version) {
  566. a.SetEnforceDefaultTargetSdkVersion(true)
  567. }
  568. // Process all building blocks, from AAPT to certificates.
  569. a.aaptBuildActions(ctx)
  570. // The decision to enforce <uses-library> checks is made before adding implicit SDK libraries.
  571. a.usesLibrary.freezeEnforceUsesLibraries()
  572. // Add implicit SDK libraries to <uses-library> list.
  573. requiredUsesLibs, optionalUsesLibs := a.classLoaderContexts.UsesLibs()
  574. for _, usesLib := range requiredUsesLibs {
  575. a.usesLibrary.addLib(usesLib, false)
  576. }
  577. for _, usesLib := range optionalUsesLibs {
  578. a.usesLibrary.addLib(usesLib, true)
  579. }
  580. // Check that the <uses-library> list is coherent with the manifest.
  581. if a.usesLibrary.enforceUsesLibraries() {
  582. manifestCheckFile := a.usesLibrary.verifyUsesLibrariesManifest(ctx, a.mergedManifestFile)
  583. apkDeps = append(apkDeps, manifestCheckFile)
  584. }
  585. a.proguardBuildActions(ctx)
  586. a.linter.mergedManifest = a.aapt.mergedManifestFile
  587. a.linter.manifest = a.aapt.manifestPath
  588. a.linter.resources = a.aapt.resourceFiles
  589. a.linter.buildModuleReportZip = ctx.Config().UnbundledBuildApps()
  590. dexJarFile := a.dexBuildActions(ctx)
  591. jniLibs, prebuiltJniPackages, certificates := collectAppDeps(ctx, a, a.shouldEmbedJnis(ctx), !Bool(a.appProperties.Jni_uses_platform_apis))
  592. jniJarFile := a.jniBuildActions(jniLibs, prebuiltJniPackages, ctx)
  593. if ctx.Failed() {
  594. return
  595. }
  596. a.certificate, certificates = processMainCert(a.ModuleBase, a.getCertString(ctx), certificates, ctx)
  597. // Build a final signed app package.
  598. packageFile := android.PathForModuleOut(ctx, a.installApkName+".apk")
  599. v4SigningRequested := Bool(a.Module.deviceProperties.V4_signature)
  600. var v4SignatureFile android.WritablePath = nil
  601. if v4SigningRequested {
  602. v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+".apk.idsig")
  603. }
  604. var lineageFile android.Path
  605. if lineage := String(a.overridableAppProperties.Lineage); lineage != "" {
  606. lineageFile = android.PathForModuleSrc(ctx, lineage)
  607. }
  608. rotationMinSdkVersion := String(a.overridableAppProperties.RotationMinSdkVersion)
  609. CreateAndSignAppPackage(ctx, packageFile, a.exportPackage, jniJarFile, dexJarFile, certificates, apkDeps, v4SignatureFile, lineageFile, rotationMinSdkVersion, Bool(a.dexProperties.Optimize.Shrink_resources))
  610. a.outputFile = packageFile
  611. if v4SigningRequested {
  612. a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
  613. }
  614. if a.aapt.noticeFile.Valid() {
  615. // Generating the notice file rule has to be here after a.outputFile is known.
  616. noticeFile := android.PathForModuleOut(ctx, "NOTICE.html.gz")
  617. android.BuildNoticeHtmlOutputFromLicenseMetadata(
  618. ctx, noticeFile, "", "",
  619. []string{
  620. a.installDir.String() + "/",
  621. android.PathForModuleInstall(ctx).String() + "/",
  622. a.outputFile.String(),
  623. })
  624. builder := android.NewRuleBuilder(pctx, ctx)
  625. builder.Command().Text("cp").
  626. Input(noticeFile).
  627. Output(noticeAssetPath)
  628. builder.Build("notice_dir", "Building notice dir")
  629. }
  630. for _, split := range a.aapt.splits {
  631. // Sign the split APKs
  632. packageFile := android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk")
  633. if v4SigningRequested {
  634. v4SignatureFile = android.PathForModuleOut(ctx, a.installApkName+"_"+split.suffix+".apk.idsig")
  635. }
  636. CreateAndSignAppPackage(ctx, packageFile, split.path, nil, nil, certificates, apkDeps, v4SignatureFile, lineageFile, rotationMinSdkVersion, false)
  637. a.extraOutputFiles = append(a.extraOutputFiles, packageFile)
  638. if v4SigningRequested {
  639. a.extraOutputFiles = append(a.extraOutputFiles, v4SignatureFile)
  640. }
  641. }
  642. // Build an app bundle.
  643. bundleFile := android.PathForModuleOut(ctx, "base.zip")
  644. BuildBundleModule(ctx, bundleFile, a.exportPackage, jniJarFile, dexJarFile)
  645. a.bundleFile = bundleFile
  646. allowlist := a.createPrivappAllowlist(ctx)
  647. if allowlist != nil {
  648. a.privAppAllowlist = android.OptionalPathForPath(allowlist)
  649. }
  650. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  651. // Install the app package.
  652. shouldInstallAppPackage := (Bool(a.Module.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() && !a.appProperties.PreventInstall
  653. if shouldInstallAppPackage {
  654. var extraInstalledPaths android.Paths
  655. for _, extra := range a.extraOutputFiles {
  656. installed := ctx.InstallFile(a.installDir, extra.Base(), extra)
  657. extraInstalledPaths = append(extraInstalledPaths, installed)
  658. }
  659. ctx.InstallFile(a.installDir, a.outputFile.Base(), a.outputFile, extraInstalledPaths...)
  660. if a.privAppAllowlist.Valid() {
  661. installPath := android.PathForModuleInstall(ctx, "etc", "permissions")
  662. ctx.InstallFile(installPath, a.privAppAllowlist.Path().Base(), a.privAppAllowlist.Path())
  663. }
  664. }
  665. a.buildAppDependencyInfo(ctx)
  666. }
  667. type appDepsInterface interface {
  668. SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
  669. MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel
  670. RequiresStableAPIs(ctx android.BaseModuleContext) bool
  671. }
  672. func collectAppDeps(ctx android.ModuleContext, app appDepsInterface,
  673. shouldCollectRecursiveNativeDeps bool,
  674. checkNativeSdkVersion bool) ([]jniLib, android.Paths, []Certificate) {
  675. var jniLibs []jniLib
  676. var prebuiltJniPackages android.Paths
  677. var certificates []Certificate
  678. seenModulePaths := make(map[string]bool)
  679. if checkNativeSdkVersion {
  680. checkNativeSdkVersion = app.SdkVersion(ctx).Specified() &&
  681. app.SdkVersion(ctx).Kind != android.SdkCorePlatform && !app.RequiresStableAPIs(ctx)
  682. }
  683. ctx.WalkDeps(func(module android.Module, parent android.Module) bool {
  684. otherName := ctx.OtherModuleName(module)
  685. tag := ctx.OtherModuleDependencyTag(module)
  686. if IsJniDepTag(tag) || cc.IsSharedDepTag(tag) {
  687. if dep, ok := module.(cc.LinkableInterface); ok {
  688. if dep.IsNdk(ctx.Config()) || dep.IsStubs() {
  689. return false
  690. }
  691. lib := dep.OutputFile()
  692. if lib.Valid() {
  693. path := lib.Path()
  694. if seenModulePaths[path.String()] {
  695. return false
  696. }
  697. seenModulePaths[path.String()] = true
  698. if checkNativeSdkVersion && dep.SdkVersion() == "" {
  699. ctx.PropertyErrorf("jni_libs", "JNI dependency %q uses platform APIs, but this module does not",
  700. otherName)
  701. }
  702. jniLibs = append(jniLibs, jniLib{
  703. name: ctx.OtherModuleName(module),
  704. path: path,
  705. target: module.Target(),
  706. coverageFile: dep.CoverageOutputFile(),
  707. unstrippedFile: dep.UnstrippedOutputFile(),
  708. partition: dep.Partition(),
  709. })
  710. } else if ctx.Config().AllowMissingDependencies() {
  711. ctx.AddMissingDependencies([]string{otherName})
  712. } else {
  713. ctx.ModuleErrorf("dependency %q missing output file", otherName)
  714. }
  715. } else {
  716. ctx.ModuleErrorf("jni_libs dependency %q must be a cc library", otherName)
  717. }
  718. return shouldCollectRecursiveNativeDeps
  719. }
  720. if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
  721. prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
  722. }
  723. if tag == certificateTag {
  724. if dep, ok := module.(*AndroidAppCertificate); ok {
  725. certificates = append(certificates, dep.Certificate)
  726. } else {
  727. ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", otherName)
  728. }
  729. }
  730. return false
  731. })
  732. return jniLibs, prebuiltJniPackages, certificates
  733. }
  734. func (a *AndroidApp) WalkPayloadDeps(ctx android.ModuleContext, do android.PayloadDepsCallback) {
  735. ctx.WalkDeps(func(child, parent android.Module) bool {
  736. isExternal := !a.DepIsInSameApex(ctx, child)
  737. if am, ok := child.(android.ApexModule); ok {
  738. if !do(ctx, parent, am, isExternal) {
  739. return false
  740. }
  741. }
  742. return !isExternal
  743. })
  744. }
  745. func (a *AndroidApp) buildAppDependencyInfo(ctx android.ModuleContext) {
  746. if ctx.Host() {
  747. return
  748. }
  749. depsInfo := android.DepNameToDepInfoMap{}
  750. a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
  751. depName := to.Name()
  752. // Skip dependencies that are only available to APEXes; they are developed with updatability
  753. // in mind and don't need manual approval.
  754. if to.(android.ApexModule).NotAvailableForPlatform() {
  755. return true
  756. }
  757. if info, exist := depsInfo[depName]; exist {
  758. info.From = append(info.From, from.Name())
  759. info.IsExternal = info.IsExternal && externalDep
  760. depsInfo[depName] = info
  761. } else {
  762. toMinSdkVersion := "(no version)"
  763. if m, ok := to.(interface {
  764. MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel
  765. }); ok {
  766. if v := m.MinSdkVersion(ctx); !v.IsNone() {
  767. toMinSdkVersion = v.String()
  768. }
  769. } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
  770. // TODO(b/175678607) eliminate the use of MinSdkVersion returning
  771. // string
  772. if v := m.MinSdkVersion(); v != "" {
  773. toMinSdkVersion = v
  774. }
  775. }
  776. depsInfo[depName] = android.ApexModuleDepInfo{
  777. To: depName,
  778. From: []string{from.Name()},
  779. IsExternal: externalDep,
  780. MinSdkVersion: toMinSdkVersion,
  781. }
  782. }
  783. return true
  784. })
  785. a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).String(), depsInfo)
  786. }
  787. func (a *AndroidApp) enforceDefaultTargetSdkVersion() bool {
  788. return a.appProperties.EnforceDefaultTargetSdkVersion
  789. }
  790. func (a *AndroidApp) SetEnforceDefaultTargetSdkVersion(val bool) {
  791. a.appProperties.EnforceDefaultTargetSdkVersion = val
  792. }
  793. func (a *AndroidApp) Updatable() bool {
  794. return Bool(a.appProperties.Updatable)
  795. }
  796. func (a *AndroidApp) SetUpdatable(val bool) {
  797. a.appProperties.Updatable = &val
  798. }
  799. func (a *AndroidApp) getCertString(ctx android.BaseModuleContext) string {
  800. certificate, overridden := ctx.DeviceConfig().OverrideCertificateFor(ctx.ModuleName())
  801. if overridden {
  802. return ":" + certificate
  803. }
  804. return String(a.overridableAppProperties.Certificate)
  805. }
  806. func (a *AndroidApp) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  807. if IsJniDepTag(ctx.OtherModuleDependencyTag(dep)) {
  808. return true
  809. }
  810. return a.Library.DepIsInSameApex(ctx, dep)
  811. }
  812. // For OutputFileProducer interface
  813. func (a *AndroidApp) OutputFiles(tag string) (android.Paths, error) {
  814. switch tag {
  815. // In some instances, it can be useful to reference the aapt-generated flags from another
  816. // target, e.g., system server implements services declared in the framework-res manifest.
  817. case ".aapt.proguardOptionsFile":
  818. return []android.Path{a.proguardOptionsFile}, nil
  819. case ".aapt.srcjar":
  820. return []android.Path{a.aaptSrcJar}, nil
  821. case ".export-package.apk":
  822. return []android.Path{a.exportPackage}, nil
  823. }
  824. return a.Library.OutputFiles(tag)
  825. }
  826. func (a *AndroidApp) Privileged() bool {
  827. return Bool(a.appProperties.Privileged)
  828. }
  829. func (a *AndroidApp) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
  830. return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
  831. }
  832. func (a *AndroidApp) SetPreventInstall() {
  833. a.appProperties.PreventInstall = true
  834. }
  835. func (a *AndroidApp) MarkAsCoverageVariant(coverage bool) {
  836. a.appProperties.IsCoverageVariant = coverage
  837. }
  838. func (a *AndroidApp) EnableCoverageIfNeeded() {}
  839. var _ cc.Coverage = (*AndroidApp)(nil)
  840. // android_app compiles sources and Android resources into an Android application package `.apk` file.
  841. func AndroidAppFactory() android.Module {
  842. module := &AndroidApp{}
  843. module.Module.dexProperties.Optimize.EnabledByDefault = true
  844. module.Module.dexProperties.Optimize.Shrink = proptools.BoolPtr(true)
  845. module.Module.properties.Instrument = true
  846. module.Module.properties.Supports_static_instrumentation = true
  847. module.Module.properties.Installable = proptools.BoolPtr(true)
  848. module.addHostAndDeviceProperties()
  849. module.AddProperties(
  850. &module.aaptProperties,
  851. &module.appProperties,
  852. &module.overridableAppProperties)
  853. module.usesLibrary.enforce = true
  854. android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
  855. android.InitDefaultableModule(module)
  856. android.InitOverridableModule(module, &module.overridableAppProperties.Overrides)
  857. android.InitApexModule(module)
  858. android.InitBazelModule(module)
  859. return module
  860. }
  861. type appTestProperties struct {
  862. // The name of the android_app module that the tests will run against.
  863. Instrumentation_for *string
  864. // If specified, the instrumentation target package name in the manifest is overwritten by it.
  865. Instrumentation_target_package *string
  866. // If specified, the mainline module package name in the test config is overwritten by it.
  867. Mainline_package_name *string
  868. }
  869. type AndroidTest struct {
  870. AndroidApp
  871. appTestProperties appTestProperties
  872. testProperties testProperties
  873. testConfig android.Path
  874. extraTestConfigs android.Paths
  875. data android.Paths
  876. }
  877. func (a *AndroidTest) InstallInTestcases() bool {
  878. return true
  879. }
  880. type androidTestApp interface {
  881. includedInTestSuite(searchPrefix string) bool
  882. }
  883. func (a *AndroidTest) includedInTestSuite(searchPrefix string) bool {
  884. return android.PrefixInList(a.testProperties.Test_suites, searchPrefix)
  885. }
  886. func (a *AndroidTestHelperApp) includedInTestSuite(searchPrefix string) bool {
  887. return android.PrefixInList(a.appTestHelperAppProperties.Test_suites, searchPrefix)
  888. }
  889. func (a *AndroidTest) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  890. var configs []tradefed.Config
  891. if a.appTestProperties.Instrumentation_target_package != nil {
  892. a.additionalAaptFlags = append(a.additionalAaptFlags,
  893. "--rename-instrumentation-target-package "+*a.appTestProperties.Instrumentation_target_package)
  894. } else if a.appTestProperties.Instrumentation_for != nil {
  895. // Check if the instrumentation target package is overridden.
  896. manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(*a.appTestProperties.Instrumentation_for)
  897. if overridden {
  898. a.additionalAaptFlags = append(a.additionalAaptFlags, "--rename-instrumentation-target-package "+manifestPackageName)
  899. }
  900. }
  901. a.generateAndroidBuildActions(ctx)
  902. for _, module := range a.testProperties.Test_mainline_modules {
  903. configs = append(configs, tradefed.Option{Name: "config-descriptor:metadata", Key: "mainline-param", Value: module})
  904. }
  905. testConfig := tradefed.AutoGenInstrumentationTestConfig(ctx, a.testProperties.Test_config,
  906. a.testProperties.Test_config_template, a.manifestPath, a.testProperties.Test_suites, a.testProperties.Auto_gen_config, configs)
  907. a.testConfig = a.FixTestConfig(ctx, testConfig)
  908. a.extraTestConfigs = android.PathsForModuleSrc(ctx, a.testProperties.Test_options.Extra_test_configs)
  909. a.data = android.PathsForModuleSrc(ctx, a.testProperties.Data)
  910. }
  911. func (a *AndroidTest) FixTestConfig(ctx android.ModuleContext, testConfig android.Path) android.Path {
  912. if testConfig == nil {
  913. return nil
  914. }
  915. fixedConfig := android.PathForModuleOut(ctx, "test_config_fixer", "AndroidTest.xml")
  916. rule := android.NewRuleBuilder(pctx, ctx)
  917. command := rule.Command().BuiltTool("test_config_fixer").Input(testConfig).Output(fixedConfig)
  918. fixNeeded := false
  919. // Auto-generated test config uses `ModuleName` as the APK name. So fix it if it is not the case.
  920. if ctx.ModuleName() != a.installApkName {
  921. fixNeeded = true
  922. command.FlagWithArg("--test-file-name ", a.installApkName+".apk")
  923. }
  924. if a.overridableAppProperties.Package_name != nil {
  925. fixNeeded = true
  926. command.FlagWithInput("--manifest ", a.manifestPath).
  927. FlagWithArg("--package-name ", *a.overridableAppProperties.Package_name)
  928. }
  929. if a.appTestProperties.Mainline_package_name != nil {
  930. fixNeeded = true
  931. command.FlagWithArg("--mainline-package-name ", *a.appTestProperties.Mainline_package_name)
  932. }
  933. if fixNeeded {
  934. rule.Build("fix_test_config", "fix test config")
  935. return fixedConfig
  936. }
  937. return testConfig
  938. }
  939. func (a *AndroidTest) DepsMutator(ctx android.BottomUpMutatorContext) {
  940. a.AndroidApp.DepsMutator(ctx)
  941. }
  942. func (a *AndroidTest) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
  943. a.AndroidApp.OverridablePropertiesDepsMutator(ctx)
  944. if a.appTestProperties.Instrumentation_for != nil {
  945. // The android_app dependency listed in instrumentation_for needs to be added to the classpath for javac,
  946. // but not added to the aapt2 link includes like a normal android_app or android_library dependency, so
  947. // use instrumentationForTag instead of libTag.
  948. ctx.AddVariationDependencies(nil, instrumentationForTag, String(a.appTestProperties.Instrumentation_for))
  949. }
  950. }
  951. // android_test compiles test sources and Android resources into an Android application package `.apk` file and
  952. // creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
  953. func AndroidTestFactory() android.Module {
  954. module := &AndroidTest{}
  955. module.Module.dexProperties.Optimize.EnabledByDefault = false
  956. module.Module.properties.Instrument = true
  957. module.Module.properties.Supports_static_instrumentation = true
  958. module.Module.properties.Installable = proptools.BoolPtr(true)
  959. module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
  960. module.appProperties.AlwaysPackageNativeLibs = true
  961. module.Module.dexpreopter.isTest = true
  962. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  963. module.addHostAndDeviceProperties()
  964. module.AddProperties(
  965. &module.aaptProperties,
  966. &module.appProperties,
  967. &module.appTestProperties,
  968. &module.overridableAppProperties,
  969. &module.testProperties)
  970. android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
  971. android.InitDefaultableModule(module)
  972. android.InitOverridableModule(module, &module.overridableAppProperties.Overrides)
  973. return module
  974. }
  975. type appTestHelperAppProperties struct {
  976. // list of compatibility suites (for example "cts", "vts") that the module should be
  977. // installed into.
  978. Test_suites []string `android:"arch_variant"`
  979. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  980. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  981. // explicitly.
  982. Auto_gen_config *bool
  983. // Install the test into a folder named for the module in all test suites.
  984. Per_testcase_directory *bool
  985. }
  986. type AndroidTestHelperApp struct {
  987. AndroidApp
  988. appTestHelperAppProperties appTestHelperAppProperties
  989. }
  990. func (a *AndroidTestHelperApp) InstallInTestcases() bool {
  991. return true
  992. }
  993. // android_test_helper_app compiles sources and Android resources into an Android application package `.apk` file that
  994. // will be used by tests, but does not produce an `AndroidTest.xml` file so the module will not be run directly as a
  995. // test.
  996. func AndroidTestHelperAppFactory() android.Module {
  997. module := &AndroidTestHelperApp{}
  998. // TODO(b/192032291): Disable by default after auditing downstream usage.
  999. module.Module.dexProperties.Optimize.EnabledByDefault = true
  1000. module.Module.properties.Installable = proptools.BoolPtr(true)
  1001. module.appProperties.Use_embedded_native_libs = proptools.BoolPtr(true)
  1002. module.appProperties.AlwaysPackageNativeLibs = true
  1003. module.Module.dexpreopter.isTest = true
  1004. module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
  1005. module.addHostAndDeviceProperties()
  1006. module.AddProperties(
  1007. &module.aaptProperties,
  1008. &module.appProperties,
  1009. &module.appTestHelperAppProperties,
  1010. &module.overridableAppProperties)
  1011. android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
  1012. android.InitDefaultableModule(module)
  1013. android.InitApexModule(module)
  1014. return module
  1015. }
  1016. type AndroidAppCertificate struct {
  1017. android.ModuleBase
  1018. android.BazelModuleBase
  1019. properties AndroidAppCertificateProperties
  1020. Certificate Certificate
  1021. }
  1022. type AndroidAppCertificateProperties struct {
  1023. // Name of the certificate files. Extensions .x509.pem and .pk8 will be added to the name.
  1024. Certificate *string
  1025. }
  1026. // android_app_certificate modules can be referenced by the certificates property of android_app modules to select
  1027. // the signing key.
  1028. func AndroidAppCertificateFactory() android.Module {
  1029. module := &AndroidAppCertificate{}
  1030. module.AddProperties(&module.properties)
  1031. android.InitAndroidModule(module)
  1032. android.InitBazelModule(module)
  1033. return module
  1034. }
  1035. func (c *AndroidAppCertificate) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1036. cert := String(c.properties.Certificate)
  1037. c.Certificate = Certificate{
  1038. Pem: android.PathForModuleSrc(ctx, cert+".x509.pem"),
  1039. Key: android.PathForModuleSrc(ctx, cert+".pk8"),
  1040. }
  1041. }
  1042. type OverrideAndroidApp struct {
  1043. android.ModuleBase
  1044. android.OverrideModuleBase
  1045. }
  1046. func (i *OverrideAndroidApp) GenerateAndroidBuildActions(_ android.ModuleContext) {
  1047. // All the overrides happen in the base module.
  1048. // TODO(jungjw): Check the base module type.
  1049. }
  1050. // override_android_app is used to create an android_app module based on another android_app by overriding
  1051. // some of its properties.
  1052. func OverrideAndroidAppModuleFactory() android.Module {
  1053. m := &OverrideAndroidApp{}
  1054. m.AddProperties(
  1055. &OverridableDeviceProperties{},
  1056. &overridableAppProperties{},
  1057. )
  1058. android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
  1059. android.InitOverrideModule(m)
  1060. return m
  1061. }
  1062. type OverrideAndroidTest struct {
  1063. android.ModuleBase
  1064. android.OverrideModuleBase
  1065. }
  1066. func (i *OverrideAndroidTest) GenerateAndroidBuildActions(_ android.ModuleContext) {
  1067. // All the overrides happen in the base module.
  1068. // TODO(jungjw): Check the base module type.
  1069. }
  1070. // override_android_test is used to create an android_app module based on another android_test by overriding
  1071. // some of its properties.
  1072. func OverrideAndroidTestModuleFactory() android.Module {
  1073. m := &OverrideAndroidTest{}
  1074. m.AddProperties(&overridableAppProperties{})
  1075. m.AddProperties(&appTestProperties{})
  1076. android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
  1077. android.InitOverrideModule(m)
  1078. return m
  1079. }
  1080. type UsesLibraryProperties struct {
  1081. // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file.
  1082. Uses_libs []string
  1083. // A list of shared library modules that will be listed in uses-library tags in the AndroidManifest.xml file with
  1084. // required=false.
  1085. Optional_uses_libs []string
  1086. // If true, the list of uses_libs and optional_uses_libs modules must match the AndroidManifest.xml file. Defaults
  1087. // to true if either uses_libs or optional_uses_libs is set. Will unconditionally default to true in the future.
  1088. Enforce_uses_libs *bool
  1089. // Optional name of the <uses-library> provided by this module. This is needed for non-SDK
  1090. // libraries, because SDK ones are automatically picked up by Soong. The <uses-library> name
  1091. // normally is the same as the module name, but there are exceptions.
  1092. Provides_uses_lib *string
  1093. // A list of shared library names to exclude from the classpath of the APK. Adding a library here
  1094. // will prevent it from being used when precompiling the APK and prevent it from being implicitly
  1095. // added to the APK's manifest's <uses-library> elements.
  1096. //
  1097. // Care must be taken when using this as it could result in runtime errors if the APK actually
  1098. // uses classes provided by the library and which are not provided in any other way.
  1099. //
  1100. // This is primarily intended for use by various CTS tests that check the runtime handling of the
  1101. // android.test.base shared library (and related libraries) but which depend on some common
  1102. // libraries that depend on the android.test.base library. Without this those tests will end up
  1103. // with a <uses-library android:name="android.test.base"/> in their manifest which would either
  1104. // render the tests worthless (as they would be testing the wrong behavior), or would break the
  1105. // test altogether by providing access to classes that the tests were not expecting. Those tests
  1106. // provide the android.test.base statically and use jarjar to rename them so they do not collide
  1107. // with the classes provided by the android.test.base library.
  1108. Exclude_uses_libs []string
  1109. }
  1110. // usesLibrary provides properties and helper functions for AndroidApp and AndroidAppImport to verify that the
  1111. // <uses-library> tags that end up in the manifest of an APK match the ones known to the build system through the
  1112. // uses_libs and optional_uses_libs properties. The build system's values are used by dexpreopt to preopt apps
  1113. // with knowledge of their shared libraries.
  1114. type usesLibrary struct {
  1115. usesLibraryProperties UsesLibraryProperties
  1116. // Whether to enforce verify_uses_library check.
  1117. enforce bool
  1118. }
  1119. func (u *usesLibrary) addLib(lib string, optional bool) {
  1120. if !android.InList(lib, u.usesLibraryProperties.Uses_libs) && !android.InList(lib, u.usesLibraryProperties.Optional_uses_libs) {
  1121. if optional {
  1122. u.usesLibraryProperties.Optional_uses_libs = append(u.usesLibraryProperties.Optional_uses_libs, lib)
  1123. } else {
  1124. u.usesLibraryProperties.Uses_libs = append(u.usesLibraryProperties.Uses_libs, lib)
  1125. }
  1126. }
  1127. }
  1128. func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, addCompatDeps bool) {
  1129. if !ctx.Config().UnbundledBuild() || ctx.Config().UnbundledBuildImage() {
  1130. ctx.AddVariationDependencies(nil, usesLibReqTag, u.usesLibraryProperties.Uses_libs...)
  1131. ctx.AddVariationDependencies(nil, usesLibOptTag, u.presentOptionalUsesLibs(ctx)...)
  1132. // Only add these extra dependencies if the module is an app that depends on framework
  1133. // libs. This avoids creating a cyclic dependency:
  1134. // e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
  1135. if addCompatDeps {
  1136. // Dexpreopt needs paths to the dex jars of these libraries in order to construct
  1137. // class loader context for dex2oat. Add them as a dependency with a special tag.
  1138. ctx.AddVariationDependencies(nil, usesLibCompat29ReqTag, dexpreopt.CompatUsesLibs29...)
  1139. ctx.AddVariationDependencies(nil, usesLibCompat28OptTag, dexpreopt.OptionalCompatUsesLibs28...)
  1140. ctx.AddVariationDependencies(nil, usesLibCompat30OptTag, dexpreopt.OptionalCompatUsesLibs30...)
  1141. }
  1142. } else {
  1143. ctx.AddVariationDependencies(nil, r8LibraryJarTag, u.usesLibraryProperties.Uses_libs...)
  1144. ctx.AddVariationDependencies(nil, r8LibraryJarTag, u.presentOptionalUsesLibs(ctx)...)
  1145. }
  1146. }
  1147. // presentOptionalUsesLibs returns optional_uses_libs after filtering out MissingUsesLibraries, which don't exist in the
  1148. // build.
  1149. func (u *usesLibrary) presentOptionalUsesLibs(ctx android.BaseModuleContext) []string {
  1150. optionalUsesLibs, _ := android.FilterList(u.usesLibraryProperties.Optional_uses_libs, ctx.Config().MissingUsesLibraries())
  1151. return optionalUsesLibs
  1152. }
  1153. // Helper function to replace string in a list.
  1154. func replaceInList(list []string, oldstr, newstr string) {
  1155. for i, str := range list {
  1156. if str == oldstr {
  1157. list[i] = newstr
  1158. }
  1159. }
  1160. }
  1161. // Returns a map of module names of shared library dependencies to the paths to their dex jars on
  1162. // host and on device.
  1163. func (u *usesLibrary) classLoaderContextForUsesLibDeps(ctx android.ModuleContext) dexpreopt.ClassLoaderContextMap {
  1164. clcMap := make(dexpreopt.ClassLoaderContextMap)
  1165. // Skip when UnbundledBuild() is true, but UnbundledBuildImage() is false. With
  1166. // UnbundledBuildImage() it is necessary to generate dexpreopt.config for post-dexpreopting.
  1167. if ctx.Config().UnbundledBuild() && !ctx.Config().UnbundledBuildImage() {
  1168. return clcMap
  1169. }
  1170. ctx.VisitDirectDeps(func(m android.Module) {
  1171. tag, isUsesLibTag := ctx.OtherModuleDependencyTag(m).(usesLibraryDependencyTag)
  1172. if !isUsesLibTag {
  1173. return
  1174. }
  1175. dep := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(m))
  1176. // Skip stub libraries. A dependency on the implementation library has been added earlier,
  1177. // so it will be added to CLC, but the stub shouldn't be. Stub libraries can be distingushed
  1178. // from implementation libraries by their name, which is different as it has a suffix.
  1179. if comp, ok := m.(SdkLibraryComponentDependency); ok {
  1180. if impl := comp.OptionalSdkLibraryImplementation(); impl != nil && *impl != dep {
  1181. return
  1182. }
  1183. }
  1184. if lib, ok := m.(UsesLibraryDependency); ok {
  1185. libName := dep
  1186. if ulib, ok := m.(ProvidesUsesLib); ok && ulib.ProvidesUsesLib() != nil {
  1187. libName = *ulib.ProvidesUsesLib()
  1188. // Replace module name with library name in `uses_libs`/`optional_uses_libs` in
  1189. // order to pass verify_uses_libraries check (which compares these properties
  1190. // against library names written in the manifest).
  1191. replaceInList(u.usesLibraryProperties.Uses_libs, dep, libName)
  1192. replaceInList(u.usesLibraryProperties.Optional_uses_libs, dep, libName)
  1193. }
  1194. clcMap.AddContext(ctx, tag.sdkVersion, libName, tag.optional,
  1195. lib.DexJarBuildPath().PathOrNil(), lib.DexJarInstallPath(),
  1196. lib.ClassLoaderContexts())
  1197. } else if ctx.Config().AllowMissingDependencies() {
  1198. ctx.AddMissingDependencies([]string{dep})
  1199. } else {
  1200. ctx.ModuleErrorf("module %q in uses_libs or optional_uses_libs must be a java library", dep)
  1201. }
  1202. })
  1203. return clcMap
  1204. }
  1205. // enforceUsesLibraries returns true of <uses-library> tags should be checked against uses_libs and optional_uses_libs
  1206. // properties. Defaults to true if either of uses_libs or optional_uses_libs is specified. Will default to true
  1207. // unconditionally in the future.
  1208. func (u *usesLibrary) enforceUsesLibraries() bool {
  1209. defaultEnforceUsesLibs := len(u.usesLibraryProperties.Uses_libs) > 0 ||
  1210. len(u.usesLibraryProperties.Optional_uses_libs) > 0
  1211. return BoolDefault(u.usesLibraryProperties.Enforce_uses_libs, u.enforce || defaultEnforceUsesLibs)
  1212. }
  1213. // Freeze the value of `enforce_uses_libs` based on the current values of `uses_libs` and `optional_uses_libs`.
  1214. func (u *usesLibrary) freezeEnforceUsesLibraries() {
  1215. enforce := u.enforceUsesLibraries()
  1216. u.usesLibraryProperties.Enforce_uses_libs = &enforce
  1217. }
  1218. // verifyUsesLibraries checks the <uses-library> tags in the manifest against the ones specified
  1219. // in the `uses_libs`/`optional_uses_libs` properties. The input can be either an XML manifest, or
  1220. // an APK with the manifest embedded in it (manifest_check will know which one it is by the file
  1221. // extension: APKs are supposed to end with '.apk').
  1222. func (u *usesLibrary) verifyUsesLibraries(ctx android.ModuleContext, inputFile android.Path,
  1223. outputFile android.WritablePath) android.Path {
  1224. statusFile := dexpreopt.UsesLibrariesStatusFile(ctx)
  1225. // Disable verify_uses_libraries check if dexpreopt is globally disabled. Without dexpreopt the
  1226. // check is not necessary, and although it is good to have, it is difficult to maintain on
  1227. // non-linux build platforms where dexpreopt is generally disabled (the check may fail due to
  1228. // various unrelated reasons, such as a failure to get manifest from an APK).
  1229. global := dexpreopt.GetGlobalConfig(ctx)
  1230. if global.DisablePreopt || global.OnlyPreoptBootImageAndSystemServer {
  1231. return inputFile
  1232. }
  1233. rule := android.NewRuleBuilder(pctx, ctx)
  1234. cmd := rule.Command().BuiltTool("manifest_check").
  1235. Flag("--enforce-uses-libraries").
  1236. Input(inputFile).
  1237. FlagWithOutput("--enforce-uses-libraries-status ", statusFile).
  1238. FlagWithInput("--aapt ", ctx.Config().HostToolPath(ctx, "aapt2"))
  1239. if outputFile != nil {
  1240. cmd.FlagWithOutput("-o ", outputFile)
  1241. }
  1242. if dexpreopt.GetGlobalConfig(ctx).RelaxUsesLibraryCheck {
  1243. cmd.Flag("--enforce-uses-libraries-relax")
  1244. }
  1245. for _, lib := range u.usesLibraryProperties.Uses_libs {
  1246. cmd.FlagWithArg("--uses-library ", lib)
  1247. }
  1248. for _, lib := range u.usesLibraryProperties.Optional_uses_libs {
  1249. cmd.FlagWithArg("--optional-uses-library ", lib)
  1250. }
  1251. rule.Build("verify_uses_libraries", "verify <uses-library>")
  1252. return outputFile
  1253. }
  1254. // verifyUsesLibrariesManifest checks the <uses-library> tags in an AndroidManifest.xml against
  1255. // the build system and returns the path to a copy of the manifest.
  1256. func (u *usesLibrary) verifyUsesLibrariesManifest(ctx android.ModuleContext, manifest android.Path) android.Path {
  1257. outputFile := android.PathForModuleOut(ctx, "manifest_check", "AndroidManifest.xml")
  1258. return u.verifyUsesLibraries(ctx, manifest, outputFile)
  1259. }
  1260. // verifyUsesLibrariesAPK checks the <uses-library> tags in the manifest of an APK against the build
  1261. // system and returns the path to a copy of the APK.
  1262. func (u *usesLibrary) verifyUsesLibrariesAPK(ctx android.ModuleContext, apk android.Path) {
  1263. u.verifyUsesLibraries(ctx, apk, nil) // for APKs manifest_check does not write output file
  1264. }
  1265. // For Bazel / bp2build
  1266. type bazelAndroidAppCertificateAttributes struct {
  1267. Certificate string
  1268. }
  1269. func (m *AndroidAppCertificate) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  1270. androidAppCertificateBp2Build(ctx, m)
  1271. }
  1272. func androidAppCertificateBp2Build(ctx android.TopDownMutatorContext, module *AndroidAppCertificate) {
  1273. var certificate string
  1274. if module.properties.Certificate != nil {
  1275. certificate = *module.properties.Certificate
  1276. }
  1277. attrs := &bazelAndroidAppCertificateAttributes{
  1278. Certificate: certificate,
  1279. }
  1280. props := bazel.BazelTargetModuleProperties{
  1281. Rule_class: "android_app_certificate",
  1282. Bzl_load_location: "//build/bazel/rules/android:android_app_certificate.bzl",
  1283. }
  1284. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: module.Name()}, attrs)
  1285. }
  1286. type manifestValueAttribute struct {
  1287. MinSdkVersion *string
  1288. }
  1289. type bazelAndroidAppAttributes struct {
  1290. *javaCommonAttributes
  1291. *bazelAapt
  1292. Deps bazel.LabelListAttribute
  1293. Custom_package *string
  1294. Certificate bazel.LabelAttribute
  1295. Certificate_name bazel.StringAttribute
  1296. Manifest_values *manifestValueAttribute
  1297. }
  1298. // ConvertWithBp2build is used to convert android_app to Bazel.
  1299. func (a *AndroidApp) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  1300. commonAttrs, bp2BuildInfo := a.convertLibraryAttrsBp2Build(ctx)
  1301. depLabels := bp2BuildInfo.DepLabels
  1302. deps := depLabels.Deps
  1303. deps.Append(depLabels.StaticDeps)
  1304. aapt := a.convertAaptAttrsWithBp2Build(ctx)
  1305. certificate, certificateName := android.BazelStringOrLabelFromProp(ctx, a.overridableAppProperties.Certificate)
  1306. manifestValues := &manifestValueAttribute{}
  1307. // TODO(b/274474008 ): Directly convert deviceProperties.Min_sdk_version in bp2build
  1308. // MinSdkVersion(ctx) calls SdkVersion(ctx) if no value for min_sdk_version is set
  1309. minSdkVersion := a.MinSdkVersion(ctx)
  1310. if !minSdkVersion.IsPreview() && !minSdkVersion.IsInvalid() {
  1311. minSdkStr, err := minSdkVersion.EffectiveVersionString(ctx)
  1312. if err == nil {
  1313. manifestValues.MinSdkVersion = &minSdkStr
  1314. }
  1315. }
  1316. appAttrs := &bazelAndroidAppAttributes{
  1317. // TODO(b/209576404): handle package name override by product variable PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
  1318. Custom_package: a.overridableAppProperties.Package_name,
  1319. Certificate: certificate,
  1320. Certificate_name: certificateName,
  1321. Manifest_values: manifestValues,
  1322. }
  1323. props := bazel.BazelTargetModuleProperties{
  1324. Rule_class: "android_binary",
  1325. Bzl_load_location: "//build/bazel/rules/android:android_binary.bzl",
  1326. }
  1327. if !bp2BuildInfo.hasKotlin {
  1328. appAttrs.javaCommonAttributes = commonAttrs
  1329. appAttrs.bazelAapt = aapt
  1330. appAttrs.Deps = deps
  1331. } else {
  1332. ktName := a.Name() + "_kt"
  1333. ctx.CreateBazelTargetModule(
  1334. AndroidLibraryBazelTargetModuleProperties(),
  1335. android.CommonAttributes{Name: ktName},
  1336. &bazelAndroidLibrary{
  1337. javaLibraryAttributes: &javaLibraryAttributes{
  1338. javaCommonAttributes: commonAttrs,
  1339. Deps: deps,
  1340. },
  1341. bazelAapt: aapt,
  1342. },
  1343. )
  1344. appAttrs.bazelAapt = &bazelAapt{Manifest: aapt.Manifest}
  1345. appAttrs.Deps = bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + ktName})
  1346. appAttrs.javaCommonAttributes = &javaCommonAttributes{
  1347. Sdk_version: commonAttrs.Sdk_version,
  1348. }
  1349. }
  1350. ctx.CreateBazelTargetModule(
  1351. props,
  1352. android.CommonAttributes{Name: a.Name(), SkipData: proptools.BoolPtr(true)},
  1353. appAttrs,
  1354. )
  1355. }