apex.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. (strings.HasPrefix(what, "com.android.gki.") && InList(AvailableToGkiApex, apex_available))
  390. }
  391. // Implements ApexModule
  392. func (m *ApexModuleBase) AvailableFor(what string) bool {
  393. return CheckAvailableForApex(what, m.ApexProperties.Apex_available)
  394. }
  395. // Implements ApexModule
  396. func (m *ApexModuleBase) AlwaysRequiresPlatformApexVariant() bool {
  397. return false
  398. }
  399. // Implements ApexModule
  400. func (m *ApexModuleBase) NotAvailableForPlatform() bool {
  401. return m.ApexProperties.NotAvailableForPlatform
  402. }
  403. // Implements ApexModule
  404. func (m *ApexModuleBase) SetNotAvailableForPlatform() {
  405. m.ApexProperties.NotAvailableForPlatform = true
  406. }
  407. // This function makes sure that the apex_available property is valid
  408. func (m *ApexModuleBase) checkApexAvailableProperty(mctx BaseModuleContext) {
  409. for _, n := range m.ApexProperties.Apex_available {
  410. if n == AvailableToPlatform || n == AvailableToAnyApex || n == AvailableToGkiApex {
  411. continue
  412. }
  413. if !mctx.OtherModuleExists(n) && !mctx.Config().AllowMissingDependencies() {
  414. mctx.PropertyErrorf("apex_available", "%q is not a valid module name", n)
  415. }
  416. }
  417. }
  418. // AvailableToSameApexes returns true if the two modules are apex_available to
  419. // exactly the same set of APEXes (and platform), i.e. if their apex_available
  420. // properties have the same elements.
  421. func AvailableToSameApexes(mod1, mod2 ApexModule) bool {
  422. mod1ApexAvail := SortedUniqueStrings(mod1.apexModuleBase().ApexProperties.Apex_available)
  423. mod2ApexAvail := SortedUniqueStrings(mod2.apexModuleBase().ApexProperties.Apex_available)
  424. if len(mod1ApexAvail) != len(mod2ApexAvail) {
  425. return false
  426. }
  427. for i, v := range mod1ApexAvail {
  428. if v != mod2ApexAvail[i] {
  429. return false
  430. }
  431. }
  432. return true
  433. }
  434. type byApexName []ApexInfo
  435. func (a byApexName) Len() int { return len(a) }
  436. func (a byApexName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  437. func (a byApexName) Less(i, j int) bool { return a[i].ApexVariationName < a[j].ApexVariationName }
  438. // mergeApexVariations deduplicates apex variations that would build identically into a common
  439. // variation. It returns the reduced list of variations and a list of aliases from the original
  440. // variation names to the new variation names.
  441. func mergeApexVariations(ctx PathContext, apexInfos []ApexInfo) (merged []ApexInfo, aliases [][2]string) {
  442. sort.Sort(byApexName(apexInfos))
  443. seen := make(map[string]int)
  444. for _, apexInfo := range apexInfos {
  445. // If this is for a prebuilt apex then use the actual name of the apex variation to prevent this
  446. // from being merged with other ApexInfo. See Prebuilt.ApexInfoMutator for more information.
  447. if apexInfo.ForPrebuiltApex {
  448. merged = append(merged, apexInfo)
  449. continue
  450. }
  451. // Merge the ApexInfo together. If a compatible ApexInfo exists then merge the information from
  452. // this one into it, otherwise create a new merged ApexInfo from this one and save it away so
  453. // other ApexInfo instances can be merged into it.
  454. variantName := apexInfo.ApexVariationName
  455. mergedName := apexInfo.mergedName(ctx)
  456. if index, exists := seen[mergedName]; exists {
  457. // Variants having the same mergedName are deduped
  458. merged[index].InApexVariants = append(merged[index].InApexVariants, variantName)
  459. merged[index].InApexModules = append(merged[index].InApexModules, apexInfo.InApexModules...)
  460. merged[index].ApexContents = append(merged[index].ApexContents, apexInfo.ApexContents...)
  461. merged[index].Updatable = merged[index].Updatable || apexInfo.Updatable
  462. // Platform APIs is allowed for this module only when all APEXes containing
  463. // the module are with `use_platform_apis: true`.
  464. merged[index].UsePlatformApis = merged[index].UsePlatformApis && apexInfo.UsePlatformApis
  465. } else {
  466. seen[mergedName] = len(merged)
  467. apexInfo.ApexVariationName = mergedName
  468. apexInfo.InApexVariants = CopyOf(apexInfo.InApexVariants)
  469. apexInfo.InApexModules = CopyOf(apexInfo.InApexModules)
  470. apexInfo.ApexContents = append([]*ApexContents(nil), apexInfo.ApexContents...)
  471. merged = append(merged, apexInfo)
  472. }
  473. aliases = append(aliases, [2]string{variantName, mergedName})
  474. }
  475. return merged, aliases
  476. }
  477. // CreateApexVariations mutates a given module into multiple apex variants each of which is for an
  478. // apexBundle (and/or the platform) where the module is part of.
  479. func CreateApexVariations(mctx BottomUpMutatorContext, module ApexModule) []Module {
  480. base := module.apexModuleBase()
  481. // Shortcut
  482. if len(base.apexInfos) == 0 {
  483. return nil
  484. }
  485. // Do some validity checks.
  486. // TODO(jiyong): is this the right place?
  487. base.checkApexAvailableProperty(mctx)
  488. var apexInfos []ApexInfo
  489. var aliases [][2]string
  490. if !mctx.Module().(ApexModule).UniqueApexVariations() && !base.ApexProperties.UniqueApexVariationsForDeps {
  491. apexInfos, aliases = mergeApexVariations(mctx, base.apexInfos)
  492. } else {
  493. apexInfos = base.apexInfos
  494. }
  495. // base.apexInfos is only needed to propagate the list of apexes from apexInfoMutator to
  496. // apexMutator. It is no longer accurate after mergeApexVariations, and won't be copied to
  497. // all but the first created variant. Clear it so it doesn't accidentally get used later.
  498. base.apexInfos = nil
  499. sort.Sort(byApexName(apexInfos))
  500. var inApex ApexMembership
  501. for _, a := range apexInfos {
  502. for _, apexContents := range a.ApexContents {
  503. inApex = inApex.merge(apexContents.contents[mctx.ModuleName()])
  504. }
  505. }
  506. base.ApexProperties.InAnyApex = true
  507. base.ApexProperties.DirectlyInAnyApex = inApex == directlyInApex
  508. defaultVariation := ""
  509. mctx.SetDefaultDependencyVariation(&defaultVariation)
  510. variations := []string{defaultVariation}
  511. for _, a := range apexInfos {
  512. variations = append(variations, a.ApexVariationName)
  513. }
  514. modules := mctx.CreateVariations(variations...)
  515. for i, mod := range modules {
  516. platformVariation := i == 0
  517. if platformVariation && !mctx.Host() && !mod.(ApexModule).AvailableFor(AvailableToPlatform) {
  518. // Do not install the module for platform, but still allow it to output
  519. // uninstallable AndroidMk entries in certain cases when they have side
  520. // effects. TODO(jiyong): move this routine to somewhere else
  521. mod.MakeUninstallable()
  522. }
  523. if !platformVariation {
  524. mctx.SetVariationProvider(mod, ApexInfoProvider, apexInfos[i-1])
  525. }
  526. }
  527. for _, alias := range aliases {
  528. mctx.CreateAliasVariation(alias[0], alias[1])
  529. }
  530. return modules
  531. }
  532. // UpdateUniqueApexVariationsForDeps sets UniqueApexVariationsForDeps if any dependencies that are
  533. // in the same APEX have unique APEX variations so that the module can link against the right
  534. // variant.
  535. func UpdateUniqueApexVariationsForDeps(mctx BottomUpMutatorContext, am ApexModule) {
  536. // anyInSameApex returns true if the two ApexInfo lists contain any values in an
  537. // InApexVariants list in common. It is used instead of DepIsInSameApex because it needs to
  538. // determine if the dep is in the same APEX due to being directly included, not only if it
  539. // is included _because_ it is a dependency.
  540. anyInSameApex := func(a, b []ApexInfo) bool {
  541. collectApexes := func(infos []ApexInfo) []string {
  542. var ret []string
  543. for _, info := range infos {
  544. ret = append(ret, info.InApexVariants...)
  545. }
  546. return ret
  547. }
  548. aApexes := collectApexes(a)
  549. bApexes := collectApexes(b)
  550. sort.Strings(bApexes)
  551. for _, aApex := range aApexes {
  552. index := sort.SearchStrings(bApexes, aApex)
  553. if index < len(bApexes) && bApexes[index] == aApex {
  554. return true
  555. }
  556. }
  557. return false
  558. }
  559. // If any of the dependencies requires unique apex variations, so does this module.
  560. mctx.VisitDirectDeps(func(dep Module) {
  561. if depApexModule, ok := dep.(ApexModule); ok {
  562. if anyInSameApex(depApexModule.apexModuleBase().apexInfos, am.apexModuleBase().apexInfos) &&
  563. (depApexModule.UniqueApexVariations() ||
  564. depApexModule.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps) {
  565. am.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps = true
  566. }
  567. }
  568. })
  569. }
  570. // UpdateDirectlyInAnyApex uses the final module to store if any variant of this module is directly
  571. // in any APEX, and then copies the final value to all the modules. It also copies the
  572. // DirectlyInAnyApex value to any direct dependencies with a CopyDirectlyInAnyApexTag dependency
  573. // tag.
  574. func UpdateDirectlyInAnyApex(mctx BottomUpMutatorContext, am ApexModule) {
  575. base := am.apexModuleBase()
  576. // Copy DirectlyInAnyApex and InAnyApex from any direct dependencies with a
  577. // CopyDirectlyInAnyApexTag dependency tag.
  578. mctx.VisitDirectDeps(func(dep Module) {
  579. if _, ok := mctx.OtherModuleDependencyTag(dep).(CopyDirectlyInAnyApexTag); ok {
  580. depBase := dep.(ApexModule).apexModuleBase()
  581. depBase.ApexProperties.DirectlyInAnyApex = base.ApexProperties.DirectlyInAnyApex
  582. depBase.ApexProperties.InAnyApex = base.ApexProperties.InAnyApex
  583. }
  584. })
  585. if base.ApexProperties.DirectlyInAnyApex {
  586. // Variants of a module are always visited sequentially in order, so it is safe to
  587. // write to another variant of this module. For a BottomUpMutator the
  588. // PrimaryModule() is visited first and FinalModule() is visited last.
  589. mctx.FinalModule().(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex = true
  590. }
  591. // If this is the FinalModule (last visited module) copy
  592. // AnyVariantDirectlyInAnyApex to all the other variants
  593. if am == mctx.FinalModule().(ApexModule) {
  594. mctx.VisitAllModuleVariants(func(variant Module) {
  595. variant.(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex =
  596. base.ApexProperties.AnyVariantDirectlyInAnyApex
  597. })
  598. }
  599. }
  600. // ApexMembership tells how a module became part of an APEX.
  601. type ApexMembership int
  602. const (
  603. notInApex ApexMembership = 0
  604. indirectlyInApex = iota
  605. directlyInApex
  606. )
  607. // ApexContents gives an information about member modules of an apexBundle. Each apexBundle has an
  608. // apexContents, and modules in that apex have a provider containing the apexContents of each
  609. // apexBundle they are part of.
  610. type ApexContents struct {
  611. // map from a module name to its membership in this apexBundle
  612. contents map[string]ApexMembership
  613. }
  614. // NewApexContents creates and initializes an ApexContents that is suitable
  615. // for use with an apex module.
  616. // - contents is a map from a module name to information about its membership within
  617. // the apex.
  618. func NewApexContents(contents map[string]ApexMembership) *ApexContents {
  619. return &ApexContents{
  620. contents: contents,
  621. }
  622. }
  623. // Updates an existing membership by adding a new direct (or indirect) membership
  624. func (i ApexMembership) Add(direct bool) ApexMembership {
  625. if direct || i == directlyInApex {
  626. return directlyInApex
  627. }
  628. return indirectlyInApex
  629. }
  630. // Merges two membership into one. Merging is needed because a module can be a part of an apexBundle
  631. // in many different paths. For example, it could be dependend on by the apexBundle directly, but at
  632. // the same time, there might be an indirect dependency to the module. In that case, the more
  633. // specific dependency (the direct one) is chosen.
  634. func (i ApexMembership) merge(other ApexMembership) ApexMembership {
  635. if other == directlyInApex || i == directlyInApex {
  636. return directlyInApex
  637. }
  638. if other == indirectlyInApex || i == indirectlyInApex {
  639. return indirectlyInApex
  640. }
  641. return notInApex
  642. }
  643. // Tests whether a module named moduleName is directly included in the apexBundle where this
  644. // ApexContents is tagged.
  645. func (ac *ApexContents) DirectlyInApex(moduleName string) bool {
  646. return ac.contents[moduleName] == directlyInApex
  647. }
  648. // Tests whether a module named moduleName is included in the apexBundle where this ApexContent is
  649. // tagged.
  650. func (ac *ApexContents) InApex(moduleName string) bool {
  651. return ac.contents[moduleName] != notInApex
  652. }
  653. // Tests whether a module named moduleName is directly depended on by all APEXes in an ApexInfo.
  654. func DirectlyInAllApexes(apexInfo ApexInfo, moduleName string) bool {
  655. for _, contents := range apexInfo.ApexContents {
  656. if !contents.DirectlyInApex(moduleName) {
  657. return false
  658. }
  659. }
  660. return true
  661. }
  662. ////////////////////////////////////////////////////////////////////////////////////////////////////
  663. //Below are routines for extra safety checks.
  664. //
  665. // BuildDepsInfoLists is to flatten the dependency graph for an apexBundle into a text file
  666. // (actually two in slightly different formats). The files are mostly for debugging, for example to
  667. // see why a certain module is included in an APEX via which dependency path.
  668. //
  669. // CheckMinSdkVersion is to make sure that all modules in an apexBundle satisfy the min_sdk_version
  670. // requirement of the apexBundle.
  671. // A dependency info for a single ApexModule, either direct or transitive.
  672. type ApexModuleDepInfo struct {
  673. // Name of the dependency
  674. To string
  675. // List of dependencies To belongs to. Includes APEX itself, if a direct dependency.
  676. From []string
  677. // Whether the dependency belongs to the final compiled APEX.
  678. IsExternal bool
  679. // min_sdk_version of the ApexModule
  680. MinSdkVersion string
  681. }
  682. // A map of a dependency name to its ApexModuleDepInfo
  683. type DepNameToDepInfoMap map[string]ApexModuleDepInfo
  684. type ApexBundleDepsInfo struct {
  685. flatListPath OutputPath
  686. fullListPath OutputPath
  687. }
  688. type ApexBundleDepsInfoIntf interface {
  689. Updatable() bool
  690. FlatListPath() Path
  691. FullListPath() Path
  692. }
  693. func (d *ApexBundleDepsInfo) FlatListPath() Path {
  694. return d.flatListPath
  695. }
  696. func (d *ApexBundleDepsInfo) FullListPath() Path {
  697. return d.fullListPath
  698. }
  699. // Generate two module out files:
  700. // 1. FullList with transitive deps and their parents in the dep graph
  701. // 2. FlatList with a flat list of transitive deps
  702. // In both cases transitive deps of external deps are not included. Neither are deps that are only
  703. // available to APEXes; they are developed with updatability in mind and don't need manual approval.
  704. func (d *ApexBundleDepsInfo) BuildDepsInfoLists(ctx ModuleContext, minSdkVersion string, depInfos DepNameToDepInfoMap) {
  705. var fullContent strings.Builder
  706. var flatContent strings.Builder
  707. fmt.Fprintf(&fullContent, "%s(minSdkVersion:%s):\n", ctx.ModuleName(), minSdkVersion)
  708. for _, key := range FirstUniqueStrings(SortedKeys(depInfos)) {
  709. info := depInfos[key]
  710. toName := fmt.Sprintf("%s(minSdkVersion:%s)", info.To, info.MinSdkVersion)
  711. if info.IsExternal {
  712. toName = toName + " (external)"
  713. }
  714. fmt.Fprintf(&fullContent, " %s <- %s\n", toName, strings.Join(SortedUniqueStrings(info.From), ", "))
  715. fmt.Fprintf(&flatContent, "%s\n", toName)
  716. }
  717. d.fullListPath = PathForModuleOut(ctx, "depsinfo", "fulllist.txt").OutputPath
  718. WriteFileRule(ctx, d.fullListPath, fullContent.String())
  719. d.flatListPath = PathForModuleOut(ctx, "depsinfo", "flatlist.txt").OutputPath
  720. WriteFileRule(ctx, d.flatListPath, flatContent.String())
  721. ctx.Phony(fmt.Sprintf("%s-depsinfo", ctx.ModuleName()), d.fullListPath, d.flatListPath)
  722. }
  723. // Function called while walking an APEX's payload dependencies.
  724. //
  725. // Return true if the `to` module should be visited, false otherwise.
  726. type PayloadDepsCallback func(ctx ModuleContext, from blueprint.Module, to ApexModule, externalDep bool) bool
  727. type WalkPayloadDepsFunc func(ctx ModuleContext, do PayloadDepsCallback)
  728. // ModuleWithMinSdkVersionCheck represents a module that implements min_sdk_version checks
  729. type ModuleWithMinSdkVersionCheck interface {
  730. Module
  731. MinSdkVersion(ctx EarlyModuleContext) ApiLevel
  732. CheckMinSdkVersion(ctx ModuleContext)
  733. }
  734. // CheckMinSdkVersion checks if every dependency of an updatable module sets min_sdk_version
  735. // accordingly
  736. func CheckMinSdkVersion(ctx ModuleContext, minSdkVersion ApiLevel, walk WalkPayloadDepsFunc) {
  737. // do not enforce min_sdk_version for host
  738. if ctx.Host() {
  739. return
  740. }
  741. // do not enforce for coverage build
  742. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") || ctx.DeviceConfig().NativeCoverageEnabled() || ctx.DeviceConfig().ClangCoverageEnabled() {
  743. return
  744. }
  745. // do not enforce deps.min_sdk_version if APEX/APK doesn't set min_sdk_version
  746. if minSdkVersion.IsNone() {
  747. return
  748. }
  749. walk(ctx, func(ctx ModuleContext, from blueprint.Module, to ApexModule, externalDep bool) bool {
  750. if externalDep {
  751. // external deps are outside the payload boundary, which is "stable"
  752. // interface. We don't have to check min_sdk_version for external
  753. // dependencies.
  754. return false
  755. }
  756. if am, ok := from.(DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
  757. return false
  758. }
  759. if m, ok := to.(ModuleWithMinSdkVersionCheck); ok {
  760. // This dependency performs its own min_sdk_version check, just make sure it sets min_sdk_version
  761. // to trigger the check.
  762. if !m.MinSdkVersion(ctx).Specified() {
  763. ctx.OtherModuleErrorf(m, "must set min_sdk_version")
  764. }
  765. return false
  766. }
  767. if err := to.ShouldSupportSdkVersion(ctx, minSdkVersion); err != nil {
  768. toName := ctx.OtherModuleName(to)
  769. ctx.OtherModuleErrorf(to, "should support min_sdk_version(%v) for %q: %v."+
  770. "\n\nDependency path: %s\n\n"+
  771. "Consider adding 'min_sdk_version: %q' to %q",
  772. minSdkVersion, ctx.ModuleName(), err.Error(),
  773. ctx.GetPathString(false),
  774. minSdkVersion, toName)
  775. return false
  776. }
  777. return true
  778. })
  779. }