app.go 52 KB

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