aar.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. // Copyright 2018 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. import (
  16. "fmt"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "android/soong/android"
  21. "android/soong/bazel"
  22. "android/soong/dexpreopt"
  23. "github.com/google/blueprint"
  24. "github.com/google/blueprint/proptools"
  25. )
  26. type AndroidLibraryDependency interface {
  27. LibraryDependency
  28. ExportPackage() android.Path
  29. ExportedRRODirs() []rroDir
  30. ExportedStaticPackages() android.Paths
  31. ExportedManifests() android.Paths
  32. ExportedAssets() android.OptionalPath
  33. SetRROEnforcedForDependent(enforce bool)
  34. IsRROEnforced(ctx android.BaseModuleContext) bool
  35. }
  36. func init() {
  37. RegisterAARBuildComponents(android.InitRegistrationContext)
  38. }
  39. func RegisterAARBuildComponents(ctx android.RegistrationContext) {
  40. ctx.RegisterModuleType("android_library_import", AARImportFactory)
  41. ctx.RegisterModuleType("android_library", AndroidLibraryFactory)
  42. ctx.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
  43. ctx.TopDown("propagate_rro_enforcement", propagateRROEnforcementMutator).Parallel()
  44. })
  45. }
  46. //
  47. // AAR (android library)
  48. //
  49. type androidLibraryProperties struct {
  50. BuildAAR bool `blueprint:"mutated"`
  51. }
  52. type aaptProperties struct {
  53. // flags passed to aapt when creating the apk
  54. Aaptflags []string
  55. // include all resource configurations, not just the product-configured
  56. // ones.
  57. Aapt_include_all_resources *bool
  58. // list of directories relative to the Blueprints file containing assets.
  59. // Defaults to ["assets"] if a directory called assets exists. Set to []
  60. // to disable the default.
  61. Asset_dirs []string
  62. // list of directories relative to the Blueprints file containing
  63. // Android resources. Defaults to ["res"] if a directory called res exists.
  64. // Set to [] to disable the default.
  65. Resource_dirs []string
  66. // list of zip files containing Android resources.
  67. Resource_zips []string `android:"path"`
  68. // path to AndroidManifest.xml. If unset, defaults to "AndroidManifest.xml".
  69. Manifest *string `android:"path"`
  70. // paths to additional manifest files to merge with main manifest.
  71. Additional_manifests []string `android:"path"`
  72. // do not include AndroidManifest from dependent libraries
  73. Dont_merge_manifests *bool
  74. // true if RRO is enforced for any of the dependent modules
  75. RROEnforcedForDependent bool `blueprint:"mutated"`
  76. }
  77. type aapt struct {
  78. aaptSrcJar android.Path
  79. exportPackage android.Path
  80. manifestPath android.Path
  81. transitiveManifestPaths android.Paths
  82. proguardOptionsFile android.Path
  83. rroDirs []rroDir
  84. rTxt android.Path
  85. extraAaptPackagesFile android.Path
  86. mergedManifestFile android.Path
  87. noticeFile android.OptionalPath
  88. assetPackage android.OptionalPath
  89. isLibrary bool
  90. defaultManifestVersion string
  91. useEmbeddedNativeLibs bool
  92. useEmbeddedDex bool
  93. usesNonSdkApis bool
  94. hasNoCode bool
  95. LoggingParent string
  96. resourceFiles android.Paths
  97. splitNames []string
  98. splits []split
  99. aaptProperties aaptProperties
  100. }
  101. type split struct {
  102. name string
  103. suffix string
  104. path android.Path
  105. }
  106. // Propagate RRO enforcement flag to static lib dependencies transitively.
  107. func propagateRROEnforcementMutator(ctx android.TopDownMutatorContext) {
  108. m := ctx.Module()
  109. if d, ok := m.(AndroidLibraryDependency); ok && d.IsRROEnforced(ctx) {
  110. ctx.VisitDirectDepsWithTag(staticLibTag, func(d android.Module) {
  111. if a, ok := d.(AndroidLibraryDependency); ok {
  112. a.SetRROEnforcedForDependent(true)
  113. }
  114. })
  115. }
  116. }
  117. func (a *aapt) ExportPackage() android.Path {
  118. return a.exportPackage
  119. }
  120. func (a *aapt) ExportedRRODirs() []rroDir {
  121. return a.rroDirs
  122. }
  123. func (a *aapt) ExportedManifests() android.Paths {
  124. return a.transitiveManifestPaths
  125. }
  126. func (a *aapt) ExportedAssets() android.OptionalPath {
  127. return a.assetPackage
  128. }
  129. func (a *aapt) SetRROEnforcedForDependent(enforce bool) {
  130. a.aaptProperties.RROEnforcedForDependent = enforce
  131. }
  132. func (a *aapt) IsRROEnforced(ctx android.BaseModuleContext) bool {
  133. // True if RRO is enforced for this module or...
  134. return ctx.Config().EnforceRROForModule(ctx.ModuleName()) ||
  135. // if RRO is enforced for any of its dependents.
  136. a.aaptProperties.RROEnforcedForDependent
  137. }
  138. func (a *aapt) aapt2Flags(ctx android.ModuleContext, sdkContext android.SdkContext,
  139. manifestPath android.Path) (compileFlags, linkFlags []string, linkDeps android.Paths,
  140. resDirs, overlayDirs []globbedResourceDir, rroDirs []rroDir, resZips android.Paths) {
  141. hasVersionCode := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-code")
  142. hasVersionName := android.PrefixInList(a.aaptProperties.Aaptflags, "--version-name")
  143. // Flags specified in Android.bp
  144. linkFlags = append(linkFlags, a.aaptProperties.Aaptflags...)
  145. linkFlags = append(linkFlags, "--no-static-lib-packages")
  146. // Find implicit or explicit asset and resource dirs
  147. assetDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Asset_dirs, "assets")
  148. resourceDirs := android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res")
  149. resourceZips := android.PathsForModuleSrc(ctx, a.aaptProperties.Resource_zips)
  150. // Glob directories into lists of paths
  151. for _, dir := range resourceDirs {
  152. resDirs = append(resDirs, globbedResourceDir{
  153. dir: dir,
  154. files: androidResourceGlob(ctx, dir),
  155. })
  156. resOverlayDirs, resRRODirs := overlayResourceGlob(ctx, a, dir)
  157. overlayDirs = append(overlayDirs, resOverlayDirs...)
  158. rroDirs = append(rroDirs, resRRODirs...)
  159. }
  160. var assetDeps android.Paths
  161. for i, dir := range assetDirs {
  162. // Add a dependency on every file in the asset directory. This ensures the aapt2
  163. // rule will be rerun if one of the files in the asset directory is modified.
  164. assetDeps = append(assetDeps, androidResourceGlob(ctx, dir)...)
  165. // Add a dependency on a file that contains a list of all the files in the asset directory.
  166. // This ensures the aapt2 rule will be run if a file is removed from the asset directory,
  167. // or a file is added whose timestamp is older than the output of aapt2.
  168. assetFileListFile := android.PathForModuleOut(ctx, "asset_dir_globs", strconv.Itoa(i)+".glob")
  169. androidResourceGlobList(ctx, dir, assetFileListFile)
  170. assetDeps = append(assetDeps, assetFileListFile)
  171. }
  172. assetDirStrings := assetDirs.Strings()
  173. if a.noticeFile.Valid() {
  174. assetDirStrings = append(assetDirStrings, filepath.Dir(a.noticeFile.Path().String()))
  175. assetDeps = append(assetDeps, a.noticeFile.Path())
  176. }
  177. linkFlags = append(linkFlags, "--manifest "+manifestPath.String())
  178. linkDeps = append(linkDeps, manifestPath)
  179. linkFlags = append(linkFlags, android.JoinWithPrefix(assetDirStrings, "-A "))
  180. linkDeps = append(linkDeps, assetDeps...)
  181. // Returns the effective version for {min|target}_sdk_version
  182. effectiveVersionString := func(sdkVersion android.SdkSpec, minSdkVersion android.ApiLevel) string {
  183. // If {min|target}_sdk_version is current, use sdk_version to determine the effective level
  184. // This is necessary for vendor modules.
  185. // The effective version does not _only_ depend on {min|target}_sdk_version(level),
  186. // but also on the sdk_version (kind+level)
  187. if minSdkVersion.IsCurrent() {
  188. ret, err := sdkVersion.EffectiveVersionString(ctx)
  189. if err != nil {
  190. ctx.ModuleErrorf("invalid sdk_version: %s", err)
  191. }
  192. return ret
  193. }
  194. ret, err := minSdkVersion.EffectiveVersionString(ctx)
  195. if err != nil {
  196. ctx.ModuleErrorf("invalid min_sdk_version: %s", err)
  197. }
  198. return ret
  199. }
  200. // SDK version flags
  201. sdkVersion := sdkContext.SdkVersion(ctx)
  202. minSdkVersion := effectiveVersionString(sdkVersion, sdkContext.MinSdkVersion(ctx))
  203. linkFlags = append(linkFlags, "--min-sdk-version "+minSdkVersion)
  204. // Use minSdkVersion for target-sdk-version, even if `target_sdk_version` is set
  205. // This behavior has been copied from Make.
  206. linkFlags = append(linkFlags, "--target-sdk-version "+minSdkVersion)
  207. // Version code
  208. if !hasVersionCode {
  209. linkFlags = append(linkFlags, "--version-code", ctx.Config().PlatformSdkVersion().String())
  210. }
  211. if !hasVersionName {
  212. var versionName string
  213. if ctx.ModuleName() == "framework-res" {
  214. // Some builds set AppsDefaultVersionName() to include the build number ("O-123456"). aapt2 copies the
  215. // version name of framework-res into app manifests as compileSdkVersionCodename, which confuses things
  216. // if it contains the build number. Use the PlatformVersionName instead.
  217. versionName = ctx.Config().PlatformVersionName()
  218. } else {
  219. versionName = ctx.Config().AppsDefaultVersionName()
  220. }
  221. versionName = proptools.NinjaEscape(versionName)
  222. linkFlags = append(linkFlags, "--version-name ", versionName)
  223. }
  224. linkFlags, compileFlags = android.FilterList(linkFlags, []string{"--legacy"})
  225. // Always set --pseudo-localize, it will be stripped out later for release
  226. // builds that don't want it.
  227. compileFlags = append(compileFlags, "--pseudo-localize")
  228. return compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
  229. }
  230. func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
  231. if sdkDep.frameworkResModule != "" {
  232. ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
  233. }
  234. }
  235. var extractAssetsRule = pctx.AndroidStaticRule("extractAssets",
  236. blueprint.RuleParams{
  237. Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} "assets/**/*"`,
  238. CommandDeps: []string{"${config.Zip2ZipCmd}"},
  239. })
  240. func (a *aapt) buildActions(ctx android.ModuleContext, sdkContext android.SdkContext,
  241. classLoaderContexts dexpreopt.ClassLoaderContextMap, excludedLibs []string,
  242. enforceDefaultTargetSdkVersion bool, extraLinkFlags ...string) {
  243. transitiveStaticLibs, transitiveStaticLibManifests, staticRRODirs, assetPackages, libDeps, libFlags :=
  244. aaptLibs(ctx, sdkContext, classLoaderContexts)
  245. // Exclude any libraries from the supplied list.
  246. classLoaderContexts = classLoaderContexts.ExcludeLibs(excludedLibs)
  247. // App manifest file
  248. manifestFile := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
  249. manifestSrcPath := android.PathForModuleSrc(ctx, manifestFile)
  250. manifestPath := ManifestFixer(ctx, manifestSrcPath, ManifestFixerParams{
  251. SdkContext: sdkContext,
  252. ClassLoaderContexts: classLoaderContexts,
  253. IsLibrary: a.isLibrary,
  254. DefaultManifestVersion: a.defaultManifestVersion,
  255. UseEmbeddedNativeLibs: a.useEmbeddedNativeLibs,
  256. UsesNonSdkApis: a.usesNonSdkApis,
  257. UseEmbeddedDex: a.useEmbeddedDex,
  258. HasNoCode: a.hasNoCode,
  259. LoggingParent: a.LoggingParent,
  260. EnforceDefaultTargetSdkVersion: enforceDefaultTargetSdkVersion,
  261. })
  262. // Add additional manifest files to transitive manifests.
  263. additionalManifests := android.PathsForModuleSrc(ctx, a.aaptProperties.Additional_manifests)
  264. a.transitiveManifestPaths = append(android.Paths{manifestPath}, additionalManifests...)
  265. a.transitiveManifestPaths = append(a.transitiveManifestPaths, transitiveStaticLibManifests...)
  266. if len(a.transitiveManifestPaths) > 1 && !Bool(a.aaptProperties.Dont_merge_manifests) {
  267. a.mergedManifestFile = manifestMerger(ctx, a.transitiveManifestPaths[0], a.transitiveManifestPaths[1:], a.isLibrary)
  268. if !a.isLibrary {
  269. // Only use the merged manifest for applications. For libraries, the transitive closure of manifests
  270. // will be propagated to the final application and merged there. The merged manifest for libraries is
  271. // only passed to Make, which can't handle transitive dependencies.
  272. manifestPath = a.mergedManifestFile
  273. }
  274. } else {
  275. a.mergedManifestFile = manifestPath
  276. }
  277. compileFlags, linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resZips := a.aapt2Flags(ctx, sdkContext, manifestPath)
  278. rroDirs = append(rroDirs, staticRRODirs...)
  279. linkFlags = append(linkFlags, libFlags...)
  280. linkDeps = append(linkDeps, libDeps...)
  281. linkFlags = append(linkFlags, extraLinkFlags...)
  282. if a.isLibrary {
  283. linkFlags = append(linkFlags, "--static-lib")
  284. }
  285. packageRes := android.PathForModuleOut(ctx, "package-res.apk")
  286. // the subdir "android" is required to be filtered by package names
  287. srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
  288. proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
  289. rTxt := android.PathForModuleOut(ctx, "R.txt")
  290. // This file isn't used by Soong, but is generated for exporting
  291. extraPackages := android.PathForModuleOut(ctx, "extra_packages")
  292. var compiledResDirs []android.Paths
  293. for _, dir := range resDirs {
  294. a.resourceFiles = append(a.resourceFiles, dir.files...)
  295. compiledResDirs = append(compiledResDirs, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths())
  296. }
  297. for i, zip := range resZips {
  298. flata := android.PathForModuleOut(ctx, fmt.Sprintf("reszip.%d.flata", i))
  299. aapt2CompileZip(ctx, flata, zip, "", compileFlags)
  300. compiledResDirs = append(compiledResDirs, android.Paths{flata})
  301. }
  302. var compiledRes, compiledOverlay android.Paths
  303. compiledOverlay = append(compiledOverlay, transitiveStaticLibs...)
  304. if len(transitiveStaticLibs) > 0 {
  305. // If we are using static android libraries, every source file becomes an overlay.
  306. // This is to emulate old AAPT behavior which simulated library support.
  307. for _, compiledResDir := range compiledResDirs {
  308. compiledOverlay = append(compiledOverlay, compiledResDir...)
  309. }
  310. } else if a.isLibrary {
  311. // Otherwise, for a static library we treat all the resources equally with no overlay.
  312. for _, compiledResDir := range compiledResDirs {
  313. compiledRes = append(compiledRes, compiledResDir...)
  314. }
  315. } else if len(compiledResDirs) > 0 {
  316. // Without static libraries, the first directory is our directory, which can then be
  317. // overlaid by the rest.
  318. compiledRes = append(compiledRes, compiledResDirs[0]...)
  319. for _, compiledResDir := range compiledResDirs[1:] {
  320. compiledOverlay = append(compiledOverlay, compiledResDir...)
  321. }
  322. }
  323. for _, dir := range overlayDirs {
  324. compiledOverlay = append(compiledOverlay, aapt2Compile(ctx, dir.dir, dir.files, compileFlags).Paths()...)
  325. }
  326. var splitPackages android.WritablePaths
  327. var splits []split
  328. for _, s := range a.splitNames {
  329. suffix := strings.Replace(s, ",", "_", -1)
  330. path := android.PathForModuleOut(ctx, "package_"+suffix+".apk")
  331. linkFlags = append(linkFlags, "--split", path.String()+":"+s)
  332. splitPackages = append(splitPackages, path)
  333. splits = append(splits, split{
  334. name: s,
  335. suffix: suffix,
  336. path: path,
  337. })
  338. }
  339. aapt2Link(ctx, packageRes, srcJar, proguardOptionsFile, rTxt, extraPackages,
  340. linkFlags, linkDeps, compiledRes, compiledOverlay, assetPackages, splitPackages)
  341. // Extract assets from the resource package output so that they can be used later in aapt2link
  342. // for modules that depend on this one.
  343. if android.PrefixInList(linkFlags, "-A ") || len(assetPackages) > 0 {
  344. assets := android.PathForModuleOut(ctx, "assets.zip")
  345. ctx.Build(pctx, android.BuildParams{
  346. Rule: extractAssetsRule,
  347. Input: packageRes,
  348. Output: assets,
  349. Description: "extract assets from built resource file",
  350. })
  351. a.assetPackage = android.OptionalPathForPath(assets)
  352. }
  353. a.aaptSrcJar = srcJar
  354. a.exportPackage = packageRes
  355. a.manifestPath = manifestPath
  356. a.proguardOptionsFile = proguardOptionsFile
  357. a.rroDirs = rroDirs
  358. a.extraAaptPackagesFile = extraPackages
  359. a.rTxt = rTxt
  360. a.splits = splits
  361. }
  362. // aaptLibs collects libraries from dependencies and sdk_version and converts them into paths
  363. func aaptLibs(ctx android.ModuleContext, sdkContext android.SdkContext, classLoaderContexts dexpreopt.ClassLoaderContextMap) (
  364. transitiveStaticLibs, transitiveStaticLibManifests android.Paths, staticRRODirs []rroDir, assets, deps android.Paths, flags []string) {
  365. var sharedLibs android.Paths
  366. if classLoaderContexts == nil {
  367. // Not all callers need to compute class loader context, those who don't just pass nil.
  368. // Create a temporary class loader context here (it will be computed, but not used).
  369. classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
  370. }
  371. sdkDep := decodeSdkDep(ctx, sdkContext)
  372. if sdkDep.useFiles {
  373. sharedLibs = append(sharedLibs, sdkDep.jars...)
  374. }
  375. ctx.VisitDirectDeps(func(module android.Module) {
  376. depTag := ctx.OtherModuleDependencyTag(module)
  377. var exportPackage android.Path
  378. aarDep, _ := module.(AndroidLibraryDependency)
  379. if aarDep != nil {
  380. exportPackage = aarDep.ExportPackage()
  381. }
  382. switch depTag {
  383. case instrumentationForTag:
  384. // Nothing, instrumentationForTag is treated as libTag for javac but not for aapt2.
  385. case sdkLibTag, libTag:
  386. if exportPackage != nil {
  387. sharedLibs = append(sharedLibs, exportPackage)
  388. }
  389. case frameworkResTag:
  390. if exportPackage != nil {
  391. sharedLibs = append(sharedLibs, exportPackage)
  392. }
  393. case staticLibTag:
  394. if exportPackage != nil {
  395. transitiveStaticLibs = append(transitiveStaticLibs, aarDep.ExportedStaticPackages()...)
  396. transitiveStaticLibs = append(transitiveStaticLibs, exportPackage)
  397. transitiveStaticLibManifests = append(transitiveStaticLibManifests, aarDep.ExportedManifests()...)
  398. if aarDep.ExportedAssets().Valid() {
  399. assets = append(assets, aarDep.ExportedAssets().Path())
  400. }
  401. outer:
  402. for _, d := range aarDep.ExportedRRODirs() {
  403. for _, e := range staticRRODirs {
  404. if d.path == e.path {
  405. continue outer
  406. }
  407. }
  408. staticRRODirs = append(staticRRODirs, d)
  409. }
  410. }
  411. }
  412. addCLCFromDep(ctx, module, classLoaderContexts)
  413. })
  414. deps = append(deps, sharedLibs...)
  415. deps = append(deps, transitiveStaticLibs...)
  416. if len(transitiveStaticLibs) > 0 {
  417. flags = append(flags, "--auto-add-overlay")
  418. }
  419. for _, sharedLib := range sharedLibs {
  420. flags = append(flags, "-I "+sharedLib.String())
  421. }
  422. transitiveStaticLibs = android.FirstUniquePaths(transitiveStaticLibs)
  423. transitiveStaticLibManifests = android.FirstUniquePaths(transitiveStaticLibManifests)
  424. return transitiveStaticLibs, transitiveStaticLibManifests, staticRRODirs, assets, deps, flags
  425. }
  426. type AndroidLibrary struct {
  427. Library
  428. aapt
  429. android.BazelModuleBase
  430. androidLibraryProperties androidLibraryProperties
  431. aarFile android.WritablePath
  432. exportedStaticPackages android.Paths
  433. }
  434. var _ android.OutputFileProducer = (*AndroidLibrary)(nil)
  435. // For OutputFileProducer interface
  436. func (a *AndroidLibrary) OutputFiles(tag string) (android.Paths, error) {
  437. switch tag {
  438. case ".aar":
  439. return []android.Path{a.aarFile}, nil
  440. default:
  441. return a.Library.OutputFiles(tag)
  442. }
  443. }
  444. func (a *AndroidLibrary) ExportedStaticPackages() android.Paths {
  445. return a.exportedStaticPackages
  446. }
  447. var _ AndroidLibraryDependency = (*AndroidLibrary)(nil)
  448. func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
  449. a.Module.deps(ctx)
  450. sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
  451. if sdkDep.hasFrameworkLibs() {
  452. a.aapt.deps(ctx, sdkDep)
  453. }
  454. a.usesLibrary.deps(ctx, false)
  455. }
  456. func (a *AndroidLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  457. a.aapt.isLibrary = true
  458. a.classLoaderContexts = a.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
  459. a.aapt.buildActions(ctx, android.SdkContext(a), a.classLoaderContexts, nil, false)
  460. a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
  461. ctx.CheckbuildFile(a.proguardOptionsFile)
  462. ctx.CheckbuildFile(a.exportPackage)
  463. ctx.CheckbuildFile(a.aaptSrcJar)
  464. // apps manifests are handled by aapt, don't let Module see them
  465. a.properties.Manifest = nil
  466. a.linter.mergedManifest = a.aapt.mergedManifestFile
  467. a.linter.manifest = a.aapt.manifestPath
  468. a.linter.resources = a.aapt.resourceFiles
  469. a.Module.extraProguardFlagFiles = append(a.Module.extraProguardFlagFiles,
  470. a.proguardOptionsFile)
  471. a.Module.compile(ctx, a.aaptSrcJar)
  472. a.aarFile = android.PathForModuleOut(ctx, ctx.ModuleName()+".aar")
  473. var res android.Paths
  474. if a.androidLibraryProperties.BuildAAR {
  475. BuildAAR(ctx, a.aarFile, a.outputFile, a.manifestPath, a.rTxt, res)
  476. ctx.CheckbuildFile(a.aarFile)
  477. }
  478. a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles,
  479. android.PathsForModuleSrc(ctx, a.dexProperties.Optimize.Proguard_flags_files)...)
  480. ctx.VisitDirectDeps(func(m android.Module) {
  481. if ctx.OtherModuleDependencyTag(m) == staticLibTag {
  482. if lib, ok := m.(LibraryDependency); ok {
  483. a.exportedProguardFlagFiles = append(a.exportedProguardFlagFiles, lib.ExportedProguardFlagFiles()...)
  484. }
  485. if alib, ok := m.(AndroidLibraryDependency); ok {
  486. a.exportedStaticPackages = append(a.exportedStaticPackages, alib.ExportPackage())
  487. a.exportedStaticPackages = append(a.exportedStaticPackages, alib.ExportedStaticPackages()...)
  488. }
  489. }
  490. })
  491. a.exportedProguardFlagFiles = android.FirstUniquePaths(a.exportedProguardFlagFiles)
  492. a.exportedStaticPackages = android.FirstUniquePaths(a.exportedStaticPackages)
  493. prebuiltJniPackages := android.Paths{}
  494. ctx.VisitDirectDeps(func(module android.Module) {
  495. if info, ok := ctx.OtherModuleProvider(module, JniPackageProvider).(JniPackageInfo); ok {
  496. prebuiltJniPackages = append(prebuiltJniPackages, info.JniPackages...)
  497. }
  498. })
  499. if len(prebuiltJniPackages) > 0 {
  500. ctx.SetProvider(JniPackageProvider, JniPackageInfo{
  501. JniPackages: prebuiltJniPackages,
  502. })
  503. }
  504. }
  505. // android_library builds and links sources into a `.jar` file for the device along with Android resources.
  506. //
  507. // An android_library has a single variant that produces a `.jar` file containing `.class` files that were
  508. // compiled against the device bootclasspath, along with a `package-res.apk` file containing Android resources compiled
  509. // with aapt2. This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
  510. // an android_app module.
  511. func AndroidLibraryFactory() android.Module {
  512. module := &AndroidLibrary{}
  513. module.Module.addHostAndDeviceProperties()
  514. module.AddProperties(
  515. &module.aaptProperties,
  516. &module.androidLibraryProperties)
  517. module.androidLibraryProperties.BuildAAR = true
  518. module.Module.linter.library = true
  519. android.InitApexModule(module)
  520. InitJavaModule(module, android.DeviceSupported)
  521. android.InitBazelModule(module)
  522. return module
  523. }
  524. //
  525. // AAR (android library) prebuilts
  526. //
  527. // Properties for android_library_import
  528. type AARImportProperties struct {
  529. // ARR (android library prebuilt) filepath. Exactly one ARR is required.
  530. Aars []string `android:"path"`
  531. // If not blank, set to the version of the sdk to compile against.
  532. // Defaults to private.
  533. // Values are of one of the following forms:
  534. // 1) numerical API level, "current", "none", or "core_platform"
  535. // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
  536. // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
  537. // If the SDK kind is empty, it will be set to public
  538. Sdk_version *string
  539. // If not blank, set the minimum version of the sdk that the compiled artifacts will run against.
  540. // Defaults to sdk_version if not set. See sdk_version for possible values.
  541. Min_sdk_version *string
  542. // List of java static libraries that the included ARR (android library prebuilts) has dependencies to.
  543. Static_libs []string
  544. // List of java libraries that the included ARR (android library prebuilts) has dependencies to.
  545. Libs []string
  546. // If set to true, run Jetifier against .aar file. Defaults to false.
  547. Jetifier *bool
  548. // If true, extract JNI libs from AAR archive. These libs will be accessible to android_app modules and
  549. // will be passed transitively through android_libraries to an android_app.
  550. //TODO(b/241138093) evaluate whether we can have this flag default to true for Bazel conversion
  551. Extract_jni *bool
  552. }
  553. type AARImport struct {
  554. android.ModuleBase
  555. android.DefaultableModuleBase
  556. android.ApexModuleBase
  557. android.BazelModuleBase
  558. prebuilt android.Prebuilt
  559. // Functionality common to Module and Import.
  560. embeddableInModuleAndImport
  561. providesTransitiveHeaderJars
  562. properties AARImportProperties
  563. classpathFile android.WritablePath
  564. proguardFlags android.WritablePath
  565. exportPackage android.WritablePath
  566. extraAaptPackagesFile android.WritablePath
  567. manifest android.WritablePath
  568. assetsPackage android.WritablePath
  569. exportedStaticPackages android.Paths
  570. hideApexVariantFromMake bool
  571. aarPath android.Path
  572. jniPackages android.Paths
  573. sdkVersion android.SdkSpec
  574. minSdkVersion android.ApiLevel
  575. }
  576. var _ android.OutputFileProducer = (*AARImport)(nil)
  577. // For OutputFileProducer interface
  578. func (a *AARImport) OutputFiles(tag string) (android.Paths, error) {
  579. switch tag {
  580. case ".aar":
  581. return []android.Path{a.aarPath}, nil
  582. case "":
  583. return []android.Path{a.classpathFile}, nil
  584. default:
  585. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  586. }
  587. }
  588. func (a *AARImport) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
  589. return android.SdkSpecFrom(ctx, String(a.properties.Sdk_version))
  590. }
  591. func (a *AARImport) SystemModules() string {
  592. return ""
  593. }
  594. func (a *AARImport) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  595. if a.properties.Min_sdk_version != nil {
  596. return android.ApiLevelFrom(ctx, *a.properties.Min_sdk_version)
  597. }
  598. return a.SdkVersion(ctx).ApiLevel
  599. }
  600. func (a *AARImport) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
  601. return android.SdkSpecFrom(ctx, "").ApiLevel
  602. }
  603. func (a *AARImport) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
  604. return a.SdkVersion(ctx).ApiLevel
  605. }
  606. func (a *AARImport) javaVersion() string {
  607. return ""
  608. }
  609. var _ AndroidLibraryDependency = (*AARImport)(nil)
  610. func (a *AARImport) ExportPackage() android.Path {
  611. return a.exportPackage
  612. }
  613. func (a *AARImport) ExportedProguardFlagFiles() android.Paths {
  614. return android.Paths{a.proguardFlags}
  615. }
  616. func (a *AARImport) ExportedRRODirs() []rroDir {
  617. return nil
  618. }
  619. func (a *AARImport) ExportedStaticPackages() android.Paths {
  620. return a.exportedStaticPackages
  621. }
  622. func (a *AARImport) ExportedManifests() android.Paths {
  623. return android.Paths{a.manifest}
  624. }
  625. func (a *AARImport) ExportedAssets() android.OptionalPath {
  626. return android.OptionalPathForPath(a.assetsPackage)
  627. }
  628. // RRO enforcement is not available on aar_import since its RRO dirs are not
  629. // exported.
  630. func (a *AARImport) SetRROEnforcedForDependent(enforce bool) {
  631. }
  632. // RRO enforcement is not available on aar_import since its RRO dirs are not
  633. // exported.
  634. func (a *AARImport) IsRROEnforced(ctx android.BaseModuleContext) bool {
  635. return false
  636. }
  637. func (a *AARImport) Prebuilt() *android.Prebuilt {
  638. return &a.prebuilt
  639. }
  640. func (a *AARImport) Name() string {
  641. return a.prebuilt.Name(a.ModuleBase.Name())
  642. }
  643. func (a *AARImport) JacocoReportClassesFile() android.Path {
  644. return nil
  645. }
  646. func (a *AARImport) DepsMutator(ctx android.BottomUpMutatorContext) {
  647. if !ctx.Config().AlwaysUsePrebuiltSdks() {
  648. sdkDep := decodeSdkDep(ctx, android.SdkContext(a))
  649. if sdkDep.useModule && sdkDep.frameworkResModule != "" {
  650. ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
  651. }
  652. }
  653. ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
  654. ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
  655. }
  656. type JniPackageInfo struct {
  657. // List of zip files containing JNI libraries
  658. // Zip files should have directory structure jni/<arch>/*.so
  659. JniPackages android.Paths
  660. }
  661. var JniPackageProvider = blueprint.NewProvider(JniPackageInfo{})
  662. // Unzip an AAR and extract the JNI libs for $archString.
  663. var extractJNI = pctx.AndroidStaticRule("extractJNI",
  664. blueprint.RuleParams{
  665. Command: `rm -rf $out $outDir && touch $out && ` +
  666. `unzip -qoDD -d $outDir $in "jni/${archString}/*" && ` +
  667. `jni_files=$$(find $outDir/jni -type f) && ` +
  668. // print error message if there are no JNI libs for this arch
  669. `[ -n "$$jni_files" ] || (echo "ERROR: no JNI libs found for arch ${archString}" && exit 1) && ` +
  670. `${config.SoongZipCmd} -o $out -P 'lib/${archString}' ` +
  671. `-C $outDir/jni/${archString} $$(echo $$jni_files | xargs -n1 printf " -f %s")`,
  672. CommandDeps: []string{"${config.SoongZipCmd}"},
  673. },
  674. "outDir", "archString")
  675. // Unzip an AAR into its constituent files and directories. Any files in Outputs that don't exist in the AAR will be
  676. // touched to create an empty file. The res directory is not extracted, as it will be extracted in its own rule.
  677. var unzipAAR = pctx.AndroidStaticRule("unzipAAR",
  678. blueprint.RuleParams{
  679. Command: `rm -rf $outDir && mkdir -p $outDir && ` +
  680. `unzip -qoDD -d $outDir $in && rm -rf $outDir/res && touch $out && ` +
  681. `${config.Zip2ZipCmd} -i $in -o $assetsPackage 'assets/**/*' && ` +
  682. `${config.MergeZipsCmd} $combinedClassesJar $$(ls $outDir/classes.jar 2> /dev/null) $$(ls $outDir/libs/*.jar 2> /dev/null)`,
  683. CommandDeps: []string{"${config.MergeZipsCmd}", "${config.Zip2ZipCmd}"},
  684. },
  685. "outDir", "combinedClassesJar", "assetsPackage")
  686. func (a *AARImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  687. if len(a.properties.Aars) != 1 {
  688. ctx.PropertyErrorf("aars", "exactly one aar is required")
  689. return
  690. }
  691. a.sdkVersion = a.SdkVersion(ctx)
  692. a.minSdkVersion = a.MinSdkVersion(ctx)
  693. a.hideApexVariantFromMake = !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform()
  694. aarName := ctx.ModuleName() + ".aar"
  695. a.aarPath = android.PathForModuleSrc(ctx, a.properties.Aars[0])
  696. if Bool(a.properties.Jetifier) {
  697. inputFile := a.aarPath
  698. a.aarPath = android.PathForModuleOut(ctx, "jetifier", aarName)
  699. TransformJetifier(ctx, a.aarPath.(android.WritablePath), inputFile)
  700. }
  701. extractedAARDir := android.PathForModuleOut(ctx, "aar")
  702. a.classpathFile = extractedAARDir.Join(ctx, "classes-combined.jar")
  703. a.proguardFlags = extractedAARDir.Join(ctx, "proguard.txt")
  704. a.manifest = extractedAARDir.Join(ctx, "AndroidManifest.xml")
  705. a.assetsPackage = android.PathForModuleOut(ctx, "assets.zip")
  706. ctx.Build(pctx, android.BuildParams{
  707. Rule: unzipAAR,
  708. Input: a.aarPath,
  709. Outputs: android.WritablePaths{a.classpathFile, a.proguardFlags, a.manifest, a.assetsPackage},
  710. Description: "unzip AAR",
  711. Args: map[string]string{
  712. "outDir": extractedAARDir.String(),
  713. "combinedClassesJar": a.classpathFile.String(),
  714. "assetsPackage": a.assetsPackage.String(),
  715. },
  716. })
  717. // Always set --pseudo-localize, it will be stripped out later for release
  718. // builds that don't want it.
  719. compileFlags := []string{"--pseudo-localize"}
  720. compiledResDir := android.PathForModuleOut(ctx, "flat-res")
  721. flata := compiledResDir.Join(ctx, "gen_res.flata")
  722. aapt2CompileZip(ctx, flata, a.aarPath, "res", compileFlags)
  723. a.exportPackage = android.PathForModuleOut(ctx, "package-res.apk")
  724. // the subdir "android" is required to be filtered by package names
  725. srcJar := android.PathForModuleGen(ctx, "android", "R.srcjar")
  726. proguardOptionsFile := android.PathForModuleGen(ctx, "proguard.options")
  727. rTxt := android.PathForModuleOut(ctx, "R.txt")
  728. a.extraAaptPackagesFile = android.PathForModuleOut(ctx, "extra_packages")
  729. var linkDeps android.Paths
  730. linkFlags := []string{
  731. "--static-lib",
  732. "--no-static-lib-packages",
  733. "--auto-add-overlay",
  734. }
  735. linkFlags = append(linkFlags, "--manifest "+a.manifest.String())
  736. linkDeps = append(linkDeps, a.manifest)
  737. transitiveStaticLibs, staticLibManifests, staticRRODirs, transitiveAssets, libDeps, libFlags :=
  738. aaptLibs(ctx, android.SdkContext(a), nil)
  739. _ = staticLibManifests
  740. _ = staticRRODirs
  741. linkDeps = append(linkDeps, libDeps...)
  742. linkFlags = append(linkFlags, libFlags...)
  743. overlayRes := append(android.Paths{flata}, transitiveStaticLibs...)
  744. aapt2Link(ctx, a.exportPackage, srcJar, proguardOptionsFile, rTxt, a.extraAaptPackagesFile,
  745. linkFlags, linkDeps, nil, overlayRes, transitiveAssets, nil)
  746. // Merge this import's assets with its dependencies' assets (if there are any).
  747. if len(transitiveAssets) > 0 {
  748. mergedAssets := android.PathForModuleOut(ctx, "merged-assets.zip")
  749. inputZips := append(android.Paths{a.assetsPackage}, transitiveAssets...)
  750. ctx.Build(pctx, android.BuildParams{
  751. Rule: mergeAssetsRule,
  752. Inputs: inputZips,
  753. Output: mergedAssets,
  754. Description: "merge assets from dependencies and self",
  755. })
  756. a.assetsPackage = mergedAssets
  757. }
  758. a.collectTransitiveHeaderJars(ctx)
  759. ctx.SetProvider(JavaInfoProvider, JavaInfo{
  760. HeaderJars: android.PathsIfNonNil(a.classpathFile),
  761. TransitiveLibsHeaderJars: a.transitiveLibsHeaderJars,
  762. TransitiveStaticLibsHeaderJars: a.transitiveStaticLibsHeaderJars,
  763. ImplementationAndResourcesJars: android.PathsIfNonNil(a.classpathFile),
  764. ImplementationJars: android.PathsIfNonNil(a.classpathFile),
  765. })
  766. if proptools.Bool(a.properties.Extract_jni) {
  767. for _, t := range ctx.MultiTargets() {
  768. arch := t.Arch.Abi[0]
  769. path := android.PathForModuleOut(ctx, arch+"_jni.zip")
  770. a.jniPackages = append(a.jniPackages, path)
  771. outDir := android.PathForModuleOut(ctx, "aarForJni")
  772. aarPath := android.PathForModuleSrc(ctx, a.properties.Aars[0])
  773. ctx.Build(pctx, android.BuildParams{
  774. Rule: extractJNI,
  775. Input: aarPath,
  776. Outputs: android.WritablePaths{path},
  777. Description: "extract JNI from AAR",
  778. Args: map[string]string{
  779. "outDir": outDir.String(),
  780. "archString": arch,
  781. },
  782. })
  783. }
  784. ctx.SetProvider(JniPackageProvider, JniPackageInfo{
  785. JniPackages: a.jniPackages,
  786. })
  787. }
  788. }
  789. func (a *AARImport) HeaderJars() android.Paths {
  790. return android.Paths{a.classpathFile}
  791. }
  792. func (a *AARImport) ImplementationAndResourcesJars() android.Paths {
  793. return android.Paths{a.classpathFile}
  794. }
  795. func (a *AARImport) DexJarBuildPath() android.Path {
  796. return nil
  797. }
  798. func (a *AARImport) DexJarInstallPath() android.Path {
  799. return nil
  800. }
  801. func (a *AARImport) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
  802. return nil
  803. }
  804. var _ android.ApexModule = (*AARImport)(nil)
  805. // Implements android.ApexModule
  806. func (a *AARImport) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  807. return a.depIsInSameApex(ctx, dep)
  808. }
  809. // Implements android.ApexModule
  810. func (g *AARImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
  811. sdkVersion android.ApiLevel) error {
  812. return nil
  813. }
  814. var _ android.PrebuiltInterface = (*AARImport)(nil)
  815. // android_library_import imports an `.aar` file into the build graph as if it was built with android_library.
  816. //
  817. // This module is not suitable for installing on a device, but can be used as a `static_libs` dependency of
  818. // an android_app module.
  819. func AARImportFactory() android.Module {
  820. module := &AARImport{}
  821. module.AddProperties(&module.properties)
  822. android.InitPrebuiltModule(module, &module.properties.Aars)
  823. android.InitApexModule(module)
  824. InitJavaModuleMultiTargets(module, android.DeviceSupported)
  825. android.InitBazelModule(module)
  826. return module
  827. }
  828. type bazelAapt struct {
  829. Manifest bazel.Label
  830. Resource_files bazel.LabelListAttribute
  831. }
  832. type bazelAndroidLibrary struct {
  833. *javaLibraryAttributes
  834. *bazelAapt
  835. }
  836. type bazelAndroidLibraryImport struct {
  837. Aar bazel.Label
  838. Deps bazel.LabelListAttribute
  839. Exports bazel.LabelListAttribute
  840. Sdk_version bazel.StringAttribute
  841. }
  842. func (a *aapt) convertAaptAttrsWithBp2Build(ctx android.TopDownMutatorContext) *bazelAapt {
  843. manifest := proptools.StringDefault(a.aaptProperties.Manifest, "AndroidManifest.xml")
  844. resourceFiles := bazel.LabelList{
  845. Includes: []bazel.Label{},
  846. }
  847. for _, dir := range android.PathsWithOptionalDefaultForModuleSrc(ctx, a.aaptProperties.Resource_dirs, "res") {
  848. files := android.RootToModuleRelativePaths(ctx, androidResourceGlob(ctx, dir))
  849. resourceFiles.Includes = append(resourceFiles.Includes, files...)
  850. }
  851. return &bazelAapt{
  852. android.BazelLabelForModuleSrcSingle(ctx, manifest),
  853. bazel.MakeLabelListAttribute(resourceFiles),
  854. }
  855. }
  856. func (a *AARImport) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  857. aars := android.BazelLabelForModuleSrcExcludes(ctx, a.properties.Aars, []string{})
  858. exportableStaticLibs := []string{}
  859. // TODO(b/240716882): investigate and handle static_libs deps that are not imports. They are not supported for export by Bazel.
  860. for _, depName := range a.properties.Static_libs {
  861. if dep, ok := ctx.ModuleFromName(depName); ok {
  862. switch dep.(type) {
  863. case *AARImport, *Import:
  864. exportableStaticLibs = append(exportableStaticLibs, depName)
  865. }
  866. }
  867. }
  868. name := android.RemoveOptionalPrebuiltPrefix(a.Name())
  869. deps := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(append(a.properties.Static_libs, a.properties.Libs...))))
  870. exports := android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(exportableStaticLibs))
  871. ctx.CreateBazelTargetModule(
  872. bazel.BazelTargetModuleProperties{
  873. Rule_class: "aar_import",
  874. Bzl_load_location: "//build/bazel/rules/android:aar_import.bzl",
  875. },
  876. android.CommonAttributes{Name: name},
  877. &bazelAndroidLibraryImport{
  878. Aar: aars.Includes[0],
  879. Deps: bazel.MakeLabelListAttribute(deps),
  880. Exports: bazel.MakeLabelListAttribute(exports),
  881. Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
  882. },
  883. )
  884. neverlink := true
  885. ctx.CreateBazelTargetModule(
  886. AndroidLibraryBazelTargetModuleProperties(),
  887. android.CommonAttributes{Name: name + "-neverlink"},
  888. &bazelAndroidLibrary{
  889. javaLibraryAttributes: &javaLibraryAttributes{
  890. Neverlink: bazel.BoolAttribute{Value: &neverlink},
  891. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  892. javaCommonAttributes: &javaCommonAttributes{
  893. Sdk_version: bazel.StringAttribute{Value: a.properties.Sdk_version},
  894. },
  895. },
  896. },
  897. )
  898. }
  899. func AndroidLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
  900. return bazel.BazelTargetModuleProperties{
  901. Rule_class: "android_library",
  902. Bzl_load_location: "//build/bazel/rules/android:android_library.bzl",
  903. }
  904. }
  905. func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
  906. commonAttrs, bp2buildInfo := a.convertLibraryAttrsBp2Build(ctx)
  907. depLabels := bp2buildInfo.DepLabels
  908. deps := depLabels.Deps
  909. if !commonAttrs.Srcs.IsEmpty() {
  910. deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
  911. } else if !depLabels.Deps.IsEmpty() {
  912. ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
  913. }
  914. name := a.Name()
  915. props := AndroidLibraryBazelTargetModuleProperties()
  916. ctx.CreateBazelTargetModule(
  917. props,
  918. android.CommonAttributes{Name: name},
  919. &bazelAndroidLibrary{
  920. &javaLibraryAttributes{
  921. javaCommonAttributes: commonAttrs,
  922. Deps: deps,
  923. Exports: depLabels.StaticDeps,
  924. },
  925. a.convertAaptAttrsWithBp2Build(ctx),
  926. },
  927. )
  928. neverlink := true
  929. ctx.CreateBazelTargetModule(
  930. props,
  931. android.CommonAttributes{Name: name + "-neverlink"},
  932. &bazelAndroidLibrary{
  933. javaLibraryAttributes: &javaLibraryAttributes{
  934. Neverlink: bazel.BoolAttribute{Value: &neverlink},
  935. Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
  936. javaCommonAttributes: &javaCommonAttributes{
  937. Sdk_version: bazel.StringAttribute{Value: a.deviceProperties.Sdk_version},
  938. Java_version: bazel.StringAttribute{Value: a.properties.Java_version},
  939. },
  940. },
  941. },
  942. )
  943. }