app.go 55 KB

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