bootclasspath_fragment.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. // Copyright (C) 2021 The Android Open Source Project
  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. "io"
  18. "path/filepath"
  19. "reflect"
  20. "strings"
  21. "android/soong/android"
  22. "android/soong/dexpreopt"
  23. "github.com/google/blueprint/proptools"
  24. "github.com/google/blueprint"
  25. )
  26. func init() {
  27. registerBootclasspathFragmentBuildComponents(android.InitRegistrationContext)
  28. android.RegisterSdkMemberType(BootclasspathFragmentSdkMemberType)
  29. }
  30. func registerBootclasspathFragmentBuildComponents(ctx android.RegistrationContext) {
  31. ctx.RegisterModuleType("bootclasspath_fragment", bootclasspathFragmentFactory)
  32. ctx.RegisterModuleType("bootclasspath_fragment_test", testBootclasspathFragmentFactory)
  33. ctx.RegisterModuleType("prebuilt_bootclasspath_fragment", prebuiltBootclasspathFragmentFactory)
  34. }
  35. // BootclasspathFragmentSdkMemberType is the member type used to add bootclasspath_fragments to
  36. // the SDK snapshot. It is exported for use by apex.
  37. var BootclasspathFragmentSdkMemberType = &bootclasspathFragmentMemberType{
  38. SdkMemberTypeBase: android.SdkMemberTypeBase{
  39. PropertyName: "bootclasspath_fragments",
  40. SupportsSdk: true,
  41. },
  42. }
  43. type bootclasspathFragmentContentDependencyTag struct {
  44. blueprint.BaseDependencyTag
  45. }
  46. // Avoid having to make bootclasspath_fragment content visible to the bootclasspath_fragment.
  47. //
  48. // This is a temporary workaround to make it easier to migrate to bootclasspath_fragment modules
  49. // with proper dependencies.
  50. // TODO(b/177892522): Remove this and add needed visibility.
  51. func (b bootclasspathFragmentContentDependencyTag) ExcludeFromVisibilityEnforcement() {
  52. }
  53. // The bootclasspath_fragment contents must never depend on prebuilts.
  54. func (b bootclasspathFragmentContentDependencyTag) ReplaceSourceWithPrebuilt() bool {
  55. return false
  56. }
  57. // SdkMemberType causes dependencies added with this tag to be automatically added to the sdk as if
  58. // they were specified using java_boot_libs or java_sdk_libs.
  59. func (b bootclasspathFragmentContentDependencyTag) SdkMemberType(child android.Module) android.SdkMemberType {
  60. // If the module is a java_sdk_library then treat it as if it was specified in the java_sdk_libs
  61. // property, otherwise treat if it was specified in the java_boot_libs property.
  62. if javaSdkLibrarySdkMemberType.IsInstance(child) {
  63. return javaSdkLibrarySdkMemberType
  64. }
  65. return javaBootLibsSdkMemberType
  66. }
  67. func (b bootclasspathFragmentContentDependencyTag) ExportMember() bool {
  68. return true
  69. }
  70. // Contents of bootclasspath fragments in an apex are considered to be directly in the apex, as if
  71. // they were listed in java_libs.
  72. func (b bootclasspathFragmentContentDependencyTag) CopyDirectlyInAnyApex() {}
  73. // Contents of bootclasspath fragments require files from prebuilt apex files.
  74. func (b bootclasspathFragmentContentDependencyTag) RequiresFilesFromPrebuiltApex() {}
  75. // The tag used for the dependency between the bootclasspath_fragment module and its contents.
  76. var bootclasspathFragmentContentDepTag = bootclasspathFragmentContentDependencyTag{}
  77. var _ android.ExcludeFromVisibilityEnforcementTag = bootclasspathFragmentContentDepTag
  78. var _ android.ReplaceSourceWithPrebuilt = bootclasspathFragmentContentDepTag
  79. var _ android.SdkMemberDependencyTag = bootclasspathFragmentContentDepTag
  80. var _ android.CopyDirectlyInAnyApexTag = bootclasspathFragmentContentDepTag
  81. var _ android.RequiresFilesFromPrebuiltApexTag = bootclasspathFragmentContentDepTag
  82. func IsBootclasspathFragmentContentDepTag(tag blueprint.DependencyTag) bool {
  83. return tag == bootclasspathFragmentContentDepTag
  84. }
  85. // Properties that can be different when coverage is enabled.
  86. type BootclasspathFragmentCoverageAffectedProperties struct {
  87. // The contents of this bootclasspath_fragment, could be either java_library, or java_sdk_library.
  88. //
  89. // A java_sdk_library specified here will also be treated as if it was specified on the stub_libs
  90. // property.
  91. //
  92. // The order of this list matters as it is the order that is used in the bootclasspath.
  93. Contents []string
  94. // The properties for specifying the API stubs provided by this fragment.
  95. BootclasspathAPIProperties
  96. }
  97. type bootclasspathFragmentProperties struct {
  98. // The name of the image this represents.
  99. //
  100. // If specified then it must be one of "art" or "boot".
  101. Image_name *string
  102. // Properties whose values need to differ with and without coverage.
  103. BootclasspathFragmentCoverageAffectedProperties
  104. Coverage BootclasspathFragmentCoverageAffectedProperties
  105. // Hidden API related properties.
  106. Hidden_api HiddenAPIFlagFileProperties
  107. // The list of additional stub libraries which this fragment's contents use but which are not
  108. // provided by another bootclasspath_fragment.
  109. //
  110. // Note, "android-non-updatable" is treated specially. While no such module exists it is treated
  111. // as if it was a java_sdk_library. So, when public API stubs are needed then it will be replaced
  112. // with "android-non-updatable.stubs", with "androidn-non-updatable.system.stubs" when the system
  113. // stubs are needed and so on.
  114. Additional_stubs []string
  115. // Properties that allow a fragment to depend on other fragments. This is needed for hidden API
  116. // processing as it needs access to all the classes used by a fragment including those provided
  117. // by other fragments.
  118. BootclasspathFragmentsDepsProperties
  119. }
  120. type HiddenApiPackageProperties struct {
  121. Hidden_api struct {
  122. // Contains prefixes of a package hierarchy that is provided solely by this
  123. // bootclasspath_fragment.
  124. //
  125. // This affects the signature patterns file that is used to select the subset of monolithic
  126. // hidden API flags. See split_packages property for more details.
  127. Package_prefixes []string
  128. // A list of individual packages that are provided solely by this
  129. // bootclasspath_fragment but which cannot be listed in package_prefixes
  130. // because there are sub-packages which are provided by other modules.
  131. //
  132. // This should only be used for legacy packages. New packages should be
  133. // covered by a package prefix.
  134. Single_packages []string
  135. // The list of split packages provided by this bootclasspath_fragment.
  136. //
  137. // A split package is one that contains classes which are provided by multiple
  138. // bootclasspath_fragment modules.
  139. //
  140. // This defaults to "*" - which treats all packages as being split. A module that has no split
  141. // packages must specify an empty list.
  142. //
  143. // This affects the signature patterns file that is generated by a bootclasspath_fragment and
  144. // used to select the subset of monolithic hidden API flags against which the flags generated
  145. // by the bootclasspath_fragment are compared.
  146. //
  147. // The signature patterns file selects the subset of monolithic hidden API flags using a number
  148. // of patterns, i.e.:
  149. // * The qualified name (including package) of an outermost class, e.g. java/lang/Character.
  150. // This selects all the flags for all the members of this class and any nested classes.
  151. // * A package wildcard, e.g. java/lang/*. This selects all the flags for all the members of all
  152. // the classes in this package (but not in sub-packages).
  153. // * A recursive package wildcard, e.g. java/**. This selects all the flags for all the members
  154. // of all the classes in this package and sub-packages.
  155. //
  156. // The signature patterns file is constructed as follows:
  157. // * All the signatures are retrieved from the all-flags.csv file.
  158. // * The member and inner class names are removed.
  159. // * If a class is in a split package then that is kept, otherwise the class part is removed
  160. // and replaced with a wildcard, i.e. *.
  161. // * If a package matches a package prefix then the package is removed.
  162. // * All the package prefixes are added with a recursive wildcard appended to each, i.e. **.
  163. // * The resulting patterns are sorted.
  164. //
  165. // So, by default (i.e. without specifying any package_prefixes or split_packages) the signature
  166. // patterns is a list of class names, because there are no package packages and all packages are
  167. // assumed to be split.
  168. //
  169. // If any split packages are specified then only those packages are treated as split and all
  170. // other packages are treated as belonging solely to the bootclasspath_fragment and so they use
  171. // wildcard package patterns.
  172. //
  173. // So, if an empty list of split packages is specified then the signature patterns file just
  174. // includes a wildcard package pattern for every package provided by the bootclasspath_fragment.
  175. //
  176. // If split_packages are specified and a package that is split is not listed then it could lead
  177. // to build failures as it will select monolithic flags that are generated by another
  178. // bootclasspath_fragment to compare against the flags provided by this fragment. The latter
  179. // will obviously not contain those flags and that can cause the comparison and build to fail.
  180. //
  181. // If any package prefixes are specified then any matching packages are removed from the
  182. // signature patterns and replaced with a single recursive package pattern.
  183. //
  184. // It is not strictly necessary to specify either package_prefixes or split_packages as the
  185. // defaults will produce a valid set of signature patterns. However, those patterns may include
  186. // implementation details, e.g. names of implementation classes or packages, which will be
  187. // exported to the sdk snapshot in the signature patterns file. That is something that should be
  188. // avoided where possible. Specifying package_prefixes and split_packages allows those
  189. // implementation details to be excluded from the snapshot.
  190. Split_packages []string
  191. }
  192. }
  193. type SourceOnlyBootclasspathProperties struct {
  194. HiddenApiPackageProperties
  195. Coverage HiddenApiPackageProperties
  196. }
  197. type BootclasspathFragmentModule struct {
  198. android.ModuleBase
  199. android.ApexModuleBase
  200. android.SdkBase
  201. ClasspathFragmentBase
  202. // True if this fragment is for testing purposes.
  203. testFragment bool
  204. properties bootclasspathFragmentProperties
  205. sourceOnlyProperties SourceOnlyBootclasspathProperties
  206. // Collect the module directory for IDE info in java/jdeps.go.
  207. modulePaths []string
  208. // Installs for on-device boot image files. This list has entries only if the installs should be
  209. // handled by Make (e.g., the boot image should be installed on the system partition, rather than
  210. // in the APEX).
  211. bootImageDeviceInstalls []dexpreopterInstall
  212. }
  213. // commonBootclasspathFragment defines the methods that are implemented by both source and prebuilt
  214. // bootclasspath fragment modules.
  215. type commonBootclasspathFragment interface {
  216. // produceHiddenAPIOutput produces the all-flags.csv and intermediate files and encodes the flags
  217. // into dex files.
  218. //
  219. // Returns a *HiddenAPIOutput containing the paths for the generated files. Returns nil if the
  220. // module cannot contribute to hidden API processing, e.g. because it is a prebuilt module in a
  221. // versioned sdk.
  222. produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput
  223. // produceBootImageFiles will attempt to produce rules to create the boot image files at the paths
  224. // predefined in the bootImageConfig.
  225. //
  226. // If it could not create the files then it will return nil. Otherwise, it will return a map from
  227. // android.ArchType to the predefined paths of the boot image files.
  228. produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig) bootImageFilesByArch
  229. }
  230. var _ commonBootclasspathFragment = (*BootclasspathFragmentModule)(nil)
  231. // bootImageFilesByArch is a map from android.ArchType to the paths to the boot image files.
  232. //
  233. // The paths include the .art, .oat and .vdex files, one for each of the modules from which the boot
  234. // image is created.
  235. type bootImageFilesByArch map[android.ArchType]android.Paths
  236. func bootclasspathFragmentFactory() android.Module {
  237. m := &BootclasspathFragmentModule{}
  238. m.AddProperties(&m.properties, &m.sourceOnlyProperties)
  239. android.InitApexModule(m)
  240. android.InitSdkAwareModule(m)
  241. initClasspathFragment(m, BOOTCLASSPATH)
  242. android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
  243. android.AddLoadHook(m, func(ctx android.LoadHookContext) {
  244. // If code coverage has been enabled for the framework then append the properties with
  245. // coverage specific properties.
  246. if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
  247. err := proptools.AppendProperties(&m.properties.BootclasspathFragmentCoverageAffectedProperties, &m.properties.Coverage, nil)
  248. if err != nil {
  249. ctx.PropertyErrorf("coverage", "error trying to append coverage specific properties: %s", err)
  250. return
  251. }
  252. err = proptools.AppendProperties(&m.sourceOnlyProperties.HiddenApiPackageProperties, &m.sourceOnlyProperties.Coverage, nil)
  253. if err != nil {
  254. ctx.PropertyErrorf("coverage", "error trying to append hidden api coverage specific properties: %s", err)
  255. return
  256. }
  257. }
  258. // Initialize the contents property from the image_name.
  259. bootclasspathFragmentInitContentsFromImage(ctx, m)
  260. })
  261. return m
  262. }
  263. func testBootclasspathFragmentFactory() android.Module {
  264. m := bootclasspathFragmentFactory().(*BootclasspathFragmentModule)
  265. m.testFragment = true
  266. return m
  267. }
  268. // bootclasspathFragmentInitContentsFromImage will initialize the contents property from the image_name if
  269. // necessary.
  270. func bootclasspathFragmentInitContentsFromImage(ctx android.EarlyModuleContext, m *BootclasspathFragmentModule) {
  271. contents := m.properties.Contents
  272. if len(contents) == 0 {
  273. ctx.PropertyErrorf("contents", "required property is missing")
  274. return
  275. }
  276. if m.properties.Image_name == nil {
  277. // Nothing to do.
  278. return
  279. }
  280. imageName := proptools.String(m.properties.Image_name)
  281. if imageName != "art" {
  282. ctx.PropertyErrorf("image_name", `unknown image name %q, expected "art"`, imageName)
  283. return
  284. }
  285. // TODO(b/177892522): Prebuilts (versioned or not) should not use the image_name property.
  286. if android.IsModuleInVersionedSdk(m) {
  287. // The module is a versioned prebuilt so ignore it. This is done for a couple of reasons:
  288. // 1. There is no way to use this at the moment so ignoring it is safe.
  289. // 2. Attempting to initialize the contents property from the configuration will end up having
  290. // the versioned prebuilt depending on the unversioned prebuilt. That will cause problems
  291. // as the unversioned prebuilt could end up with an APEX variant created for the source
  292. // APEX which will prevent it from having an APEX variant for the prebuilt APEX which in
  293. // turn will prevent it from accessing the dex implementation jar from that which will
  294. // break hidden API processing, amongst others.
  295. return
  296. }
  297. // Get the configuration for the art apex jars. Do not use getImageConfig(ctx) here as this is
  298. // too early in the Soong processing for that to work.
  299. global := dexpreopt.GetGlobalConfig(ctx)
  300. modules := global.ArtApexJars
  301. // Make sure that the apex specified in the configuration is consistent and is one for which
  302. // this boot image is available.
  303. commonApex := ""
  304. for i := 0; i < modules.Len(); i++ {
  305. apex := modules.Apex(i)
  306. jar := modules.Jar(i)
  307. if apex == "platform" {
  308. ctx.ModuleErrorf("ArtApexJars is invalid as it requests a platform variant of %q", jar)
  309. continue
  310. }
  311. if !m.AvailableFor(apex) {
  312. ctx.ModuleErrorf("ArtApexJars configuration incompatible with this module, ArtApexJars expects this to be in apex %q but this is only in apexes %q",
  313. apex, m.ApexAvailable())
  314. continue
  315. }
  316. if commonApex == "" {
  317. commonApex = apex
  318. } else if commonApex != apex {
  319. ctx.ModuleErrorf("ArtApexJars configuration is inconsistent, expected all jars to be in the same apex but it specifies apex %q and %q",
  320. commonApex, apex)
  321. }
  322. }
  323. }
  324. // bootclasspathImageNameContentsConsistencyCheck checks that the configuration that applies to this
  325. // module (if any) matches the contents.
  326. //
  327. // This should be a noop as if image_name="art" then the contents will be set from the ArtApexJars
  328. // config by bootclasspathFragmentInitContentsFromImage so it will be guaranteed to match. However,
  329. // in future this will not be the case.
  330. func (b *BootclasspathFragmentModule) bootclasspathImageNameContentsConsistencyCheck(ctx android.BaseModuleContext) {
  331. imageName := proptools.String(b.properties.Image_name)
  332. if imageName == "art" {
  333. // TODO(b/177892522): Prebuilts (versioned or not) should not use the image_name property.
  334. if android.IsModuleInVersionedSdk(b) {
  335. // The module is a versioned prebuilt so ignore it. This is done for a couple of reasons:
  336. // 1. There is no way to use this at the moment so ignoring it is safe.
  337. // 2. Attempting to initialize the contents property from the configuration will end up having
  338. // the versioned prebuilt depending on the unversioned prebuilt. That will cause problems
  339. // as the unversioned prebuilt could end up with an APEX variant created for the source
  340. // APEX which will prevent it from having an APEX variant for the prebuilt APEX which in
  341. // turn will prevent it from accessing the dex implementation jar from that which will
  342. // break hidden API processing, amongst others.
  343. return
  344. }
  345. // Get the configuration for the art apex jars.
  346. modules := b.getImageConfig(ctx).modules
  347. configuredJars := modules.CopyOfJars()
  348. // Skip the check if the configured jars list is empty as that is a common configuration when
  349. // building targets that do not result in a system image.
  350. if len(configuredJars) == 0 {
  351. return
  352. }
  353. contents := b.properties.Contents
  354. if !reflect.DeepEqual(configuredJars, contents) {
  355. ctx.ModuleErrorf("inconsistency in specification of contents. ArtApexJars configuration specifies %#v, contents property specifies %#v",
  356. configuredJars, contents)
  357. }
  358. }
  359. }
  360. var BootclasspathFragmentApexContentInfoProvider = blueprint.NewProvider(BootclasspathFragmentApexContentInfo{})
  361. // BootclasspathFragmentApexContentInfo contains the bootclasspath_fragments contributions to the
  362. // apex contents.
  363. type BootclasspathFragmentApexContentInfo struct {
  364. // The configured modules, will be empty if this is from a bootclasspath_fragment that does not
  365. // set image_name: "art".
  366. modules android.ConfiguredJarList
  367. // Map from arch type to the boot image files.
  368. bootImageFilesByArch bootImageFilesByArch
  369. // True if the boot image should be installed in the APEX.
  370. shouldInstallBootImageInApex bool
  371. // Map from the base module name (without prebuilt_ prefix) of a fragment's contents module to the
  372. // hidden API encoded dex jar path.
  373. contentModuleDexJarPaths bootDexJarByModule
  374. // Path to the image profile file on host (or empty, if profile is not generated).
  375. profilePathOnHost android.Path
  376. // Install path of the boot image profile if it needs to be installed in the APEX, or empty if not
  377. // needed.
  378. profileInstallPathInApex string
  379. }
  380. func (i BootclasspathFragmentApexContentInfo) Modules() android.ConfiguredJarList {
  381. return i.modules
  382. }
  383. // Get a map from ArchType to the associated boot image's contents for Android.
  384. //
  385. // Extension boot images only return their own files, not the files of the boot images they extend.
  386. func (i BootclasspathFragmentApexContentInfo) AndroidBootImageFilesByArchType() bootImageFilesByArch {
  387. return i.bootImageFilesByArch
  388. }
  389. // Return true if the boot image should be installed in the APEX.
  390. func (i *BootclasspathFragmentApexContentInfo) ShouldInstallBootImageInApex() bool {
  391. return i.shouldInstallBootImageInApex
  392. }
  393. // DexBootJarPathForContentModule returns the path to the dex boot jar for specified module.
  394. //
  395. // The dex boot jar is one which has had hidden API encoding performed on it.
  396. func (i BootclasspathFragmentApexContentInfo) DexBootJarPathForContentModule(module android.Module) (android.Path, error) {
  397. // A bootclasspath_fragment cannot use a prebuilt library so Name() will return the base name
  398. // without a prebuilt_ prefix so is safe to use as the key for the contentModuleDexJarPaths.
  399. name := module.Name()
  400. if dexJar, ok := i.contentModuleDexJarPaths[name]; ok {
  401. return dexJar, nil
  402. } else {
  403. return nil, fmt.Errorf("unknown bootclasspath_fragment content module %s, expected one of %s",
  404. name, strings.Join(android.SortedStringKeys(i.contentModuleDexJarPaths), ", "))
  405. }
  406. }
  407. func (i BootclasspathFragmentApexContentInfo) ProfilePathOnHost() android.Path {
  408. return i.profilePathOnHost
  409. }
  410. func (i BootclasspathFragmentApexContentInfo) ProfileInstallPathInApex() string {
  411. return i.profileInstallPathInApex
  412. }
  413. func (b *BootclasspathFragmentModule) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  414. tag := ctx.OtherModuleDependencyTag(dep)
  415. if IsBootclasspathFragmentContentDepTag(tag) {
  416. // Boot image contents are automatically added to apex.
  417. return true
  418. }
  419. if android.IsMetaDependencyTag(tag) {
  420. // Cross-cutting metadata dependencies are metadata.
  421. return false
  422. }
  423. panic(fmt.Errorf("boot_image module %q should not have a dependency on %q via tag %s", b, dep, android.PrettyPrintTag(tag)))
  424. }
  425. func (b *BootclasspathFragmentModule) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
  426. return nil
  427. }
  428. // ComponentDepsMutator adds dependencies onto modules before any prebuilt modules without a
  429. // corresponding source module are renamed. This means that adding a dependency using a name without
  430. // a prebuilt_ prefix will always resolve to a source module and when using a name with that prefix
  431. // it will always resolve to a prebuilt module.
  432. func (b *BootclasspathFragmentModule) ComponentDepsMutator(ctx android.BottomUpMutatorContext) {
  433. module := ctx.Module()
  434. _, isSourceModule := module.(*BootclasspathFragmentModule)
  435. for _, name := range b.properties.Contents {
  436. // A bootclasspath_fragment must depend only on other source modules, while the
  437. // prebuilt_bootclasspath_fragment must only depend on other prebuilt modules.
  438. //
  439. // TODO(b/177892522) - avoid special handling of jacocoagent.
  440. if !isSourceModule && name != "jacocoagent" {
  441. name = android.PrebuiltNameFromSource(name)
  442. }
  443. ctx.AddDependency(module, bootclasspathFragmentContentDepTag, name)
  444. }
  445. }
  446. func (b *BootclasspathFragmentModule) DepsMutator(ctx android.BottomUpMutatorContext) {
  447. // Add dependencies onto all the modules that provide the API stubs for classes on this
  448. // bootclasspath fragment.
  449. hiddenAPIAddStubLibDependencies(ctx, b.properties.apiScopeToStubLibs())
  450. for _, additionalStubModule := range b.properties.Additional_stubs {
  451. for _, apiScope := range hiddenAPISdkLibrarySupportedScopes {
  452. // Add a dependency onto a possibly scope specific stub library.
  453. scopeSpecificDependency := apiScope.scopeSpecificStubModule(ctx, additionalStubModule)
  454. tag := hiddenAPIStubsDependencyTag{apiScope: apiScope, fromAdditionalDependency: true}
  455. ctx.AddVariationDependencies(nil, tag, scopeSpecificDependency)
  456. }
  457. }
  458. if SkipDexpreoptBootJars(ctx) {
  459. return
  460. }
  461. // Add a dependency onto the dex2oat tool which is needed for creating the boot image. The
  462. // path is retrieved from the dependency by GetGlobalSoongConfig(ctx).
  463. dexpreopt.RegisterToolDeps(ctx)
  464. }
  465. func (b *BootclasspathFragmentModule) BootclasspathDepsMutator(ctx android.BottomUpMutatorContext) {
  466. // Add dependencies on all the fragments.
  467. b.properties.BootclasspathFragmentsDepsProperties.addDependenciesOntoFragments(ctx)
  468. }
  469. func (b *BootclasspathFragmentModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  470. // Only perform a consistency check if this module is the active module. That will prevent an
  471. // unused prebuilt that was created without instrumentation from breaking an instrumentation
  472. // build.
  473. if isActiveModule(ctx.Module()) {
  474. b.bootclasspathImageNameContentsConsistencyCheck(ctx)
  475. }
  476. // Generate classpaths.proto config
  477. b.generateClasspathProtoBuildActions(ctx)
  478. // Collect the module directory for IDE info in java/jdeps.go.
  479. b.modulePaths = append(b.modulePaths, ctx.ModuleDir())
  480. // Gather the bootclasspath fragment's contents.
  481. var contents []android.Module
  482. ctx.VisitDirectDeps(func(module android.Module) {
  483. tag := ctx.OtherModuleDependencyTag(module)
  484. if IsBootclasspathFragmentContentDepTag(tag) {
  485. contents = append(contents, module)
  486. }
  487. })
  488. fragments := gatherApexModulePairDepsWithTag(ctx, bootclasspathFragmentDepTag)
  489. // Verify that the image_name specified on a bootclasspath_fragment is valid even if this is a
  490. // prebuilt which will not use the image config.
  491. imageConfig := b.getImageConfig(ctx)
  492. // A versioned prebuilt_bootclasspath_fragment cannot and does not need to perform hidden API
  493. // processing. It cannot do it because it is not part of a prebuilt_apex and so has no access to
  494. // the correct dex implementation jar. It does not need to because the platform-bootclasspath
  495. // always references the latest bootclasspath_fragments.
  496. if !android.IsModuleInVersionedSdk(ctx.Module()) {
  497. // Perform hidden API processing.
  498. hiddenAPIOutput := b.generateHiddenAPIBuildActions(ctx, contents, fragments)
  499. var bootImageFilesByArch bootImageFilesByArch
  500. if imageConfig != nil {
  501. // Delegate the production of the boot image files to a module type specific method.
  502. common := ctx.Module().(commonBootclasspathFragment)
  503. bootImageFilesByArch = common.produceBootImageFiles(ctx, imageConfig)
  504. if shouldCopyBootFilesToPredefinedLocations(ctx, imageConfig) {
  505. // Zip the boot image files up, if available. This will generate the zip file in a
  506. // predefined location.
  507. buildBootImageZipInPredefinedLocation(ctx, imageConfig, bootImageFilesByArch)
  508. // Copy the dex jars of this fragment's content modules to their predefined locations.
  509. copyBootJarsToPredefinedLocations(ctx, hiddenAPIOutput.EncodedBootDexFilesByModule, imageConfig.dexPathsByModule)
  510. }
  511. for _, variant := range imageConfig.apexVariants() {
  512. arch := variant.target.Arch.ArchType.String()
  513. for _, install := range variant.deviceInstalls {
  514. // Remove the "/" prefix because the path should be relative to $ANDROID_PRODUCT_OUT.
  515. installDir := strings.TrimPrefix(filepath.Dir(install.To), "/")
  516. installBase := filepath.Base(install.To)
  517. installPath := android.PathForModuleInPartitionInstall(ctx, "", installDir)
  518. b.bootImageDeviceInstalls = append(b.bootImageDeviceInstalls, dexpreopterInstall{
  519. name: arch + "-" + installBase,
  520. moduleName: b.Name(),
  521. outputPathOnHost: install.From,
  522. installDirOnDevice: installPath,
  523. installFileOnDevice: installBase,
  524. })
  525. }
  526. }
  527. }
  528. // A prebuilt fragment cannot contribute to an apex.
  529. if !android.IsModulePrebuilt(ctx.Module()) {
  530. // Provide the apex content info.
  531. b.provideApexContentInfo(ctx, imageConfig, hiddenAPIOutput, bootImageFilesByArch)
  532. }
  533. } else {
  534. // Versioned fragments are not needed by make.
  535. b.HideFromMake()
  536. }
  537. // In order for information about bootclasspath_fragment modules to be added to module-info.json
  538. // it is necessary to output an entry to Make. As bootclasspath_fragment modules are part of an
  539. // APEX there can be multiple variants, including the default/platform variant and only one can
  540. // be output to Make but it does not really matter which variant is output. The default/platform
  541. // variant is the first (ctx.PrimaryModule()) and is usually hidden from make so this just picks
  542. // the last variant (ctx.FinalModule()).
  543. if ctx.Module() != ctx.FinalModule() {
  544. b.HideFromMake()
  545. }
  546. }
  547. // shouldCopyBootFilesToPredefinedLocations determines whether the current module should copy boot
  548. // files, e.g. boot dex jars or boot image files, to the predefined location expected by the rest
  549. // of the build.
  550. //
  551. // This ensures that only a single module will copy its files to the image configuration.
  552. func shouldCopyBootFilesToPredefinedLocations(ctx android.ModuleContext, imageConfig *bootImageConfig) bool {
  553. // Bootclasspath fragment modules that are for the platform do not produce boot related files.
  554. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  555. if apexInfo.IsForPlatform() {
  556. return false
  557. }
  558. // If the image configuration has no modules specified then it means that the build has been
  559. // configured to build something other than a boot image, e.g. an sdk, so do not try and copy the
  560. // files.
  561. if imageConfig.modules.Len() == 0 {
  562. return false
  563. }
  564. // Only copy files from the module that is preferred.
  565. return isActiveModule(ctx.Module())
  566. }
  567. // provideApexContentInfo creates, initializes and stores the apex content info for use by other
  568. // modules.
  569. func (b *BootclasspathFragmentModule) provideApexContentInfo(ctx android.ModuleContext, imageConfig *bootImageConfig, hiddenAPIOutput *HiddenAPIOutput, bootImageFilesByArch bootImageFilesByArch) {
  570. // Construct the apex content info from the config.
  571. info := BootclasspathFragmentApexContentInfo{
  572. // Populate the apex content info with paths to the dex jars.
  573. contentModuleDexJarPaths: hiddenAPIOutput.EncodedBootDexFilesByModule,
  574. }
  575. if imageConfig != nil {
  576. info.modules = imageConfig.modules
  577. global := dexpreopt.GetGlobalConfig(ctx)
  578. if !global.DisableGenerateProfile {
  579. info.profilePathOnHost = imageConfig.profilePathOnHost
  580. info.profileInstallPathInApex = imageConfig.profileInstallPathInApex
  581. }
  582. info.shouldInstallBootImageInApex = imageConfig.shouldInstallInApex()
  583. }
  584. info.bootImageFilesByArch = bootImageFilesByArch
  585. // Make the apex content info available for other modules.
  586. ctx.SetProvider(BootclasspathFragmentApexContentInfoProvider, info)
  587. }
  588. // generateClasspathProtoBuildActions generates all required build actions for classpath.proto config
  589. func (b *BootclasspathFragmentModule) generateClasspathProtoBuildActions(ctx android.ModuleContext) {
  590. var classpathJars []classpathJar
  591. configuredJars := b.configuredJars(ctx)
  592. if "art" == proptools.String(b.properties.Image_name) {
  593. // ART and platform boot jars must have a corresponding entry in DEX2OATBOOTCLASSPATH
  594. classpathJars = configuredJarListToClasspathJars(ctx, configuredJars, BOOTCLASSPATH, DEX2OATBOOTCLASSPATH)
  595. } else {
  596. classpathJars = configuredJarListToClasspathJars(ctx, configuredJars, b.classpathType)
  597. }
  598. b.classpathFragmentBase().generateClasspathProtoBuildActions(ctx, configuredJars, classpathJars)
  599. }
  600. func (b *BootclasspathFragmentModule) configuredJars(ctx android.ModuleContext) android.ConfiguredJarList {
  601. if "art" == proptools.String(b.properties.Image_name) {
  602. return b.getImageConfig(ctx).modules
  603. }
  604. global := dexpreopt.GetGlobalConfig(ctx)
  605. possibleUpdatableModules := gatherPossibleApexModuleNamesAndStems(ctx, b.properties.Contents, bootclasspathFragmentContentDepTag)
  606. jars, unknown := global.ApexBootJars.Filter(possibleUpdatableModules)
  607. // TODO(satayev): for apex_test we want to include all contents unconditionally to classpaths
  608. // config. However, any test specific jars would not be present in ApexBootJars. Instead,
  609. // we should check if we are creating a config for apex_test via ApexInfo and amend the values.
  610. // This is an exception to support end-to-end test for SdkExtensions, until such support exists.
  611. if android.InList("test_framework-sdkextensions", possibleUpdatableModules) {
  612. jars = jars.Append("com.android.sdkext", "test_framework-sdkextensions")
  613. } else if android.InList("AddNewActivity", possibleUpdatableModules) {
  614. jars = jars.Append("test_com.android.cts.frameworkresapkplits", "AddNewActivity")
  615. } else if android.InList("test_framework-apexd", possibleUpdatableModules) {
  616. jars = jars.Append("com.android.apex.test_package", "test_framework-apexd")
  617. } else if global.ApexBootJars.Len() != 0 && !android.IsModuleInVersionedSdk(ctx.Module()) {
  618. unknown = android.RemoveListFromList(unknown, b.properties.Coverage.Contents)
  619. _, unknown = android.RemoveFromList("core-icu4j", unknown)
  620. if len(unknown) > 0 {
  621. ctx.ModuleErrorf("%s in contents must also be declared in PRODUCT_APEX_BOOT_JARS", unknown)
  622. }
  623. }
  624. return jars
  625. }
  626. func (b *BootclasspathFragmentModule) getImageConfig(ctx android.EarlyModuleContext) *bootImageConfig {
  627. // Get a map of the image configs that are supported.
  628. imageConfigs := genBootImageConfigs(ctx)
  629. // Retrieve the config for this image.
  630. imageNamePtr := b.properties.Image_name
  631. if imageNamePtr == nil {
  632. return nil
  633. }
  634. imageName := *imageNamePtr
  635. imageConfig := imageConfigs[imageName]
  636. if imageConfig == nil {
  637. ctx.PropertyErrorf("image_name", "Unknown image name %q, expected one of %s", imageName, strings.Join(android.SortedStringKeys(imageConfigs), ", "))
  638. return nil
  639. }
  640. return imageConfig
  641. }
  642. // generateHiddenAPIBuildActions generates all the hidden API related build rules.
  643. func (b *BootclasspathFragmentModule) generateHiddenAPIBuildActions(ctx android.ModuleContext, contents []android.Module, fragments []android.Module) *HiddenAPIOutput {
  644. // Create hidden API input structure.
  645. input := b.createHiddenAPIFlagInput(ctx, contents, fragments)
  646. // Delegate the production of the hidden API all-flags.csv file to a module type specific method.
  647. common := ctx.Module().(commonBootclasspathFragment)
  648. output := common.produceHiddenAPIOutput(ctx, contents, input)
  649. // If the source or prebuilts module does not provide a signature patterns file then generate one
  650. // from the flags.
  651. // TODO(b/192868581): Remove once the source and prebuilts provide a signature patterns file of
  652. // their own.
  653. if output.SignaturePatternsPath == nil {
  654. output.SignaturePatternsPath = buildRuleSignaturePatternsFile(
  655. ctx, output.AllFlagsPath, []string{"*"}, nil, nil)
  656. }
  657. // Initialize a HiddenAPIInfo structure.
  658. hiddenAPIInfo := HiddenAPIInfo{
  659. // The monolithic hidden API processing needs access to the flag files that override the default
  660. // flags from all the fragments whether or not they actually perform their own hidden API flag
  661. // generation. That is because the monolithic hidden API processing uses those flag files to
  662. // perform its own flag generation.
  663. FlagFilesByCategory: input.FlagFilesByCategory,
  664. // Other bootclasspath_fragments that depend on this need the transitive set of stub dex jars
  665. // from this to resolve any references from their code to classes provided by this fragment
  666. // and the fragments this depends upon.
  667. TransitiveStubDexJarsByScope: input.transitiveStubDexJarsByScope(),
  668. }
  669. // The monolithic hidden API processing also needs access to all the output files produced by
  670. // hidden API processing of this fragment.
  671. hiddenAPIInfo.HiddenAPIFlagOutput = output.HiddenAPIFlagOutput
  672. // Provide it for use by other modules.
  673. ctx.SetProvider(HiddenAPIInfoProvider, hiddenAPIInfo)
  674. return output
  675. }
  676. // retrieveLegacyEncodedBootDexFiles attempts to retrieve the legacy encoded boot dex jar files.
  677. func retrieveLegacyEncodedBootDexFiles(ctx android.ModuleContext, contents []android.Module) bootDexJarByModule {
  678. // If the current bootclasspath_fragment is the active module or a source module then retrieve the
  679. // encoded dex files, otherwise return an empty map.
  680. //
  681. // An inactive (i.e. not preferred) bootclasspath_fragment needs to retrieve the encoded dex jars
  682. // as they are still needed by an apex. An inactive prebuilt_bootclasspath_fragment does not need
  683. // to do so and may not yet have access to dex boot jars from a prebuilt_apex/apex_set.
  684. if isActiveModule(ctx.Module()) || !android.IsModulePrebuilt(ctx.Module()) {
  685. return extractEncodedDexJarsFromModules(ctx, contents)
  686. } else {
  687. return nil
  688. }
  689. }
  690. // createHiddenAPIFlagInput creates a HiddenAPIFlagInput struct and initializes it with information derived
  691. // from the properties on this module and its dependencies.
  692. func (b *BootclasspathFragmentModule) createHiddenAPIFlagInput(ctx android.ModuleContext, contents []android.Module, fragments []android.Module) HiddenAPIFlagInput {
  693. // Merge the HiddenAPIInfo from all the fragment dependencies.
  694. dependencyHiddenApiInfo := newHiddenAPIInfo()
  695. dependencyHiddenApiInfo.mergeFromFragmentDeps(ctx, fragments)
  696. // Create hidden API flag input structure.
  697. input := newHiddenAPIFlagInput()
  698. // Update the input structure with information obtained from the stub libraries.
  699. input.gatherStubLibInfo(ctx, contents)
  700. // Populate with flag file paths from the properties.
  701. input.extractFlagFilesFromProperties(ctx, &b.properties.Hidden_api)
  702. // Add the stub dex jars from this module's fragment dependencies.
  703. input.DependencyStubDexJarsByScope.addStubDexJarsByModule(dependencyHiddenApiInfo.TransitiveStubDexJarsByScope)
  704. return input
  705. }
  706. // isTestFragment returns true if the current module is a test bootclasspath_fragment.
  707. func (b *BootclasspathFragmentModule) isTestFragment() bool {
  708. if b.testFragment {
  709. return true
  710. }
  711. // TODO(b/194063708): Once test fragments all use bootclasspath_fragment_test
  712. // Some temporary exceptions until all test fragments use the
  713. // bootclasspath_fragment_test module type.
  714. name := b.BaseModuleName()
  715. if strings.HasPrefix(name, "test_") {
  716. return true
  717. }
  718. if name == "apex.apexd_test_bootclasspath-fragment" {
  719. return true
  720. }
  721. return false
  722. }
  723. // produceHiddenAPIOutput produces the hidden API all-flags.csv file (and supporting files)
  724. // for the fragment as well as encoding the flags in the boot dex jars.
  725. func (b *BootclasspathFragmentModule) produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput {
  726. // Generate the rules to create the hidden API flags and update the supplied hiddenAPIInfo with the
  727. // paths to the created files.
  728. output := hiddenAPIRulesForBootclasspathFragment(ctx, contents, input)
  729. // If the module specifies split_packages or package_prefixes then use those to generate the
  730. // signature patterns.
  731. splitPackages := b.sourceOnlyProperties.Hidden_api.Split_packages
  732. packagePrefixes := b.sourceOnlyProperties.Hidden_api.Package_prefixes
  733. singlePackages := b.sourceOnlyProperties.Hidden_api.Single_packages
  734. if splitPackages != nil || packagePrefixes != nil || singlePackages != nil {
  735. output.SignaturePatternsPath = buildRuleSignaturePatternsFile(
  736. ctx, output.AllFlagsPath, splitPackages, packagePrefixes, singlePackages)
  737. } else if !b.isTestFragment() {
  738. ctx.ModuleErrorf(`Must specify at least one of the split_packages, package_prefixes and single_packages properties
  739. If this is a new bootclasspath_fragment or you are unsure what to do add the
  740. the following to the bootclasspath_fragment:
  741. hidden_api: {split_packages: ["*"]},
  742. and then run the following:
  743. m analyze_bcpf && analyze_bcpf --bcpf %q
  744. it will analyze the bootclasspath_fragment and provide hints as to what you
  745. should specify here. If you are happy with its suggestions then you can add
  746. the --fix option and it will fix them for you.`, b.BaseModuleName())
  747. }
  748. return output
  749. }
  750. // produceBootImageFiles builds the boot image files from the source if it is required.
  751. func (b *BootclasspathFragmentModule) produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig) bootImageFilesByArch {
  752. if SkipDexpreoptBootJars(ctx) {
  753. return nil
  754. }
  755. // Only generate the boot image if the configuration does not skip it.
  756. return b.generateBootImageBuildActions(ctx, imageConfig)
  757. }
  758. // generateBootImageBuildActions generates ninja rules to create the boot image if required for this
  759. // module.
  760. //
  761. // If it could not create the files then it will return nil. Otherwise, it will return a map from
  762. // android.ArchType to the predefined paths of the boot image files.
  763. func (b *BootclasspathFragmentModule) generateBootImageBuildActions(ctx android.ModuleContext, imageConfig *bootImageConfig) bootImageFilesByArch {
  764. global := dexpreopt.GetGlobalConfig(ctx)
  765. if !shouldBuildBootImages(ctx.Config(), global) {
  766. return nil
  767. }
  768. // Bootclasspath fragment modules that are for the platform do not produce a boot image.
  769. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  770. if apexInfo.IsForPlatform() {
  771. return nil
  772. }
  773. // Bootclasspath fragment modules that are versioned do not produce a boot image.
  774. if android.IsModuleInVersionedSdk(ctx.Module()) {
  775. return nil
  776. }
  777. // Build a profile for the image config and then use that to build the boot image.
  778. profile := bootImageProfileRule(ctx, imageConfig)
  779. // Build boot image files for the host variants.
  780. buildBootImageVariantsForBuildOs(ctx, imageConfig, profile)
  781. // Build boot image files for the android variants.
  782. androidBootImageFilesByArch := buildBootImageVariantsForAndroidOs(ctx, imageConfig, profile)
  783. // Return the boot image files for the android variants for inclusion in an APEX and to be zipped
  784. // up for the dist.
  785. return androidBootImageFilesByArch
  786. }
  787. func (b *BootclasspathFragmentModule) AndroidMkEntries() []android.AndroidMkEntries {
  788. // Use the generated classpath proto as the output.
  789. outputFile := b.outputFilepath
  790. // Create a fake entry that will cause this to be added to the module-info.json file.
  791. entriesList := []android.AndroidMkEntries{{
  792. Class: "FAKE",
  793. OutputFile: android.OptionalPathForPath(outputFile),
  794. Include: "$(BUILD_PHONY_PACKAGE)",
  795. ExtraFooters: []android.AndroidMkExtraFootersFunc{
  796. func(w io.Writer, name, prefix, moduleDir string) {
  797. // Allow the bootclasspath_fragment to be built by simply passing its name on the command
  798. // line.
  799. fmt.Fprintln(w, ".PHONY:", b.Name())
  800. fmt.Fprintln(w, b.Name()+":", outputFile.String())
  801. },
  802. },
  803. }}
  804. for _, install := range b.bootImageDeviceInstalls {
  805. entriesList = append(entriesList, install.ToMakeEntries())
  806. }
  807. return entriesList
  808. }
  809. // Returns the names of all Make modules that handle the installation of the boot image.
  810. func (b *BootclasspathFragmentModule) BootImageDeviceInstallMakeModules() []string {
  811. var makeModules []string
  812. for _, install := range b.bootImageDeviceInstalls {
  813. makeModules = append(makeModules, install.FullModuleName())
  814. }
  815. return makeModules
  816. }
  817. // Collect information for opening IDE project files in java/jdeps.go.
  818. func (b *BootclasspathFragmentModule) IDEInfo(dpInfo *android.IdeInfo) {
  819. dpInfo.Deps = append(dpInfo.Deps, b.properties.Contents...)
  820. dpInfo.Paths = append(dpInfo.Paths, b.modulePaths...)
  821. }
  822. type bootclasspathFragmentMemberType struct {
  823. android.SdkMemberTypeBase
  824. }
  825. func (b *bootclasspathFragmentMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
  826. ctx.AddVariationDependencies(nil, dependencyTag, names...)
  827. }
  828. func (b *bootclasspathFragmentMemberType) IsInstance(module android.Module) bool {
  829. _, ok := module.(*BootclasspathFragmentModule)
  830. return ok
  831. }
  832. func (b *bootclasspathFragmentMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
  833. if b.PropertyName == "boot_images" {
  834. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "prebuilt_boot_image")
  835. } else {
  836. return ctx.SnapshotBuilder().AddPrebuiltModule(member, "prebuilt_bootclasspath_fragment")
  837. }
  838. }
  839. func (b *bootclasspathFragmentMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
  840. return &bootclasspathFragmentSdkMemberProperties{}
  841. }
  842. type bootclasspathFragmentSdkMemberProperties struct {
  843. android.SdkMemberPropertiesBase
  844. // The image name
  845. Image_name *string
  846. // Contents of the bootclasspath fragment
  847. Contents []string
  848. // Stub_libs properties.
  849. Stub_libs []string
  850. Core_platform_stub_libs []string
  851. // Fragment properties
  852. Fragments []ApexVariantReference
  853. // Flag files by *hiddenAPIFlagFileCategory
  854. Flag_files_by_category FlagFilesByCategory
  855. // The path to the generated annotation-flags.csv file.
  856. Annotation_flags_path android.OptionalPath
  857. // The path to the generated metadata.csv file.
  858. Metadata_path android.OptionalPath
  859. // The path to the generated index.csv file.
  860. Index_path android.OptionalPath
  861. // The path to the generated stub-flags.csv file.
  862. Stub_flags_path android.OptionalPath `supported_build_releases:"S"`
  863. // The path to the generated all-flags.csv file.
  864. All_flags_path android.OptionalPath `supported_build_releases:"S"`
  865. // The path to the generated signature-patterns.csv file.
  866. Signature_patterns_path android.OptionalPath `supported_build_releases:"Tiramisu+"`
  867. // The path to the generated filtered-stub-flags.csv file.
  868. Filtered_stub_flags_path android.OptionalPath `supported_build_releases:"Tiramisu+"`
  869. // The path to the generated filtered-flags.csv file.
  870. Filtered_flags_path android.OptionalPath `supported_build_releases:"Tiramisu+"`
  871. }
  872. func (b *bootclasspathFragmentSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
  873. module := variant.(*BootclasspathFragmentModule)
  874. b.Image_name = module.properties.Image_name
  875. b.Contents = module.properties.Contents
  876. // Get the hidden API information from the module.
  877. mctx := ctx.SdkModuleContext()
  878. hiddenAPIInfo := mctx.OtherModuleProvider(module, HiddenAPIInfoProvider).(HiddenAPIInfo)
  879. b.Flag_files_by_category = hiddenAPIInfo.FlagFilesByCategory
  880. // Copy all the generated file paths.
  881. b.Annotation_flags_path = android.OptionalPathForPath(hiddenAPIInfo.AnnotationFlagsPath)
  882. b.Metadata_path = android.OptionalPathForPath(hiddenAPIInfo.MetadataPath)
  883. b.Index_path = android.OptionalPathForPath(hiddenAPIInfo.IndexPath)
  884. b.Stub_flags_path = android.OptionalPathForPath(hiddenAPIInfo.StubFlagsPath)
  885. b.All_flags_path = android.OptionalPathForPath(hiddenAPIInfo.AllFlagsPath)
  886. b.Signature_patterns_path = android.OptionalPathForPath(hiddenAPIInfo.SignaturePatternsPath)
  887. b.Filtered_stub_flags_path = android.OptionalPathForPath(hiddenAPIInfo.FilteredStubFlagsPath)
  888. b.Filtered_flags_path = android.OptionalPathForPath(hiddenAPIInfo.FilteredFlagsPath)
  889. // Copy stub_libs properties.
  890. b.Stub_libs = module.properties.Api.Stub_libs
  891. b.Core_platform_stub_libs = module.properties.Core_platform_api.Stub_libs
  892. // Copy fragment properties.
  893. b.Fragments = module.properties.Fragments
  894. }
  895. func (b *bootclasspathFragmentSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
  896. if b.Image_name != nil {
  897. propertySet.AddProperty("image_name", *b.Image_name)
  898. }
  899. builder := ctx.SnapshotBuilder()
  900. requiredMemberDependency := builder.SdkMemberReferencePropertyTag(true)
  901. if len(b.Contents) > 0 {
  902. propertySet.AddPropertyWithTag("contents", b.Contents, requiredMemberDependency)
  903. }
  904. if len(b.Stub_libs) > 0 {
  905. apiPropertySet := propertySet.AddPropertySet("api")
  906. apiPropertySet.AddPropertyWithTag("stub_libs", b.Stub_libs, requiredMemberDependency)
  907. }
  908. if len(b.Core_platform_stub_libs) > 0 {
  909. corePlatformApiPropertySet := propertySet.AddPropertySet("core_platform_api")
  910. corePlatformApiPropertySet.AddPropertyWithTag("stub_libs", b.Core_platform_stub_libs, requiredMemberDependency)
  911. }
  912. if len(b.Fragments) > 0 {
  913. propertySet.AddProperty("fragments", b.Fragments)
  914. }
  915. hiddenAPISet := propertySet.AddPropertySet("hidden_api")
  916. hiddenAPIDir := "hiddenapi"
  917. // Copy manually curated flag files specified on the bootclasspath_fragment.
  918. if b.Flag_files_by_category != nil {
  919. for _, category := range HiddenAPIFlagFileCategories {
  920. paths := b.Flag_files_by_category[category]
  921. if len(paths) > 0 {
  922. dests := []string{}
  923. for _, p := range paths {
  924. dest := filepath.Join(hiddenAPIDir, p.Base())
  925. builder.CopyToSnapshot(p, dest)
  926. dests = append(dests, dest)
  927. }
  928. hiddenAPISet.AddProperty(category.PropertyName, dests)
  929. }
  930. }
  931. }
  932. copyOptionalPath := func(path android.OptionalPath, property string) {
  933. if path.Valid() {
  934. p := path.Path()
  935. dest := filepath.Join(hiddenAPIDir, p.Base())
  936. builder.CopyToSnapshot(p, dest)
  937. hiddenAPISet.AddProperty(property, dest)
  938. }
  939. }
  940. // Copy all the generated files, if available.
  941. copyOptionalPath(b.Annotation_flags_path, "annotation_flags")
  942. copyOptionalPath(b.Metadata_path, "metadata")
  943. copyOptionalPath(b.Index_path, "index")
  944. copyOptionalPath(b.Stub_flags_path, "stub_flags")
  945. copyOptionalPath(b.All_flags_path, "all_flags")
  946. copyOptionalPath(b.Signature_patterns_path, "signature_patterns")
  947. copyOptionalPath(b.Filtered_stub_flags_path, "filtered_stub_flags")
  948. copyOptionalPath(b.Filtered_flags_path, "filtered_flags")
  949. }
  950. var _ android.SdkMemberType = (*bootclasspathFragmentMemberType)(nil)
  951. // prebuiltBootclasspathFragmentProperties contains additional prebuilt_bootclasspath_fragment
  952. // specific properties.
  953. type prebuiltBootclasspathFragmentProperties struct {
  954. Hidden_api struct {
  955. // The path to the annotation-flags.csv file created by the bootclasspath_fragment.
  956. Annotation_flags *string `android:"path"`
  957. // The path to the metadata.csv file created by the bootclasspath_fragment.
  958. Metadata *string `android:"path"`
  959. // The path to the index.csv file created by the bootclasspath_fragment.
  960. Index *string `android:"path"`
  961. // The path to the signature-patterns.csv file created by the bootclasspath_fragment.
  962. Signature_patterns *string `android:"path"`
  963. // The path to the stub-flags.csv file created by the bootclasspath_fragment.
  964. Stub_flags *string `android:"path"`
  965. // The path to the all-flags.csv file created by the bootclasspath_fragment.
  966. All_flags *string `android:"path"`
  967. // The path to the filtered-stub-flags.csv file created by the bootclasspath_fragment.
  968. Filtered_stub_flags *string `android:"path"`
  969. // The path to the filtered-flags.csv file created by the bootclasspath_fragment.
  970. Filtered_flags *string `android:"path"`
  971. }
  972. }
  973. // A prebuilt version of the bootclasspath_fragment module.
  974. //
  975. // At the moment this is basically just a bootclasspath_fragment module that can be used as a
  976. // prebuilt. Eventually as more functionality is migrated into the bootclasspath_fragment module
  977. // type from the various singletons then this will diverge.
  978. type PrebuiltBootclasspathFragmentModule struct {
  979. BootclasspathFragmentModule
  980. prebuilt android.Prebuilt
  981. // Additional prebuilt specific properties.
  982. prebuiltProperties prebuiltBootclasspathFragmentProperties
  983. }
  984. func (module *PrebuiltBootclasspathFragmentModule) Prebuilt() *android.Prebuilt {
  985. return &module.prebuilt
  986. }
  987. func (module *PrebuiltBootclasspathFragmentModule) Name() string {
  988. return module.prebuilt.Name(module.ModuleBase.Name())
  989. }
  990. // produceHiddenAPIOutput returns a path to the prebuilt all-flags.csv or nil if none is specified.
  991. func (module *PrebuiltBootclasspathFragmentModule) produceHiddenAPIOutput(ctx android.ModuleContext, contents []android.Module, input HiddenAPIFlagInput) *HiddenAPIOutput {
  992. pathForOptionalSrc := func(src *string, defaultPath android.Path) android.Path {
  993. if src == nil {
  994. return defaultPath
  995. }
  996. return android.PathForModuleSrc(ctx, *src)
  997. }
  998. pathForSrc := func(property string, src *string) android.Path {
  999. if src == nil {
  1000. ctx.PropertyErrorf(property, "is required but was not specified")
  1001. return android.PathForModuleSrc(ctx, "missing", property)
  1002. }
  1003. return android.PathForModuleSrc(ctx, *src)
  1004. }
  1005. // Retrieve the dex files directly from the content modules. They in turn should retrieve the
  1006. // encoded dex jars from the prebuilt .apex files.
  1007. encodedBootDexJarsByModule := extractEncodedDexJarsFromModules(ctx, contents)
  1008. output := HiddenAPIOutput{
  1009. HiddenAPIFlagOutput: HiddenAPIFlagOutput{
  1010. AnnotationFlagsPath: pathForSrc("hidden_api.annotation_flags", module.prebuiltProperties.Hidden_api.Annotation_flags),
  1011. MetadataPath: pathForSrc("hidden_api.metadata", module.prebuiltProperties.Hidden_api.Metadata),
  1012. IndexPath: pathForSrc("hidden_api.index", module.prebuiltProperties.Hidden_api.Index),
  1013. SignaturePatternsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Signature_patterns, nil),
  1014. // TODO: Temporarily handle stub_flags/all_flags properties until prebuilts have been updated.
  1015. StubFlagsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Stub_flags, nil),
  1016. AllFlagsPath: pathForOptionalSrc(module.prebuiltProperties.Hidden_api.All_flags, nil),
  1017. },
  1018. EncodedBootDexFilesByModule: encodedBootDexJarsByModule,
  1019. }
  1020. // TODO: Temporarily fallback to stub_flags/all_flags properties until prebuilts have been updated.
  1021. output.FilteredStubFlagsPath = pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Filtered_stub_flags, output.StubFlagsPath)
  1022. output.FilteredFlagsPath = pathForOptionalSrc(module.prebuiltProperties.Hidden_api.Filtered_flags, output.AllFlagsPath)
  1023. return &output
  1024. }
  1025. // produceBootImageFiles extracts the boot image files from the APEX if available.
  1026. func (module *PrebuiltBootclasspathFragmentModule) produceBootImageFiles(ctx android.ModuleContext, imageConfig *bootImageConfig) bootImageFilesByArch {
  1027. if !shouldCopyBootFilesToPredefinedLocations(ctx, imageConfig) {
  1028. return nil
  1029. }
  1030. di := android.FindDeapexerProviderForModule(ctx)
  1031. if di == nil {
  1032. return nil // An error has been reported by FindDeapexerProviderForModule.
  1033. }
  1034. profile := (android.WritablePath)(nil)
  1035. if imageConfig.profileInstallPathInApex != "" {
  1036. profile = di.PrebuiltExportPath(imageConfig.profileInstallPathInApex)
  1037. }
  1038. // Build the boot image files for the host variants. These are always built from the dex files
  1039. // provided by the contents of this module as prebuilt versions of the host boot image files are
  1040. // not available, i.e. there is no host specific prebuilt apex containing them. This has to be
  1041. // built without a profile as the prebuilt modules do not provide a profile.
  1042. buildBootImageVariantsForBuildOs(ctx, imageConfig, profile)
  1043. if imageConfig.shouldInstallInApex() {
  1044. // If the boot image files for the android variants are in the prebuilt apex, we must use those
  1045. // rather than building new ones because those boot image files are going to be used on device.
  1046. files := bootImageFilesByArch{}
  1047. for _, variant := range imageConfig.apexVariants() {
  1048. arch := variant.target.Arch.ArchType
  1049. for _, toPath := range variant.imagesDeps {
  1050. apexRelativePath := apexRootRelativePathToBootImageFile(arch, toPath.Base())
  1051. // Get the path to the file that the deapexer extracted from the prebuilt apex file.
  1052. fromPath := di.PrebuiltExportPath(apexRelativePath)
  1053. // Return the toPath as the calling code expects the paths in the returned map to be the
  1054. // paths predefined in the bootImageConfig.
  1055. files[arch] = append(files[arch], toPath)
  1056. // Copy the file to the predefined location.
  1057. ctx.Build(pctx, android.BuildParams{
  1058. Rule: android.Cp,
  1059. Input: fromPath,
  1060. Output: toPath,
  1061. })
  1062. }
  1063. }
  1064. return files
  1065. } else {
  1066. if profile == nil {
  1067. ctx.ModuleErrorf("Unable to produce boot image files: neither boot image files nor profiles exists in the prebuilt apex")
  1068. return nil
  1069. }
  1070. // Build boot image files for the android variants from the dex files provided by the contents
  1071. // of this module.
  1072. return buildBootImageVariantsForAndroidOs(ctx, imageConfig, profile)
  1073. }
  1074. }
  1075. var _ commonBootclasspathFragment = (*PrebuiltBootclasspathFragmentModule)(nil)
  1076. // createBootImageTag creates the tag to uniquely identify the boot image file among all of the
  1077. // files that a module requires from the prebuilt .apex file.
  1078. func createBootImageTag(arch android.ArchType, baseName string) string {
  1079. tag := fmt.Sprintf(".bootimage-%s-%s", arch, baseName)
  1080. return tag
  1081. }
  1082. // RequiredFilesFromPrebuiltApex returns the list of all files the prebuilt_bootclasspath_fragment
  1083. // requires from a prebuilt .apex file.
  1084. //
  1085. // If there is no image config associated with this fragment then it returns nil. Otherwise, it
  1086. // returns the files that are listed in the image config.
  1087. func (module *PrebuiltBootclasspathFragmentModule) RequiredFilesFromPrebuiltApex(ctx android.BaseModuleContext) []string {
  1088. imageConfig := module.getImageConfig(ctx)
  1089. if imageConfig != nil {
  1090. files := []string{}
  1091. if imageConfig.profileInstallPathInApex != "" {
  1092. // Add the boot image profile.
  1093. files = append(files, imageConfig.profileInstallPathInApex)
  1094. }
  1095. if imageConfig.shouldInstallInApex() {
  1096. // Add the boot image files, e.g. .art, .oat and .vdex files.
  1097. for _, variant := range imageConfig.apexVariants() {
  1098. arch := variant.target.Arch.ArchType
  1099. for _, path := range variant.imagesDeps.Paths() {
  1100. base := path.Base()
  1101. files = append(files, apexRootRelativePathToBootImageFile(arch, base))
  1102. }
  1103. }
  1104. }
  1105. return files
  1106. }
  1107. return nil
  1108. }
  1109. func apexRootRelativePathToBootImageFile(arch android.ArchType, base string) string {
  1110. return filepath.Join("javalib", arch.String(), base)
  1111. }
  1112. var _ android.RequiredFilesFromPrebuiltApex = (*PrebuiltBootclasspathFragmentModule)(nil)
  1113. func prebuiltBootclasspathFragmentFactory() android.Module {
  1114. m := &PrebuiltBootclasspathFragmentModule{}
  1115. m.AddProperties(&m.properties, &m.prebuiltProperties)
  1116. // This doesn't actually have any prebuilt files of its own so pass a placeholder for the srcs
  1117. // array.
  1118. android.InitPrebuiltModule(m, &[]string{"placeholder"})
  1119. android.InitApexModule(m)
  1120. android.InitSdkAwareModule(m)
  1121. android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibCommon)
  1122. // Initialize the contents property from the image_name.
  1123. android.AddLoadHook(m, func(ctx android.LoadHookContext) {
  1124. bootclasspathFragmentInitContentsFromImage(ctx, &m.BootclasspathFragmentModule)
  1125. })
  1126. return m
  1127. }