app.go 61 KB

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