apex.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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 android
  15. import (
  16. "fmt"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "github.com/google/blueprint"
  22. )
  23. var (
  24. // This is the sdk version when APEX was first introduced
  25. SdkVersion_Android10 = uncheckedFinalApiLevel(29)
  26. )
  27. // ApexInfo describes the metadata about one or more apexBundles that an apex variant of a module is
  28. // part of. When an apex variant is created, the variant is associated with one apexBundle. But
  29. // when multiple apex variants are merged for deduping (see mergeApexVariations), this holds the
  30. // information about the apexBundles that are merged together.
  31. // Accessible via `ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)`
  32. type ApexInfo struct {
  33. // Name of the apex variation that this module (i.e. the apex variant of the module) is
  34. // mutated into, or "" for a platform (i.e. non-APEX) variant. Note that this name and the
  35. // Soong module name of the APEX can be different. That happens when there is
  36. // `override_apex` that overrides `apex`. In that case, both Soong modules have the same
  37. // apex variation name which usually is `com.android.foo`. This name is also the `name`
  38. // in the path `/apex/<name>` where this apex is activated on at runtime.
  39. //
  40. // Also note that a module can be included in multiple APEXes, in which case, the module is
  41. // mutated into one or more variants, each of which is for an APEX. The variants then can
  42. // later be deduped if they don't need to be compiled differently. This is an optimization
  43. // done in mergeApexVariations.
  44. ApexVariationName string
  45. // ApiLevel that this module has to support at minimum.
  46. MinSdkVersion ApiLevel
  47. // True if this module comes from an updatable apexBundle.
  48. Updatable bool
  49. // True if this module can use private platform APIs. Only non-updatable APEX can set this
  50. // to true.
  51. UsePlatformApis bool
  52. // List of Apex variant names that this module is associated with. This initially is the
  53. // same as the `ApexVariationName` field. Then when multiple apex variants are merged in
  54. // mergeApexVariations, ApexInfo struct of the merged variant holds the list of apexBundles
  55. // that are merged together.
  56. InApexVariants []string
  57. // List of APEX Soong module names that this module is part of. Note that the list includes
  58. // different variations of the same APEX. For example, if module `foo` is included in the
  59. // apex `com.android.foo`, and also if there is an override_apex module
  60. // `com.mycompany.android.foo` overriding `com.android.foo`, then this list contains both
  61. // `com.android.foo` and `com.mycompany.android.foo`. If the APEX Soong module is a
  62. // prebuilt, the name here doesn't have the `prebuilt_` prefix.
  63. InApexModules []string
  64. // Pointers to the ApexContents struct each of which is for apexBundle modules that this
  65. // module is part of. The ApexContents gives information about which modules the apexBundle
  66. // has and whether a module became part of the apexBundle via a direct dependency or not.
  67. ApexContents []*ApexContents
  68. // True if this is for a prebuilt_apex.
  69. //
  70. // If true then this will customize the apex processing to make it suitable for handling
  71. // prebuilt_apex, e.g. it will prevent ApexInfos from being merged together.
  72. //
  73. // See Prebuilt.ApexInfoMutator for more information.
  74. ForPrebuiltApex bool
  75. }
  76. var ApexInfoProvider = blueprint.NewMutatorProvider(ApexInfo{}, "apex")
  77. func (i ApexInfo) AddJSONData(d *map[string]interface{}) {
  78. (*d)["Apex"] = map[string]interface{}{
  79. "ApexVariationName": i.ApexVariationName,
  80. "MinSdkVersion": i.MinSdkVersion,
  81. "InApexModules": i.InApexModules,
  82. "InApexVariants": i.InApexVariants,
  83. "ForPrebuiltApex": i.ForPrebuiltApex,
  84. }
  85. }
  86. // mergedName gives the name of the alias variation that will be used when multiple apex variations
  87. // of a module can be deduped into one variation. For example, if libfoo is included in both apex.a
  88. // and apex.b, and if the two APEXes have the same min_sdk_version (say 29), then libfoo doesn't
  89. // have to be built twice, but only once. In that case, the two apex variations apex.a and apex.b
  90. // are configured to have the same alias variation named apex29. Whether platform APIs is allowed
  91. // or not also matters; if two APEXes don't have the same allowance, they get different names and
  92. // thus wouldn't be merged.
  93. func (i ApexInfo) mergedName(ctx PathContext) string {
  94. name := "apex" + strconv.Itoa(i.MinSdkVersion.FinalOrFutureInt())
  95. return name
  96. }
  97. // IsForPlatform tells whether this module is for the platform or not. If false is returned, it
  98. // means that this apex variant of the module is built for an APEX.
  99. func (i ApexInfo) IsForPlatform() bool {
  100. return i.ApexVariationName == ""
  101. }
  102. // InApexVariant tells whether this apex variant of the module is part of the given apexVariant or
  103. // not.
  104. func (i ApexInfo) InApexVariant(apexVariant string) bool {
  105. for _, a := range i.InApexVariants {
  106. if a == apexVariant {
  107. return true
  108. }
  109. }
  110. return false
  111. }
  112. func (i ApexInfo) InApexModule(apexModuleName string) bool {
  113. for _, a := range i.InApexModules {
  114. if a == apexModuleName {
  115. return true
  116. }
  117. }
  118. return false
  119. }
  120. // ApexTestForInfo stores the contents of APEXes for which this module is a test - although this
  121. // module is not part of the APEX - and thus has access to APEX internals.
  122. type ApexTestForInfo struct {
  123. ApexContents []*ApexContents
  124. }
  125. var ApexTestForInfoProvider = blueprint.NewMutatorProvider(ApexTestForInfo{}, "apex_test_for")
  126. // DepIsInSameApex defines an interface that should be used to determine whether a given dependency
  127. // should be considered as part of the same APEX as the current module or not. Note: this was
  128. // extracted from ApexModule to make it easier to define custom subsets of the ApexModule interface
  129. // and improve code navigation within the IDE.
  130. type DepIsInSameApex interface {
  131. // DepIsInSameApex tests if the other module 'dep' is considered as part of the same APEX as
  132. // this module. For example, a static lib dependency usually returns true here, while a
  133. // shared lib dependency to a stub library returns false.
  134. //
  135. // This method must not be called directly without first ignoring dependencies whose tags
  136. // implement ExcludeFromApexContentsTag. Calls from within the func passed to WalkPayloadDeps()
  137. // are fine as WalkPayloadDeps() will ignore those dependencies automatically. Otherwise, use
  138. // IsDepInSameApex instead.
  139. DepIsInSameApex(ctx BaseModuleContext, dep Module) bool
  140. }
  141. func IsDepInSameApex(ctx BaseModuleContext, module, dep Module) bool {
  142. depTag := ctx.OtherModuleDependencyTag(dep)
  143. if _, ok := depTag.(ExcludeFromApexContentsTag); ok {
  144. // The tag defines a dependency that never requires the child module to be part of the same
  145. // apex as the parent.
  146. return false
  147. }
  148. return module.(DepIsInSameApex).DepIsInSameApex(ctx, dep)
  149. }
  150. // ApexModule is the interface that a module type is expected to implement if the module has to be
  151. // built differently depending on whether the module is destined for an APEX or not (i.e., installed
  152. // to one of the regular partitions).
  153. //
  154. // Native shared libraries are one such module type; when it is built for an APEX, it should depend
  155. // only on stable interfaces such as NDK, stable AIDL, or C APIs from other APEXes.
  156. //
  157. // A module implementing this interface will be mutated into multiple variations by apex.apexMutator
  158. // if it is directly or indirectly included in one or more APEXes. Specifically, if a module is
  159. // included in apex.foo and apex.bar then three apex variants are created: platform, apex.foo and
  160. // apex.bar. The platform variant is for the regular partitions (e.g., /system or /vendor, etc.)
  161. // while the other two are for the APEXs, respectively. The latter two variations can be merged (see
  162. // mergedName) when the two APEXes have the same min_sdk_version requirement.
  163. type ApexModule interface {
  164. Module
  165. DepIsInSameApex
  166. apexModuleBase() *ApexModuleBase
  167. // Marks that this module should be built for the specified APEX. Call this BEFORE
  168. // apex.apexMutator is run.
  169. BuildForApex(apex ApexInfo)
  170. // Returns true if this module is present in any APEX either directly or indirectly. Call
  171. // this after apex.apexMutator is run.
  172. InAnyApex() bool
  173. // Returns true if this module is directly in any APEX. Call this AFTER apex.apexMutator is
  174. // run.
  175. DirectlyInAnyApex() bool
  176. // NotInPlatform tells whether or not this module is included in an APEX and therefore
  177. // shouldn't be exposed to the platform (i.e. outside of the APEX) directly. A module is
  178. // considered to be included in an APEX either when there actually is an APEX that
  179. // explicitly has the module as its dependency or the module is not available to the
  180. // platform, which indicates that the module belongs to at least one or more other APEXes.
  181. NotInPlatform() bool
  182. // Tests if this module could have APEX variants. Even when a module type implements
  183. // ApexModule interface, APEX variants are created only for the module instances that return
  184. // true here. This is useful for not creating APEX variants for certain types of shared
  185. // libraries such as NDK stubs.
  186. CanHaveApexVariants() bool
  187. // Tests if this module can be installed to APEX as a file. For example, this would return
  188. // true for shared libs while return false for static libs because static libs are not
  189. // installable module (but it can still be mutated for APEX)
  190. IsInstallableToApex() bool
  191. // Tests if this module is available for the specified APEX or ":platform". This is from the
  192. // apex_available property of the module.
  193. AvailableFor(what string) bool
  194. // AlwaysRequiresPlatformApexVariant allows the implementing module to determine whether an
  195. // APEX mutator should always be created for it.
  196. //
  197. // Returns false by default.
  198. AlwaysRequiresPlatformApexVariant() bool
  199. // Returns true if this module is not available to platform (i.e. apex_available property
  200. // doesn't have "//apex_available:platform"), or shouldn't be available to platform, which
  201. // is the case when this module depends on other module that isn't available to platform.
  202. NotAvailableForPlatform() bool
  203. // Marks that this module is not available to platform. Set by the
  204. // check-platform-availability mutator in the apex package.
  205. SetNotAvailableForPlatform()
  206. // Returns the list of APEXes that this module is a test for. The module has access to the
  207. // private part of the listed APEXes even when it is not included in the APEXes. This by
  208. // default returns nil. A module type should override the default implementation. For
  209. // example, cc_test module type returns the value of test_for here.
  210. TestFor() []string
  211. // Returns nil (success) if this module should support the given sdk version. Returns an
  212. // error if not. No default implementation is provided for this method. A module type
  213. // implementing this interface should provide an implementation. A module supports an sdk
  214. // version when the module's min_sdk_version is equal to or less than the given sdk version.
  215. ShouldSupportSdkVersion(ctx BaseModuleContext, sdkVersion ApiLevel) error
  216. // Returns true if this module needs a unique variation per apex, effectively disabling the
  217. // deduping. This is turned on when, for example if use_apex_name_macro is set so that each
  218. // apex variant should be built with different macro definitions.
  219. UniqueApexVariations() bool
  220. }
  221. // Properties that are common to all module types implementing ApexModule interface.
  222. type ApexProperties struct {
  223. // Availability of this module in APEXes. Only the listed APEXes can contain this module. If
  224. // the module has stubs then other APEXes and the platform may access it through them
  225. // (subject to visibility).
  226. //
  227. // "//apex_available:anyapex" is a pseudo APEX name that matches to any APEX.
  228. // "//apex_available:platform" refers to non-APEX partitions like "system.img".
  229. // "com.android.gki.*" matches any APEX module name with the prefix "com.android.gki.".
  230. // Default is ["//apex_available:platform"].
  231. Apex_available []string
  232. // See ApexModule.InAnyApex()
  233. InAnyApex bool `blueprint:"mutated"`
  234. // See ApexModule.DirectlyInAnyApex()
  235. DirectlyInAnyApex bool `blueprint:"mutated"`
  236. // AnyVariantDirectlyInAnyApex is true in the primary variant of a module if _any_ variant
  237. // of the module is directly in any apex. This includes host, arch, asan, etc. variants. It
  238. // is unused in any variant that is not the primary variant. Ideally this wouldn't be used,
  239. // as it incorrectly mixes arch variants if only one arch is in an apex, but a few places
  240. // depend on it, for example when an ASAN variant is created before the apexMutator. Call
  241. // this after apex.apexMutator is run.
  242. AnyVariantDirectlyInAnyApex bool `blueprint:"mutated"`
  243. // See ApexModule.NotAvailableForPlatform()
  244. NotAvailableForPlatform bool `blueprint:"mutated"`
  245. // See ApexModule.UniqueApexVariants()
  246. UniqueApexVariationsForDeps bool `blueprint:"mutated"`
  247. }
  248. // Marker interface that identifies dependencies that are excluded from APEX contents.
  249. //
  250. // Unless the tag also implements the AlwaysRequireApexVariantTag this will prevent an apex variant
  251. // from being created for the module.
  252. //
  253. // At the moment the sdk.sdkRequirementsMutator relies on the fact that the existing tags which
  254. // implement this interface do not define dependencies onto members of an sdk_snapshot. If that
  255. // changes then sdk.sdkRequirementsMutator will need fixing.
  256. type ExcludeFromApexContentsTag interface {
  257. blueprint.DependencyTag
  258. // Method that differentiates this interface from others.
  259. ExcludeFromApexContents()
  260. }
  261. // Marker interface that identifies dependencies that always requires an APEX variant to be created.
  262. //
  263. // It is possible for a dependency to require an apex variant but exclude the module from the APEX
  264. // contents. See sdk.sdkMemberDependencyTag.
  265. type AlwaysRequireApexVariantTag interface {
  266. blueprint.DependencyTag
  267. // Return true if this tag requires that the target dependency has an apex variant.
  268. AlwaysRequireApexVariant() bool
  269. }
  270. // Marker interface that identifies dependencies that should inherit the DirectlyInAnyApex state
  271. // from the parent to the child. For example, stubs libraries are marked as DirectlyInAnyApex if
  272. // their implementation is in an apex.
  273. type CopyDirectlyInAnyApexTag interface {
  274. blueprint.DependencyTag
  275. // Method that differentiates this interface from others.
  276. CopyDirectlyInAnyApex()
  277. }
  278. // Interface that identifies dependencies to skip Apex dependency check
  279. type SkipApexAllowedDependenciesCheck interface {
  280. // Returns true to skip the Apex dependency check, which limits the allowed dependency in build.
  281. SkipApexAllowedDependenciesCheck() bool
  282. }
  283. // ApexModuleBase provides the default implementation for the ApexModule interface. APEX-aware
  284. // modules are expected to include this struct and call InitApexModule().
  285. type ApexModuleBase struct {
  286. ApexProperties ApexProperties
  287. canHaveApexVariants bool
  288. apexInfos []ApexInfo
  289. apexInfosLock sync.Mutex // protects apexInfos during parallel apexInfoMutator
  290. }
  291. // Initializes ApexModuleBase struct. Not calling this (even when inheriting from ApexModuleBase)
  292. // prevents the module from being mutated for apexBundle.
  293. func InitApexModule(m ApexModule) {
  294. base := m.apexModuleBase()
  295. base.canHaveApexVariants = true
  296. m.AddProperties(&base.ApexProperties)
  297. }
  298. // Implements ApexModule
  299. func (m *ApexModuleBase) apexModuleBase() *ApexModuleBase {
  300. return m
  301. }
  302. // Implements ApexModule
  303. func (m *ApexModuleBase) ApexAvailable() []string {
  304. return m.ApexProperties.Apex_available
  305. }
  306. // Implements ApexModule
  307. func (m *ApexModuleBase) BuildForApex(apex ApexInfo) {
  308. m.apexInfosLock.Lock()
  309. defer m.apexInfosLock.Unlock()
  310. for i, v := range m.apexInfos {
  311. if v.ApexVariationName == apex.ApexVariationName {
  312. if len(apex.InApexModules) != 1 {
  313. panic(fmt.Errorf("Newly created apexInfo must be for a single APEX"))
  314. }
  315. // Even when the ApexVariantNames are the same, the given ApexInfo might
  316. // actually be for different APEX. This can happen when an APEX is
  317. // overridden via override_apex. For example, there can be two apexes
  318. // `com.android.foo` (from the `apex` module type) and
  319. // `com.mycompany.android.foo` (from the `override_apex` module type), both
  320. // of which has the same ApexVariantName `com.android.foo`. Add the apex
  321. // name to the list so that it's not lost.
  322. if !InList(apex.InApexModules[0], v.InApexModules) {
  323. m.apexInfos[i].InApexModules = append(m.apexInfos[i].InApexModules, apex.InApexModules[0])
  324. }
  325. return
  326. }
  327. }
  328. m.apexInfos = append(m.apexInfos, apex)
  329. }
  330. // Implements ApexModule
  331. func (m *ApexModuleBase) InAnyApex() bool {
  332. return m.ApexProperties.InAnyApex
  333. }
  334. // Implements ApexModule
  335. func (m *ApexModuleBase) DirectlyInAnyApex() bool {
  336. return m.ApexProperties.DirectlyInAnyApex
  337. }
  338. // Implements ApexModule
  339. func (m *ApexModuleBase) NotInPlatform() bool {
  340. return m.ApexProperties.AnyVariantDirectlyInAnyApex || !m.AvailableFor(AvailableToPlatform)
  341. }
  342. // Implements ApexModule
  343. func (m *ApexModuleBase) CanHaveApexVariants() bool {
  344. return m.canHaveApexVariants
  345. }
  346. // Implements ApexModule
  347. func (m *ApexModuleBase) IsInstallableToApex() bool {
  348. // If needed, this will bel overridden by concrete types inheriting
  349. // ApexModuleBase
  350. return false
  351. }
  352. // Implements ApexModule
  353. func (m *ApexModuleBase) TestFor() []string {
  354. // If needed, this will be overridden by concrete types inheriting
  355. // ApexModuleBase
  356. return nil
  357. }
  358. // Implements ApexModule
  359. func (m *ApexModuleBase) UniqueApexVariations() bool {
  360. // If needed, this will bel overridden by concrete types inheriting
  361. // ApexModuleBase
  362. return false
  363. }
  364. // Implements ApexModule
  365. func (m *ApexModuleBase) DepIsInSameApex(ctx BaseModuleContext, dep Module) bool {
  366. // By default, if there is a dependency from A to B, we try to include both in the same
  367. // APEX, unless B is explicitly from outside of the APEX (i.e. a stubs lib). Thus, returning
  368. // true. This is overridden by some module types like apex.ApexBundle, cc.Module,
  369. // java.Module, etc.
  370. return true
  371. }
  372. const (
  373. AvailableToPlatform = "//apex_available:platform"
  374. AvailableToAnyApex = "//apex_available:anyapex"
  375. AvailableToGkiApex = "com.android.gki.*"
  376. )
  377. // CheckAvailableForApex provides the default algorithm for checking the apex availability. When the
  378. // availability is empty, it defaults to ["//apex_available:platform"] which means "available to the
  379. // platform but not available to any APEX". When the list is not empty, `what` is matched against
  380. // the list. If there is any matching element in the list, thus function returns true. The special
  381. // availability "//apex_available:anyapex" matches with anything except for
  382. // "//apex_available:platform".
  383. func CheckAvailableForApex(what string, apex_available []string) bool {
  384. if len(apex_available) == 0 {
  385. return what == AvailableToPlatform
  386. }
  387. return InList(what, apex_available) ||
  388. (what != AvailableToPlatform && InList(AvailableToAnyApex, apex_available)) ||
  389. (what == "com.android.btservices" && InList("com.android.bluetooth", apex_available)) ||
  390. (strings.HasPrefix(what, "com.android.gki.") && InList(AvailableToGkiApex, apex_available))
  391. }
  392. // Implements ApexModule
  393. func (m *ApexModuleBase) AvailableFor(what string) bool {
  394. return CheckAvailableForApex(what, m.ApexProperties.Apex_available)
  395. }
  396. // Implements ApexModule
  397. func (m *ApexModuleBase) AlwaysRequiresPlatformApexVariant() bool {
  398. return false
  399. }
  400. // Implements ApexModule
  401. func (m *ApexModuleBase) NotAvailableForPlatform() bool {
  402. return m.ApexProperties.NotAvailableForPlatform
  403. }
  404. // Implements ApexModule
  405. func (m *ApexModuleBase) SetNotAvailableForPlatform() {
  406. m.ApexProperties.NotAvailableForPlatform = true
  407. }
  408. // This function makes sure that the apex_available property is valid
  409. func (m *ApexModuleBase) checkApexAvailableProperty(mctx BaseModuleContext) {
  410. for _, n := range m.ApexProperties.Apex_available {
  411. if n == AvailableToPlatform || n == AvailableToAnyApex || n == AvailableToGkiApex {
  412. continue
  413. }
  414. if !mctx.OtherModuleExists(n) && !mctx.Config().AllowMissingDependencies() {
  415. mctx.PropertyErrorf("apex_available", "%q is not a valid module name", n)
  416. }
  417. }
  418. }
  419. // AvailableToSameApexes returns true if the two modules are apex_available to
  420. // exactly the same set of APEXes (and platform), i.e. if their apex_available
  421. // properties have the same elements.
  422. func AvailableToSameApexes(mod1, mod2 ApexModule) bool {
  423. mod1ApexAvail := SortedUniqueStrings(mod1.apexModuleBase().ApexProperties.Apex_available)
  424. mod2ApexAvail := SortedUniqueStrings(mod2.apexModuleBase().ApexProperties.Apex_available)
  425. if len(mod1ApexAvail) != len(mod2ApexAvail) {
  426. return false
  427. }
  428. for i, v := range mod1ApexAvail {
  429. if v != mod2ApexAvail[i] {
  430. return false
  431. }
  432. }
  433. return true
  434. }
  435. type byApexName []ApexInfo
  436. func (a byApexName) Len() int { return len(a) }
  437. func (a byApexName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  438. func (a byApexName) Less(i, j int) bool { return a[i].ApexVariationName < a[j].ApexVariationName }
  439. // mergeApexVariations deduplicates apex variations that would build identically into a common
  440. // variation. It returns the reduced list of variations and a list of aliases from the original
  441. // variation names to the new variation names.
  442. func mergeApexVariations(ctx PathContext, apexInfos []ApexInfo) (merged []ApexInfo, aliases [][2]string) {
  443. sort.Sort(byApexName(apexInfos))
  444. seen := make(map[string]int)
  445. for _, apexInfo := range apexInfos {
  446. // If this is for a prebuilt apex then use the actual name of the apex variation to prevent this
  447. // from being merged with other ApexInfo. See Prebuilt.ApexInfoMutator for more information.
  448. if apexInfo.ForPrebuiltApex {
  449. merged = append(merged, apexInfo)
  450. continue
  451. }
  452. // Merge the ApexInfo together. If a compatible ApexInfo exists then merge the information from
  453. // this one into it, otherwise create a new merged ApexInfo from this one and save it away so
  454. // other ApexInfo instances can be merged into it.
  455. variantName := apexInfo.ApexVariationName
  456. mergedName := apexInfo.mergedName(ctx)
  457. if index, exists := seen[mergedName]; exists {
  458. // Variants having the same mergedName are deduped
  459. merged[index].InApexVariants = append(merged[index].InApexVariants, variantName)
  460. merged[index].InApexModules = append(merged[index].InApexModules, apexInfo.InApexModules...)
  461. merged[index].ApexContents = append(merged[index].ApexContents, apexInfo.ApexContents...)
  462. merged[index].Updatable = merged[index].Updatable || apexInfo.Updatable
  463. // Platform APIs is allowed for this module only when all APEXes containing
  464. // the module are with `use_platform_apis: true`.
  465. merged[index].UsePlatformApis = merged[index].UsePlatformApis && apexInfo.UsePlatformApis
  466. } else {
  467. seen[mergedName] = len(merged)
  468. apexInfo.ApexVariationName = mergedName
  469. apexInfo.InApexVariants = CopyOf(apexInfo.InApexVariants)
  470. apexInfo.InApexModules = CopyOf(apexInfo.InApexModules)
  471. apexInfo.ApexContents = append([]*ApexContents(nil), apexInfo.ApexContents...)
  472. merged = append(merged, apexInfo)
  473. }
  474. aliases = append(aliases, [2]string{variantName, mergedName})
  475. }
  476. return merged, aliases
  477. }
  478. // CreateApexVariations mutates a given module into multiple apex variants each of which is for an
  479. // apexBundle (and/or the platform) where the module is part of.
  480. func CreateApexVariations(mctx BottomUpMutatorContext, module ApexModule) []Module {
  481. base := module.apexModuleBase()
  482. // Shortcut
  483. if len(base.apexInfos) == 0 {
  484. return nil
  485. }
  486. // Do some validity checks.
  487. // TODO(jiyong): is this the right place?
  488. base.checkApexAvailableProperty(mctx)
  489. var apexInfos []ApexInfo
  490. var aliases [][2]string
  491. if !mctx.Module().(ApexModule).UniqueApexVariations() && !base.ApexProperties.UniqueApexVariationsForDeps {
  492. apexInfos, aliases = mergeApexVariations(mctx, base.apexInfos)
  493. } else {
  494. apexInfos = base.apexInfos
  495. }
  496. // base.apexInfos is only needed to propagate the list of apexes from apexInfoMutator to
  497. // apexMutator. It is no longer accurate after mergeApexVariations, and won't be copied to
  498. // all but the first created variant. Clear it so it doesn't accidentally get used later.
  499. base.apexInfos = nil
  500. sort.Sort(byApexName(apexInfos))
  501. var inApex ApexMembership
  502. for _, a := range apexInfos {
  503. for _, apexContents := range a.ApexContents {
  504. inApex = inApex.merge(apexContents.contents[mctx.ModuleName()])
  505. }
  506. }
  507. base.ApexProperties.InAnyApex = true
  508. base.ApexProperties.DirectlyInAnyApex = inApex == directlyInApex
  509. defaultVariation := ""
  510. mctx.SetDefaultDependencyVariation(&defaultVariation)
  511. variations := []string{defaultVariation}
  512. for _, a := range apexInfos {
  513. variations = append(variations, a.ApexVariationName)
  514. }
  515. modules := mctx.CreateVariations(variations...)
  516. for i, mod := range modules {
  517. platformVariation := i == 0
  518. if platformVariation && !mctx.Host() && !mod.(ApexModule).AvailableFor(AvailableToPlatform) {
  519. // Do not install the module for platform, but still allow it to output
  520. // uninstallable AndroidMk entries in certain cases when they have side
  521. // effects. TODO(jiyong): move this routine to somewhere else
  522. mod.MakeUninstallable()
  523. }
  524. if !platformVariation {
  525. mctx.SetVariationProvider(mod, ApexInfoProvider, apexInfos[i-1])
  526. }
  527. }
  528. for _, alias := range aliases {
  529. mctx.CreateAliasVariation(alias[0], alias[1])
  530. }
  531. return modules
  532. }
  533. // UpdateUniqueApexVariationsForDeps sets UniqueApexVariationsForDeps if any dependencies that are
  534. // in the same APEX have unique APEX variations so that the module can link against the right
  535. // variant.
  536. func UpdateUniqueApexVariationsForDeps(mctx BottomUpMutatorContext, am ApexModule) {
  537. // anyInSameApex returns true if the two ApexInfo lists contain any values in an
  538. // InApexVariants list in common. It is used instead of DepIsInSameApex because it needs to
  539. // determine if the dep is in the same APEX due to being directly included, not only if it
  540. // is included _because_ it is a dependency.
  541. anyInSameApex := func(a, b []ApexInfo) bool {
  542. collectApexes := func(infos []ApexInfo) []string {
  543. var ret []string
  544. for _, info := range infos {
  545. ret = append(ret, info.InApexVariants...)
  546. }
  547. return ret
  548. }
  549. aApexes := collectApexes(a)
  550. bApexes := collectApexes(b)
  551. sort.Strings(bApexes)
  552. for _, aApex := range aApexes {
  553. index := sort.SearchStrings(bApexes, aApex)
  554. if index < len(bApexes) && bApexes[index] == aApex {
  555. return true
  556. }
  557. }
  558. return false
  559. }
  560. // If any of the dependencies requires unique apex variations, so does this module.
  561. mctx.VisitDirectDeps(func(dep Module) {
  562. if depApexModule, ok := dep.(ApexModule); ok {
  563. if anyInSameApex(depApexModule.apexModuleBase().apexInfos, am.apexModuleBase().apexInfos) &&
  564. (depApexModule.UniqueApexVariations() ||
  565. depApexModule.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps) {
  566. am.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps = true
  567. }
  568. }
  569. })
  570. }
  571. // UpdateDirectlyInAnyApex uses the final module to store if any variant of this module is directly
  572. // in any APEX, and then copies the final value to all the modules. It also copies the
  573. // DirectlyInAnyApex value to any direct dependencies with a CopyDirectlyInAnyApexTag dependency
  574. // tag.
  575. func UpdateDirectlyInAnyApex(mctx BottomUpMutatorContext, am ApexModule) {
  576. base := am.apexModuleBase()
  577. // Copy DirectlyInAnyApex and InAnyApex from any direct dependencies with a
  578. // CopyDirectlyInAnyApexTag dependency tag.
  579. mctx.VisitDirectDeps(func(dep Module) {
  580. if _, ok := mctx.OtherModuleDependencyTag(dep).(CopyDirectlyInAnyApexTag); ok {
  581. depBase := dep.(ApexModule).apexModuleBase()
  582. depBase.ApexProperties.DirectlyInAnyApex = base.ApexProperties.DirectlyInAnyApex
  583. depBase.ApexProperties.InAnyApex = base.ApexProperties.InAnyApex
  584. }
  585. })
  586. if base.ApexProperties.DirectlyInAnyApex {
  587. // Variants of a module are always visited sequentially in order, so it is safe to
  588. // write to another variant of this module. For a BottomUpMutator the
  589. // PrimaryModule() is visited first and FinalModule() is visited last.
  590. mctx.FinalModule().(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex = true
  591. }
  592. // If this is the FinalModule (last visited module) copy
  593. // AnyVariantDirectlyInAnyApex to all the other variants
  594. if am == mctx.FinalModule().(ApexModule) {
  595. mctx.VisitAllModuleVariants(func(variant Module) {
  596. variant.(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex =
  597. base.ApexProperties.AnyVariantDirectlyInAnyApex
  598. })
  599. }
  600. }
  601. // ApexMembership tells how a module became part of an APEX.
  602. type ApexMembership int
  603. const (
  604. notInApex ApexMembership = 0
  605. indirectlyInApex = iota
  606. directlyInApex
  607. )
  608. // ApexContents gives an information about member modules of an apexBundle. Each apexBundle has an
  609. // apexContents, and modules in that apex have a provider containing the apexContents of each
  610. // apexBundle they are part of.
  611. type ApexContents struct {
  612. // map from a module name to its membership in this apexBundle
  613. contents map[string]ApexMembership
  614. }
  615. // NewApexContents creates and initializes an ApexContents that is suitable
  616. // for use with an apex module.
  617. // - contents is a map from a module name to information about its membership within
  618. // the apex.
  619. func NewApexContents(contents map[string]ApexMembership) *ApexContents {
  620. return &ApexContents{
  621. contents: contents,
  622. }
  623. }
  624. // Updates an existing membership by adding a new direct (or indirect) membership
  625. func (i ApexMembership) Add(direct bool) ApexMembership {
  626. if direct || i == directlyInApex {
  627. return directlyInApex
  628. }
  629. return indirectlyInApex
  630. }
  631. // Merges two membership into one. Merging is needed because a module can be a part of an apexBundle
  632. // in many different paths. For example, it could be dependend on by the apexBundle directly, but at
  633. // the same time, there might be an indirect dependency to the module. In that case, the more
  634. // specific dependency (the direct one) is chosen.
  635. func (i ApexMembership) merge(other ApexMembership) ApexMembership {
  636. if other == directlyInApex || i == directlyInApex {
  637. return directlyInApex
  638. }
  639. if other == indirectlyInApex || i == indirectlyInApex {
  640. return indirectlyInApex
  641. }
  642. return notInApex
  643. }
  644. // Tests whether a module named moduleName is directly included in the apexBundle where this
  645. // ApexContents is tagged.
  646. func (ac *ApexContents) DirectlyInApex(moduleName string) bool {
  647. return ac.contents[moduleName] == directlyInApex
  648. }
  649. // Tests whether a module named moduleName is included in the apexBundle where this ApexContent is
  650. // tagged.
  651. func (ac *ApexContents) InApex(moduleName string) bool {
  652. return ac.contents[moduleName] != notInApex
  653. }
  654. // Tests whether a module named moduleName is directly depended on by all APEXes in an ApexInfo.
  655. func DirectlyInAllApexes(apexInfo ApexInfo, moduleName string) bool {
  656. for _, contents := range apexInfo.ApexContents {
  657. if !contents.DirectlyInApex(moduleName) {
  658. return false
  659. }
  660. }
  661. return true
  662. }
  663. ////////////////////////////////////////////////////////////////////////////////////////////////////
  664. //Below are routines for extra safety checks.
  665. //
  666. // BuildDepsInfoLists is to flatten the dependency graph for an apexBundle into a text file
  667. // (actually two in slightly different formats). The files are mostly for debugging, for example to
  668. // see why a certain module is included in an APEX via which dependency path.
  669. //
  670. // CheckMinSdkVersion is to make sure that all modules in an apexBundle satisfy the min_sdk_version
  671. // requirement of the apexBundle.
  672. // A dependency info for a single ApexModule, either direct or transitive.
  673. type ApexModuleDepInfo struct {
  674. // Name of the dependency
  675. To string
  676. // List of dependencies To belongs to. Includes APEX itself, if a direct dependency.
  677. From []string
  678. // Whether the dependency belongs to the final compiled APEX.
  679. IsExternal bool
  680. // min_sdk_version of the ApexModule
  681. MinSdkVersion string
  682. }
  683. // A map of a dependency name to its ApexModuleDepInfo
  684. type DepNameToDepInfoMap map[string]ApexModuleDepInfo
  685. type ApexBundleDepsInfo struct {
  686. flatListPath OutputPath
  687. fullListPath OutputPath
  688. }
  689. type ApexBundleDepsInfoIntf interface {
  690. Updatable() bool
  691. FlatListPath() Path
  692. FullListPath() Path
  693. }
  694. func (d *ApexBundleDepsInfo) FlatListPath() Path {
  695. return d.flatListPath
  696. }
  697. func (d *ApexBundleDepsInfo) FullListPath() Path {
  698. return d.fullListPath
  699. }
  700. // Generate two module out files:
  701. // 1. FullList with transitive deps and their parents in the dep graph
  702. // 2. FlatList with a flat list of transitive deps
  703. // In both cases transitive deps of external deps are not included. Neither are deps that are only
  704. // available to APEXes; they are developed with updatability in mind and don't need manual approval.
  705. func (d *ApexBundleDepsInfo) BuildDepsInfoLists(ctx ModuleContext, minSdkVersion string, depInfos DepNameToDepInfoMap) {
  706. var fullContent strings.Builder
  707. var flatContent strings.Builder
  708. fmt.Fprintf(&fullContent, "%s(minSdkVersion:%s):\n", ctx.ModuleName(), minSdkVersion)
  709. for _, key := range FirstUniqueStrings(SortedStringKeys(depInfos)) {
  710. info := depInfos[key]
  711. toName := fmt.Sprintf("%s(minSdkVersion:%s)", info.To, info.MinSdkVersion)
  712. if info.IsExternal {
  713. toName = toName + " (external)"
  714. }
  715. fmt.Fprintf(&fullContent, " %s <- %s\n", toName, strings.Join(SortedUniqueStrings(info.From), ", "))
  716. fmt.Fprintf(&flatContent, "%s\n", toName)
  717. }
  718. d.fullListPath = PathForModuleOut(ctx, "depsinfo", "fulllist.txt").OutputPath
  719. WriteFileRule(ctx, d.fullListPath, fullContent.String())
  720. d.flatListPath = PathForModuleOut(ctx, "depsinfo", "flatlist.txt").OutputPath
  721. WriteFileRule(ctx, d.flatListPath, flatContent.String())
  722. ctx.Phony(fmt.Sprintf("%s-depsinfo", ctx.ModuleName()), d.fullListPath, d.flatListPath)
  723. }
  724. // Function called while walking an APEX's payload dependencies.
  725. //
  726. // Return true if the `to` module should be visited, false otherwise.
  727. type PayloadDepsCallback func(ctx ModuleContext, from blueprint.Module, to ApexModule, externalDep bool) bool
  728. type WalkPayloadDepsFunc func(ctx ModuleContext, do PayloadDepsCallback)
  729. // ModuleWithMinSdkVersionCheck represents a module that implements min_sdk_version checks
  730. type ModuleWithMinSdkVersionCheck interface {
  731. Module
  732. MinSdkVersion(ctx EarlyModuleContext) SdkSpec
  733. CheckMinSdkVersion(ctx ModuleContext)
  734. }
  735. // CheckMinSdkVersion checks if every dependency of an updatable module sets min_sdk_version
  736. // accordingly
  737. func CheckMinSdkVersion(ctx ModuleContext, minSdkVersion ApiLevel, walk WalkPayloadDepsFunc) {
  738. // do not enforce min_sdk_version for host
  739. if ctx.Host() {
  740. return
  741. }
  742. // do not enforce for coverage build
  743. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") || ctx.DeviceConfig().NativeCoverageEnabled() || ctx.DeviceConfig().ClangCoverageEnabled() {
  744. return
  745. }
  746. // do not enforce deps.min_sdk_version if APEX/APK doesn't set min_sdk_version
  747. if minSdkVersion.IsNone() {
  748. return
  749. }
  750. walk(ctx, func(ctx ModuleContext, from blueprint.Module, to ApexModule, externalDep bool) bool {
  751. if externalDep {
  752. // external deps are outside the payload boundary, which is "stable"
  753. // interface. We don't have to check min_sdk_version for external
  754. // dependencies.
  755. return false
  756. }
  757. if am, ok := from.(DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
  758. return false
  759. }
  760. if m, ok := to.(ModuleWithMinSdkVersionCheck); ok {
  761. // This dependency performs its own min_sdk_version check, just make sure it sets min_sdk_version
  762. // to trigger the check.
  763. if !m.MinSdkVersion(ctx).Specified() {
  764. ctx.OtherModuleErrorf(m, "must set min_sdk_version")
  765. }
  766. return false
  767. }
  768. if err := to.ShouldSupportSdkVersion(ctx, minSdkVersion); err != nil {
  769. toName := ctx.OtherModuleName(to)
  770. ctx.OtherModuleErrorf(to, "should support min_sdk_version(%v) for %q: %v."+
  771. "\n\nDependency path: %s\n\n"+
  772. "Consider adding 'min_sdk_version: %q' to %q",
  773. minSdkVersion, ctx.ModuleName(), err.Error(),
  774. ctx.GetPathString(false),
  775. minSdkVersion, toName)
  776. return false
  777. }
  778. return true
  779. })
  780. }