dexpreopt_bootjars.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. // Copyright 2019 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package java
  15. import (
  16. "path/filepath"
  17. "sort"
  18. "strings"
  19. "android/soong/android"
  20. "android/soong/dexpreopt"
  21. "github.com/google/blueprint/proptools"
  22. )
  23. // =================================================================================================
  24. // WIP - see http://b/177892522 for details
  25. //
  26. // The build support for boot images is currently being migrated away from singleton to modules so
  27. // the documentation may not be strictly accurate. Rather than update the documentation at every
  28. // step which will create a lot of churn the changes that have been made will be listed here and the
  29. // documentation will be updated once it is closer to the final result.
  30. //
  31. // Changes:
  32. // 1) dex_bootjars is now a singleton module and not a plain singleton.
  33. // 2) Boot images are now represented by the boot_image module type.
  34. // 3) The art boot image is called "art-boot-image", the framework boot image is called
  35. // "framework-boot-image".
  36. // 4) They are defined in art/build/boot/Android.bp and frameworks/base/boot/Android.bp
  37. // respectively.
  38. // 5) Each boot_image retrieves the appropriate boot image configuration from the map returned by
  39. // genBootImageConfigs() using the image_name specified in the boot_image module.
  40. // =================================================================================================
  41. // This comment describes:
  42. // 1. ART boot images in general (their types, structure, file layout, etc.)
  43. // 2. build system support for boot images
  44. //
  45. // 1. ART boot images
  46. // ------------------
  47. //
  48. // A boot image in ART is a set of files that contain AOT-compiled native code and a heap snapshot
  49. // of AOT-initialized classes for the bootclasspath Java libraries. A boot image is compiled from a
  50. // set of DEX jars by the dex2oat compiler. A boot image is used for two purposes: 1) it is
  51. // installed on device and loaded at runtime, and 2) other Java libraries and apps are compiled
  52. // against it (compilation may take place either on host, known as "dexpreopt", or on device, known
  53. // as "dexopt").
  54. //
  55. // A boot image is not a single file, but a collection of interrelated files. Each boot image has a
  56. // number of components that correspond to the Java libraries that constitute it. For each component
  57. // there are multiple files:
  58. // - *.oat or *.odex file with native code (architecture-specific, one per instruction set)
  59. // - *.art file with pre-initialized Java classes (architecture-specific, one per instruction set)
  60. // - *.vdex file with verification metadata for the DEX bytecode (architecture independent)
  61. //
  62. // *.vdex files for the boot images do not contain the DEX bytecode itself, because the
  63. // bootclasspath DEX files are stored on disk in uncompressed and aligned form. Consequently a boot
  64. // image is not self-contained and cannot be used without its DEX files. To simplify the management
  65. // of boot image files, ART uses a certain naming scheme and associates the following metadata with
  66. // each boot image:
  67. // - A stem, which is a symbolic name that is prepended to boot image file names.
  68. // - A location (on-device path to the boot image files).
  69. // - A list of boot image locations (on-device paths to dependency boot images).
  70. // - A set of DEX locations (on-device paths to the DEX files, one location for one DEX file used
  71. // to compile the boot image).
  72. //
  73. // There are two kinds of boot images:
  74. // - primary boot images
  75. // - boot image extensions
  76. //
  77. // 1.1. Primary boot images
  78. // ------------------------
  79. //
  80. // A primary boot image is compiled for a core subset of bootclasspath Java libraries. It does not
  81. // depend on any other images, and other boot images may depend on it.
  82. //
  83. // For example, assuming that the stem is "boot", the location is /apex/com.android.art/javalib/,
  84. // the set of core bootclasspath libraries is A B C, and the boot image is compiled for ARM targets
  85. // (32 and 64 bits), it will have three components with the following files:
  86. // - /apex/com.android.art/javalib/{arm,arm64}/boot.{art,oat,vdex}
  87. // - /apex/com.android.art/javalib/{arm,arm64}/boot-B.{art,oat,vdex}
  88. // - /apex/com.android.art/javalib/{arm,arm64}/boot-C.{art,oat,vdex}
  89. //
  90. // The files of the first component are special: they do not have the component name appended after
  91. // the stem. This naming convention dates back to the times when the boot image was not split into
  92. // components, and there were just boot.oat and boot.art. The decision to split was motivated by
  93. // licensing reasons for one of the bootclasspath libraries.
  94. //
  95. // As of November 2020 the only primary boot image in Android is the image in the ART APEX
  96. // com.android.art. The primary ART boot image contains the Core libraries that are part of the ART
  97. // module. When the ART module gets updated, the primary boot image will be updated with it, and all
  98. // dependent images will get invalidated (the checksum of the primary image stored in dependent
  99. // images will not match), unless they are updated in sync with the ART module.
  100. //
  101. // 1.2. Boot image extensions
  102. // --------------------------
  103. //
  104. // A boot image extension is compiled for a subset of bootclasspath Java libraries (in particular,
  105. // this subset does not include the Core bootclasspath libraries that go into the primary boot
  106. // image). A boot image extension depends on the primary boot image and optionally some other boot
  107. // image extensions. Other images may depend on it. In other words, boot image extensions can form
  108. // acyclic dependency graphs.
  109. //
  110. // The motivation for boot image extensions comes from the Mainline project. Consider a situation
  111. // when the list of bootclasspath libraries is A B C, and both A and B are parts of the Android
  112. // platform, but C is part of an updatable APEX com.android.C. When the APEX is updated, the Java
  113. // code for C might have changed compared to the code that was used to compile the boot image.
  114. // Consequently, the whole boot image is obsolete and invalidated (even though the code for A and B
  115. // that does not depend on C is up to date). To avoid this, the original monolithic boot image is
  116. // split in two parts: the primary boot image that contains A B, and the boot image extension that
  117. // contains C and depends on the primary boot image (extends it).
  118. //
  119. // For example, assuming that the stem is "boot", the location is /system/framework, the set of
  120. // bootclasspath libraries is D E (where D is part of the platform and is located in
  121. // /system/framework, and E is part of a non-updatable APEX com.android.E and is located in
  122. // /apex/com.android.E/javalib), and the boot image is compiled for ARM targets (32 and 64 bits),
  123. // it will have two components with the following files:
  124. // - /system/framework/{arm,arm64}/boot-D.{art,oat,vdex}
  125. // - /system/framework/{arm,arm64}/boot-E.{art,oat,vdex}
  126. //
  127. // As of November 2020 the only boot image extension in Android is the Framework boot image
  128. // extension. It extends the primary ART boot image and contains Framework libraries and other
  129. // bootclasspath libraries from the platform and non-updatable APEXes that are not included in the
  130. // ART image. The Framework boot image extension is updated together with the platform. In the
  131. // future other boot image extensions may be added for some updatable modules.
  132. //
  133. //
  134. // 2. Build system support for boot images
  135. // ---------------------------------------
  136. //
  137. // The primary ART boot image needs to be compiled with one dex2oat invocation that depends on DEX
  138. // jars for the core libraries. Framework boot image extension needs to be compiled with one dex2oat
  139. // invocation that depends on the primary ART boot image and all bootclasspath DEX jars except the
  140. // core libraries as they are already part of the primary ART boot image.
  141. //
  142. // 2.1. Libraries that go in the boot images
  143. // -----------------------------------------
  144. //
  145. // The contents of each boot image are determined by the PRODUCT variables. The primary ART APEX
  146. // boot image contains libraries listed in the ART_APEX_JARS variable in the AOSP makefiles. The
  147. // Framework boot image extension contains libraries specified in the PRODUCT_BOOT_JARS and
  148. // PRODUCT_BOOT_JARS_EXTRA variables. The AOSP makefiles specify some common Framework libraries,
  149. // but more product-specific libraries can be added in the product makefiles.
  150. //
  151. // Each component of the PRODUCT_BOOT_JARS and PRODUCT_BOOT_JARS_EXTRA variables is a
  152. // colon-separated pair <apex>:<library>, where <apex> is the variant name of a non-updatable APEX,
  153. // "platform" if the library is a part of the platform in the system partition, or "system_ext" if
  154. // it's in the system_ext partition.
  155. //
  156. // In these variables APEXes are identified by their "variant names", i.e. the names they get
  157. // mounted as in /apex on device. In Soong modules that is the name set in the "apex_name"
  158. // properties, which default to the "name" values. For example, many APEXes have both
  159. // com.android.xxx and com.google.android.xxx modules in Soong, but take the same place
  160. // /apex/com.android.xxx at runtime. In these cases the variant name is always com.android.xxx,
  161. // regardless which APEX goes into the product. See also android.ApexInfo.ApexVariationName and
  162. // apex.apexBundleProperties.Apex_name.
  163. //
  164. // A related variable PRODUCT_UPDATABLE_BOOT_JARS contains bootclasspath libraries that are in
  165. // APEXes. They are not included in the boot image. The only exception here is core-icu4j.jar that
  166. // has been historically part of the boot image and is now in a non updatable apex; it is treated
  167. // as being part of PRODUCT_BOOT_JARS and is in the boot image.
  168. //
  169. // One exception to the above rules are "coverage" builds (a special build flavor which requires
  170. // setting environment variable EMMA_INSTRUMENT_FRAMEWORK=true). In coverage builds the Java code in
  171. // boot image libraries is instrumented, which means that the instrumentation library (jacocoagent)
  172. // needs to be added to the list of bootclasspath DEX jars.
  173. //
  174. // In general, there is a requirement that the source code for a boot image library must be
  175. // available at build time (e.g. it cannot be a stub that has a separate implementation library).
  176. //
  177. // 2.2. Static configs
  178. // -------------------
  179. //
  180. // Because boot images are used to dexpreopt other Java modules, the paths to boot image files must
  181. // be known by the time dexpreopt build rules for the dependent modules are generated. Boot image
  182. // configs are constructed very early during the build, before build rule generation. The configs
  183. // provide predefined paths to boot image files (these paths depend only on static build
  184. // configuration, such as PRODUCT variables, and use hard-coded directory names).
  185. //
  186. // 2.3. Singleton
  187. // --------------
  188. //
  189. // Build rules for the boot images are generated with a Soong singleton. Because a singleton has no
  190. // dependencies on other modules, it has to find the modules for the DEX jars using VisitAllModules.
  191. // Soong loops through all modules and compares each module against a list of bootclasspath library
  192. // names. Then it generates build rules that copy DEX jars from their intermediate module-specific
  193. // locations to the hard-coded locations predefined in the boot image configs.
  194. //
  195. // It would be possible to use a module with proper dependencies instead, but that would require
  196. // changes in the way Soong generates variables for Make: a singleton can use one MakeVars() method
  197. // that writes variables to out/soong/make_vars-*.mk, which is included early by the main makefile,
  198. // but module(s) would have to use out/soong/Android-*.mk which has a group of LOCAL_* variables
  199. // for each module, and is included later.
  200. //
  201. // 2.4. Install rules
  202. // ------------------
  203. //
  204. // The primary boot image and the Framework extension are installed in different ways. The primary
  205. // boot image is part of the ART APEX: it is copied into the APEX intermediate files, packaged
  206. // together with other APEX contents, extracted and mounted on device. The Framework boot image
  207. // extension is installed by the rules defined in makefiles (make/core/dex_preopt_libart.mk). Soong
  208. // writes out a few DEXPREOPT_IMAGE_* variables for Make; these variables contain boot image names,
  209. // paths and so on.
  210. //
  211. // 2.5. JIT-Zygote configuration
  212. // -----------------------------
  213. //
  214. // One special configuration is JIT-Zygote build, when the primary ART image is used for compiling
  215. // apps instead of the Framework boot image extension (see DEXPREOPT_USE_ART_IMAGE and UseArtImage).
  216. //
  217. var artApexNames = []string{
  218. "com.android.art",
  219. "com.android.art.debug",
  220. "com.android.art.testing",
  221. "com.google.android.art",
  222. "com.google.android.art.debug",
  223. "com.google.android.art.testing",
  224. }
  225. func init() {
  226. RegisterDexpreoptBootJarsComponents(android.InitRegistrationContext)
  227. }
  228. // Target-independent description of a boot image.
  229. type bootImageConfig struct {
  230. // If this image is an extension, the image that it extends.
  231. extends *bootImageConfig
  232. // Image name (used in directory names and ninja rule names).
  233. name string
  234. // Basename of the image: the resulting filenames are <stem>[-<jar>].{art,oat,vdex}.
  235. stem string
  236. // Output directory for the image files.
  237. dir android.OutputPath
  238. // Output directory for the image files with debug symbols.
  239. symbolsDir android.OutputPath
  240. // Subdirectory where the image files are installed.
  241. installDirOnHost string
  242. // Subdirectory where the image files on device are installed.
  243. installDirOnDevice string
  244. // A list of (location, jar) pairs for the Java modules in this image.
  245. modules android.ConfiguredJarList
  246. // File paths to jars.
  247. dexPaths android.WritablePaths // for this image
  248. dexPathsDeps android.WritablePaths // for the dependency images and in this image
  249. // Map from module name (without prebuilt_ prefix) to the predefined build path.
  250. dexPathsByModule map[string]android.WritablePath
  251. // File path to a zip archive with all image files (or nil, if not needed).
  252. zip android.WritablePath
  253. // Rules which should be used in make to install the outputs.
  254. profileInstalls android.RuleBuilderInstalls
  255. // Target-dependent fields.
  256. variants []*bootImageVariant
  257. }
  258. // Target-dependent description of a boot image.
  259. type bootImageVariant struct {
  260. *bootImageConfig
  261. // Target for which the image is generated.
  262. target android.Target
  263. // The "locations" of jars.
  264. dexLocations []string // for this image
  265. dexLocationsDeps []string // for the dependency images and in this image
  266. // Paths to image files.
  267. imagePathOnHost android.OutputPath // first image file path on host
  268. imagePathOnDevice string // first image file path on device
  269. // All the files that constitute this image variant, i.e. .art, .oat and .vdex files.
  270. imagesDeps android.OutputPaths
  271. // The path to the primary image variant's imagePathOnHost field, where primary image variant
  272. // means the image variant that this extends.
  273. //
  274. // This is only set for a variant of an image that extends another image.
  275. primaryImages android.OutputPath
  276. // The paths to the primary image variant's imagesDeps field, where primary image variant
  277. // means the image variant that this extends.
  278. //
  279. // This is only set for a variant of an image that extends another image.
  280. primaryImagesDeps android.Paths
  281. // Rules which should be used in make to install the outputs.
  282. installs android.RuleBuilderInstalls
  283. vdexInstalls android.RuleBuilderInstalls
  284. unstrippedInstalls android.RuleBuilderInstalls
  285. }
  286. // Get target-specific boot image variant for the given boot image config and target.
  287. func (image bootImageConfig) getVariant(target android.Target) *bootImageVariant {
  288. for _, variant := range image.variants {
  289. if variant.target.Os == target.Os && variant.target.Arch.ArchType == target.Arch.ArchType {
  290. return variant
  291. }
  292. }
  293. return nil
  294. }
  295. // Return any (the first) variant which is for the device (as opposed to for the host).
  296. func (image bootImageConfig) getAnyAndroidVariant() *bootImageVariant {
  297. for _, variant := range image.variants {
  298. if variant.target.Os == android.Android {
  299. return variant
  300. }
  301. }
  302. return nil
  303. }
  304. // Return the name of a boot image module given a boot image config and a component (module) index.
  305. // A module name is a combination of the Java library name, and the boot image stem (that is stored
  306. // in the config).
  307. func (image bootImageConfig) moduleName(ctx android.PathContext, idx int) string {
  308. // The first module of the primary boot image is special: its module name has only the stem, but
  309. // not the library name. All other module names are of the form <stem>-<library name>
  310. m := image.modules.Jar(idx)
  311. name := image.stem
  312. if idx != 0 || image.extends != nil {
  313. name += "-" + android.ModuleStem(m)
  314. }
  315. return name
  316. }
  317. // Return the name of the first boot image module, or stem if the list of modules is empty.
  318. func (image bootImageConfig) firstModuleNameOrStem(ctx android.PathContext) string {
  319. if image.modules.Len() > 0 {
  320. return image.moduleName(ctx, 0)
  321. } else {
  322. return image.stem
  323. }
  324. }
  325. // Return filenames for the given boot image component, given the output directory and a list of
  326. // extensions.
  327. func (image bootImageConfig) moduleFiles(ctx android.PathContext, dir android.OutputPath, exts ...string) android.OutputPaths {
  328. ret := make(android.OutputPaths, 0, image.modules.Len()*len(exts))
  329. for i := 0; i < image.modules.Len(); i++ {
  330. name := image.moduleName(ctx, i)
  331. for _, ext := range exts {
  332. ret = append(ret, dir.Join(ctx, name+ext))
  333. }
  334. }
  335. return ret
  336. }
  337. // apexVariants returns a list of all *bootImageVariant that could be included in an apex.
  338. func (image *bootImageConfig) apexVariants() []*bootImageVariant {
  339. variants := []*bootImageVariant{}
  340. for _, variant := range image.variants {
  341. // We also generate boot images for host (for testing), but we don't need those in the apex.
  342. // TODO(b/177892522) - consider changing this to check Os.OsClass = android.Device
  343. if variant.target.Os == android.Android {
  344. variants = append(variants, variant)
  345. }
  346. }
  347. return variants
  348. }
  349. // Return boot image locations (as a list of symbolic paths).
  350. //
  351. // The image "location" is a symbolic path that, with multiarchitecture support, doesn't really
  352. // exist on the device. Typically it is /apex/com.android.art/javalib/boot.art and should be the
  353. // same for all supported architectures on the device. The concrete architecture specific files
  354. // actually end up in architecture-specific sub-directory such as arm, arm64, x86, or x86_64.
  355. //
  356. // For example a physical file /apex/com.android.art/javalib/x86/boot.art has "image location"
  357. // /apex/com.android.art/javalib/boot.art (which is not an actual file).
  358. //
  359. // For a primary boot image the list of locations has a single element.
  360. //
  361. // For a boot image extension the list of locations contains a location for all dependency images
  362. // (including the primary image) and the location of the extension itself. For example, for the
  363. // Framework boot image extension that depends on the primary ART boot image the list contains two
  364. // elements.
  365. //
  366. // The location is passed as an argument to the ART tools like dex2oat instead of the real path.
  367. // ART tools will then reconstruct the architecture-specific real path.
  368. //
  369. func (image *bootImageVariant) imageLocations() (imageLocationsOnHost []string, imageLocationsOnDevice []string) {
  370. if image.extends != nil {
  371. imageLocationsOnHost, imageLocationsOnDevice = image.extends.getVariant(image.target).imageLocations()
  372. }
  373. return append(imageLocationsOnHost, dexpreopt.PathToLocation(image.imagePathOnHost, image.target.Arch.ArchType)),
  374. append(imageLocationsOnDevice, dexpreopt.PathStringToLocation(image.imagePathOnDevice, image.target.Arch.ArchType))
  375. }
  376. func dexpreoptBootJarsFactory() android.SingletonModule {
  377. m := &dexpreoptBootJars{}
  378. android.InitAndroidModule(m)
  379. return m
  380. }
  381. func RegisterDexpreoptBootJarsComponents(ctx android.RegistrationContext) {
  382. ctx.RegisterSingletonModuleType("dex_bootjars", dexpreoptBootJarsFactory)
  383. }
  384. func SkipDexpreoptBootJars(ctx android.PathContext) bool {
  385. return dexpreopt.GetGlobalConfig(ctx).DisablePreoptBootImages
  386. }
  387. // Singleton module for generating boot image build rules.
  388. type dexpreoptBootJars struct {
  389. android.SingletonModuleBase
  390. // Default boot image config (currently always the Framework boot image extension). It should be
  391. // noted that JIT-Zygote builds use ART APEX image instead of the Framework boot image extension,
  392. // but the switch is handled not here, but in the makefiles (triggered with
  393. // DEXPREOPT_USE_ART_IMAGE=true).
  394. defaultBootImage *bootImageConfig
  395. // Other boot image configs (currently the list contains only the primary ART APEX image. It
  396. // used to contain an experimental JIT-Zygote image (now replaced with the ART APEX image). In
  397. // the future other boot image extensions may be added.
  398. otherImages []*bootImageConfig
  399. // Build path to a config file that Soong writes for Make (to be used in makefiles that install
  400. // the default boot image).
  401. dexpreoptConfigForMake android.WritablePath
  402. }
  403. // Provide paths to boot images for use by modules that depend upon them.
  404. //
  405. // The build rules are created in GenerateSingletonBuildActions().
  406. func (d *dexpreoptBootJars) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  407. // Placeholder for now.
  408. }
  409. // Generate build rules for boot images.
  410. func (d *dexpreoptBootJars) GenerateSingletonBuildActions(ctx android.SingletonContext) {
  411. if SkipDexpreoptBootJars(ctx) {
  412. return
  413. }
  414. if dexpreopt.GetCachedGlobalSoongConfig(ctx) == nil {
  415. // No module has enabled dexpreopting, so we assume there will be no boot image to make.
  416. return
  417. }
  418. d.dexpreoptConfigForMake = android.PathForOutput(ctx, ctx.Config().DeviceName(), "dexpreopt.config")
  419. writeGlobalConfigForMake(ctx, d.dexpreoptConfigForMake)
  420. global := dexpreopt.GetGlobalConfig(ctx)
  421. if !shouldBuildBootImages(ctx.Config(), global) {
  422. return
  423. }
  424. defaultImageConfig := defaultBootImageConfig(ctx)
  425. d.defaultBootImage = defaultImageConfig
  426. artBootImageConfig := artBootImageConfig(ctx)
  427. d.otherImages = []*bootImageConfig{artBootImageConfig}
  428. }
  429. // shouldBuildBootImages determines whether boot images should be built.
  430. func shouldBuildBootImages(config android.Config, global *dexpreopt.GlobalConfig) bool {
  431. // Skip recompiling the boot image for the second sanitization phase. We'll get separate paths
  432. // and invalidate first-stage artifacts which are crucial to SANITIZE_LITE builds.
  433. // Note: this is technically incorrect. Compiled code contains stack checks which may depend
  434. // on ASAN settings.
  435. if len(config.SanitizeDevice()) == 1 && config.SanitizeDevice()[0] == "address" && global.SanitizeLite {
  436. return false
  437. }
  438. return true
  439. }
  440. // copyBootJarsToPredefinedLocations generates commands that will copy boot jars to predefined
  441. // paths in the global config.
  442. func copyBootJarsToPredefinedLocations(ctx android.ModuleContext, srcBootDexJarsByModule bootDexJarByModule, dstBootJarsByModule map[string]android.WritablePath) {
  443. // Create the super set of module names.
  444. names := []string{}
  445. names = append(names, android.SortedStringKeys(srcBootDexJarsByModule)...)
  446. names = append(names, android.SortedStringKeys(dstBootJarsByModule)...)
  447. names = android.SortedUniqueStrings(names)
  448. for _, name := range names {
  449. src := srcBootDexJarsByModule[name]
  450. dst := dstBootJarsByModule[name]
  451. if src == nil {
  452. ctx.ModuleErrorf("module %s does not provide a dex boot jar", name)
  453. } else if dst == nil {
  454. ctx.ModuleErrorf("module %s is not part of the boot configuration", name)
  455. } else {
  456. ctx.Build(pctx, android.BuildParams{
  457. Rule: android.Cp,
  458. Input: src,
  459. Output: dst,
  460. })
  461. }
  462. }
  463. }
  464. // buildBootImageVariantsForAndroidOs generates rules to build the boot image variants for the
  465. // android.Android OsType and returns a map from the architectures to the paths of the generated
  466. // boot image files.
  467. //
  468. // The paths are returned because they are needed elsewhere in Soong, e.g. for populating an APEX.
  469. func buildBootImageVariantsForAndroidOs(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath) bootImageFilesByArch {
  470. return buildBootImageForOsType(ctx, image, profile, android.Android)
  471. }
  472. // buildBootImageVariantsForBuildOs generates rules to build the boot image variants for the
  473. // config.BuildOS OsType, i.e. the type of OS on which the build is being running.
  474. //
  475. // The files need to be generated into their predefined location because they are used from there
  476. // both within Soong and outside, e.g. for ART based host side testing and also for use by some
  477. // cloud based tools. However, they are not needed by callers of this function and so the paths do
  478. // not need to be returned from this func, unlike the buildBootImageVariantsForAndroidOs func.
  479. func buildBootImageVariantsForBuildOs(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath) {
  480. buildBootImageForOsType(ctx, image, profile, ctx.Config().BuildOS)
  481. }
  482. // buildBootImageForOsType takes a bootImageConfig, a profile file and an android.OsType
  483. // boot image files are required for and it creates rules to build the boot image
  484. // files for all the required architectures for them.
  485. //
  486. // It returns a map from android.ArchType to the predefined paths of the boot image files.
  487. func buildBootImageForOsType(ctx android.ModuleContext, image *bootImageConfig, profile android.WritablePath, requiredOsType android.OsType) bootImageFilesByArch {
  488. filesByArch := bootImageFilesByArch{}
  489. for _, variant := range image.variants {
  490. if variant.target.Os == requiredOsType {
  491. buildBootImageVariant(ctx, variant, profile)
  492. filesByArch[variant.target.Arch.ArchType] = variant.imagesDeps.Paths()
  493. }
  494. }
  495. return filesByArch
  496. }
  497. // buildBootImageZipInPredefinedLocation generates a zip file containing all the boot image files.
  498. //
  499. // The supplied filesByArch is nil when the boot image files have not been generated. Otherwise, it
  500. // is a map from android.ArchType to the predefined locations.
  501. func buildBootImageZipInPredefinedLocation(ctx android.ModuleContext, image *bootImageConfig, filesByArch bootImageFilesByArch) {
  502. if filesByArch == nil {
  503. return
  504. }
  505. // Compute the list of files from all the architectures.
  506. zipFiles := android.Paths{}
  507. for _, archType := range android.ArchTypeList() {
  508. zipFiles = append(zipFiles, filesByArch[archType]...)
  509. }
  510. rule := android.NewRuleBuilder(pctx, ctx)
  511. rule.Command().
  512. BuiltTool("soong_zip").
  513. FlagWithOutput("-o ", image.zip).
  514. FlagWithArg("-C ", image.dir.Join(ctx, android.Android.String()).String()).
  515. FlagWithInputList("-f ", zipFiles, " -f ")
  516. rule.Build("zip_"+image.name, "zip "+image.name+" image")
  517. }
  518. // Generate boot image build rules for a specific target.
  519. func buildBootImageVariant(ctx android.ModuleContext, image *bootImageVariant, profile android.Path) {
  520. globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
  521. global := dexpreopt.GetGlobalConfig(ctx)
  522. arch := image.target.Arch.ArchType
  523. os := image.target.Os.String() // We need to distinguish host-x86 and device-x86.
  524. symbolsDir := image.symbolsDir.Join(ctx, os, image.installDirOnHost, arch.String())
  525. symbolsFile := symbolsDir.Join(ctx, image.stem+".oat")
  526. outputDir := image.dir.Join(ctx, os, image.installDirOnHost, arch.String())
  527. outputPath := outputDir.Join(ctx, image.stem+".oat")
  528. oatLocation := dexpreopt.PathToLocation(outputPath, arch)
  529. imagePath := outputPath.ReplaceExtension(ctx, "art")
  530. rule := android.NewRuleBuilder(pctx, ctx)
  531. rule.Command().Text("mkdir").Flag("-p").Flag(symbolsDir.String())
  532. rule.Command().Text("rm").Flag("-f").
  533. Flag(symbolsDir.Join(ctx, "*.art").String()).
  534. Flag(symbolsDir.Join(ctx, "*.oat").String()).
  535. Flag(symbolsDir.Join(ctx, "*.invocation").String())
  536. rule.Command().Text("rm").Flag("-f").
  537. Flag(outputDir.Join(ctx, "*.art").String()).
  538. Flag(outputDir.Join(ctx, "*.oat").String()).
  539. Flag(outputDir.Join(ctx, "*.invocation").String())
  540. cmd := rule.Command()
  541. extraFlags := ctx.Config().Getenv("ART_BOOT_IMAGE_EXTRA_ARGS")
  542. if extraFlags == "" {
  543. // Use ANDROID_LOG_TAGS to suppress most logging by default...
  544. cmd.Text(`ANDROID_LOG_TAGS="*:e"`)
  545. } else {
  546. // ...unless the boot image is generated specifically for testing, then allow all logging.
  547. cmd.Text(`ANDROID_LOG_TAGS="*:v"`)
  548. }
  549. invocationPath := outputPath.ReplaceExtension(ctx, "invocation")
  550. cmd.Tool(globalSoong.Dex2oat).
  551. Flag("--avoid-storing-invocation").
  552. FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
  553. Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatImageXms).
  554. Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatImageXmx)
  555. if profile != nil {
  556. cmd.FlagWithArg("--compiler-filter=", "speed-profile")
  557. cmd.FlagWithInput("--profile-file=", profile)
  558. }
  559. dirtyImageFile := "frameworks/base/config/dirty-image-objects"
  560. dirtyImagePath := android.ExistentPathForSource(ctx, dirtyImageFile)
  561. if dirtyImagePath.Valid() {
  562. cmd.FlagWithInput("--dirty-image-objects=", dirtyImagePath.Path())
  563. }
  564. if image.extends != nil {
  565. // It is a boot image extension, so it needs the boot image it depends on (in this case the
  566. // primary ART APEX image).
  567. artImage := image.primaryImages
  568. cmd.
  569. Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", image.dexPathsDeps.Paths(), ":").
  570. Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", image.dexLocationsDeps, ":").
  571. // Add the path to the first file in the boot image with the arch specific directory removed,
  572. // dex2oat will reconstruct the path to the actual file when it needs it. As the actual path
  573. // to the file cannot be passed to the command make sure to add the actual path as an Implicit
  574. // dependency to ensure that it is built before the command runs.
  575. FlagWithArg("--boot-image=", dexpreopt.PathToLocation(artImage, arch)).Implicit(artImage).
  576. // Similarly, the dex2oat tool will automatically find the paths to other files in the base
  577. // boot image so make sure to add them as implicit dependencies to ensure that they are built
  578. // before this command is run.
  579. Implicits(image.primaryImagesDeps)
  580. } else {
  581. // It is a primary image, so it needs a base address.
  582. cmd.FlagWithArg("--base=", ctx.Config().LibartImgDeviceBaseAddress())
  583. }
  584. cmd.
  585. FlagForEachInput("--dex-file=", image.dexPaths.Paths()).
  586. FlagForEachArg("--dex-location=", image.dexLocations).
  587. Flag("--generate-debug-info").
  588. Flag("--generate-build-id").
  589. Flag("--image-format=lz4hc").
  590. FlagWithArg("--oat-symbols=", symbolsFile.String()).
  591. Flag("--strip").
  592. FlagWithArg("--oat-file=", outputPath.String()).
  593. FlagWithArg("--oat-location=", oatLocation).
  594. FlagWithArg("--image=", imagePath.String()).
  595. FlagWithArg("--instruction-set=", arch.String()).
  596. FlagWithArg("--android-root=", global.EmptyDirectory).
  597. FlagWithArg("--no-inline-from=", "core-oj.jar").
  598. Flag("--force-determinism").
  599. Flag("--abort-on-hard-verifier-error")
  600. // Use the default variant/features for host builds.
  601. // The map below contains only device CPU info (which might be x86 on some devices).
  602. if image.target.Os == android.Android {
  603. cmd.FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch])
  604. cmd.FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch])
  605. }
  606. if global.BootFlags != "" {
  607. cmd.Flag(global.BootFlags)
  608. }
  609. if extraFlags != "" {
  610. cmd.Flag(extraFlags)
  611. }
  612. cmd.Textf(`|| ( echo %s ; false )`, proptools.ShellEscape(failureMessage))
  613. installDir := filepath.Join("/", image.installDirOnHost, arch.String())
  614. var vdexInstalls android.RuleBuilderInstalls
  615. var unstrippedInstalls android.RuleBuilderInstalls
  616. for _, artOrOat := range image.moduleFiles(ctx, outputDir, ".art", ".oat") {
  617. cmd.ImplicitOutput(artOrOat)
  618. // Install the .oat and .art files
  619. rule.Install(artOrOat, filepath.Join(installDir, artOrOat.Base()))
  620. }
  621. for _, vdex := range image.moduleFiles(ctx, outputDir, ".vdex") {
  622. cmd.ImplicitOutput(vdex)
  623. // Note that the vdex files are identical between architectures.
  624. // Make rules will create symlinks to share them between architectures.
  625. vdexInstalls = append(vdexInstalls,
  626. android.RuleBuilderInstall{vdex, filepath.Join(installDir, vdex.Base())})
  627. }
  628. for _, unstrippedOat := range image.moduleFiles(ctx, symbolsDir, ".oat") {
  629. cmd.ImplicitOutput(unstrippedOat)
  630. // Install the unstripped oat files. The Make rules will put these in $(TARGET_OUT_UNSTRIPPED)
  631. unstrippedInstalls = append(unstrippedInstalls,
  632. android.RuleBuilderInstall{unstrippedOat, filepath.Join(installDir, unstrippedOat.Base())})
  633. }
  634. rule.Build(image.name+"JarsDexpreopt_"+image.target.String(), "dexpreopt "+image.name+" jars "+arch.String())
  635. // save output and installed files for makevars
  636. image.installs = rule.Installs()
  637. image.vdexInstalls = vdexInstalls
  638. image.unstrippedInstalls = unstrippedInstalls
  639. }
  640. const failureMessage = `ERROR: Dex2oat failed to compile a boot image.
  641. It is likely that the boot classpath is inconsistent.
  642. Rebuild with ART_BOOT_IMAGE_EXTRA_ARGS="--runtime-arg -verbose:verifier" to see verification errors.`
  643. func bootImageProfileRule(ctx android.ModuleContext, image *bootImageConfig) android.WritablePath {
  644. globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
  645. global := dexpreopt.GetGlobalConfig(ctx)
  646. if global.DisableGenerateProfile {
  647. return nil
  648. }
  649. defaultProfile := "frameworks/base/config/boot-image-profile.txt"
  650. rule := android.NewRuleBuilder(pctx, ctx)
  651. var bootImageProfile android.Path
  652. if len(global.BootImageProfiles) > 1 {
  653. combinedBootImageProfile := image.dir.Join(ctx, "boot-image-profile.txt")
  654. rule.Command().Text("cat").Inputs(global.BootImageProfiles).Text(">").Output(combinedBootImageProfile)
  655. bootImageProfile = combinedBootImageProfile
  656. } else if len(global.BootImageProfiles) == 1 {
  657. bootImageProfile = global.BootImageProfiles[0]
  658. } else if path := android.ExistentPathForSource(ctx, defaultProfile); path.Valid() {
  659. bootImageProfile = path.Path()
  660. } else {
  661. // No profile (not even a default one, which is the case on some branches
  662. // like master-art-host that don't have frameworks/base).
  663. // Return nil and continue without profile.
  664. return nil
  665. }
  666. profile := image.dir.Join(ctx, "boot.prof")
  667. rule.Command().
  668. Text(`ANDROID_LOG_TAGS="*:e"`).
  669. Tool(globalSoong.Profman).
  670. Flag("--output-profile-type=boot").
  671. FlagWithInput("--create-profile-from=", bootImageProfile).
  672. FlagForEachInput("--apk=", image.dexPathsDeps.Paths()).
  673. FlagForEachArg("--dex-location=", image.getAnyAndroidVariant().dexLocationsDeps).
  674. FlagWithOutput("--reference-profile-file=", profile)
  675. rule.Install(profile, "/system/etc/boot-image.prof")
  676. rule.Build("bootJarsProfile", "profile boot jars")
  677. image.profileInstalls = append(image.profileInstalls, rule.Installs()...)
  678. return profile
  679. }
  680. // bootFrameworkProfileRule generates the rule to create the boot framework profile and
  681. // returns a path to the generated file.
  682. func bootFrameworkProfileRule(ctx android.ModuleContext, image *bootImageConfig) android.WritablePath {
  683. globalSoong := dexpreopt.GetGlobalSoongConfig(ctx)
  684. global := dexpreopt.GetGlobalConfig(ctx)
  685. if global.DisableGenerateProfile || ctx.Config().UnbundledBuild() {
  686. return nil
  687. }
  688. defaultProfile := "frameworks/base/config/boot-profile.txt"
  689. bootFrameworkProfile := android.PathForSource(ctx, defaultProfile)
  690. profile := image.dir.Join(ctx, "boot.bprof")
  691. rule := android.NewRuleBuilder(pctx, ctx)
  692. rule.Command().
  693. Text(`ANDROID_LOG_TAGS="*:e"`).
  694. Tool(globalSoong.Profman).
  695. Flag("--output-profile-type=bprof").
  696. FlagWithInput("--create-profile-from=", bootFrameworkProfile).
  697. FlagForEachInput("--apk=", image.dexPathsDeps.Paths()).
  698. FlagForEachArg("--dex-location=", image.getAnyAndroidVariant().dexLocationsDeps).
  699. FlagWithOutput("--reference-profile-file=", profile)
  700. rule.Install(profile, "/system/etc/boot-image.bprof")
  701. rule.Build("bootFrameworkProfile", "profile boot framework jars")
  702. image.profileInstalls = append(image.profileInstalls, rule.Installs()...)
  703. return profile
  704. }
  705. // generateUpdatableBcpPackagesRule generates the rule to create the updatable-bcp-packages.txt file
  706. // and returns a path to the generated file.
  707. func generateUpdatableBcpPackagesRule(ctx android.ModuleContext, image *bootImageConfig, updatableModules []android.Module) android.WritablePath {
  708. // Collect `permitted_packages` for updatable boot jars.
  709. var updatablePackages []string
  710. for _, module := range updatableModules {
  711. if j, ok := module.(PermittedPackagesForUpdatableBootJars); ok {
  712. pp := j.PermittedPackagesForUpdatableBootJars()
  713. if len(pp) > 0 {
  714. updatablePackages = append(updatablePackages, pp...)
  715. } else {
  716. ctx.OtherModuleErrorf(module, "Missing permitted_packages")
  717. }
  718. }
  719. }
  720. // Sort updatable packages to ensure deterministic ordering.
  721. sort.Strings(updatablePackages)
  722. updatableBcpPackagesName := "updatable-bcp-packages.txt"
  723. updatableBcpPackages := image.dir.Join(ctx, updatableBcpPackagesName)
  724. // WriteFileRule automatically adds the last end-of-line.
  725. android.WriteFileRule(ctx, updatableBcpPackages, strings.Join(updatablePackages, "\n"))
  726. rule := android.NewRuleBuilder(pctx, ctx)
  727. rule.Install(updatableBcpPackages, "/system/etc/"+updatableBcpPackagesName)
  728. // TODO: Rename `profileInstalls` to `extraInstalls`?
  729. // Maybe even move the field out of the bootImageConfig into some higher level type?
  730. image.profileInstalls = append(image.profileInstalls, rule.Installs()...)
  731. return updatableBcpPackages
  732. }
  733. func dumpOatRules(ctx android.ModuleContext, image *bootImageConfig) {
  734. var allPhonies android.Paths
  735. for _, image := range image.variants {
  736. arch := image.target.Arch.ArchType
  737. suffix := arch.String()
  738. // Host and target might both use x86 arch. We need to ensure the names are unique.
  739. if image.target.Os.Class == android.Host {
  740. suffix = "host-" + suffix
  741. }
  742. // Create a rule to call oatdump.
  743. output := android.PathForOutput(ctx, "boot."+suffix+".oatdump.txt")
  744. rule := android.NewRuleBuilder(pctx, ctx)
  745. imageLocationsOnHost, _ := image.imageLocations()
  746. rule.Command().
  747. BuiltTool("oatdump").
  748. FlagWithInputList("--runtime-arg -Xbootclasspath:", image.dexPathsDeps.Paths(), ":").
  749. FlagWithList("--runtime-arg -Xbootclasspath-locations:", image.dexLocationsDeps, ":").
  750. FlagWithArg("--image=", strings.Join(imageLocationsOnHost, ":")).Implicits(image.imagesDeps.Paths()).
  751. FlagWithOutput("--output=", output).
  752. FlagWithArg("--instruction-set=", arch.String())
  753. rule.Build("dump-oat-boot-"+suffix, "dump oat boot "+arch.String())
  754. // Create a phony rule that depends on the output file and prints the path.
  755. phony := android.PathForPhony(ctx, "dump-oat-boot-"+suffix)
  756. rule = android.NewRuleBuilder(pctx, ctx)
  757. rule.Command().
  758. Implicit(output).
  759. ImplicitOutput(phony).
  760. Text("echo").FlagWithArg("Output in ", output.String())
  761. rule.Build("phony-dump-oat-boot-"+suffix, "dump oat boot "+arch.String())
  762. allPhonies = append(allPhonies, phony)
  763. }
  764. phony := android.PathForPhony(ctx, "dump-oat-boot")
  765. ctx.Build(pctx, android.BuildParams{
  766. Rule: android.Phony,
  767. Output: phony,
  768. Inputs: allPhonies,
  769. Description: "dump-oat-boot",
  770. })
  771. }
  772. func writeGlobalConfigForMake(ctx android.SingletonContext, path android.WritablePath) {
  773. data := dexpreopt.GetGlobalConfigRawData(ctx)
  774. android.WriteFileRule(ctx, path, string(data))
  775. }
  776. // Define Make variables for boot image names, paths, etc. These variables are used in makefiles
  777. // (make/core/dex_preopt_libart.mk) to generate install rules that copy boot image files to the
  778. // correct output directories.
  779. func (d *dexpreoptBootJars) MakeVars(ctx android.MakeVarsContext) {
  780. if d.dexpreoptConfigForMake != nil {
  781. ctx.Strict("DEX_PREOPT_CONFIG_FOR_MAKE", d.dexpreoptConfigForMake.String())
  782. ctx.Strict("DEX_PREOPT_SOONG_CONFIG_FOR_MAKE", android.PathForOutput(ctx, "dexpreopt_soong.config").String())
  783. }
  784. image := d.defaultBootImage
  785. if image != nil {
  786. ctx.Strict("DEXPREOPT_IMAGE_PROFILE_BUILT_INSTALLED", image.profileInstalls.String())
  787. global := dexpreopt.GetGlobalConfig(ctx)
  788. dexPaths, dexLocations := bcpForDexpreopt(ctx, global.PreoptWithUpdatableBcp)
  789. ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_FILES", strings.Join(dexPaths.Strings(), " "))
  790. ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS", strings.Join(dexLocations, " "))
  791. var imageNames []string
  792. // TODO: the primary ART boot image should not be exposed to Make, as it is installed in a
  793. // different way as a part of the ART APEX. However, there is a special JIT-Zygote build
  794. // configuration which uses the primary ART image instead of the Framework boot image
  795. // extension, and it relies on the ART image being exposed to Make. To fix this, it is
  796. // necessary to rework the logic in makefiles.
  797. for _, current := range append(d.otherImages, image) {
  798. imageNames = append(imageNames, current.name)
  799. for _, variant := range current.variants {
  800. suffix := ""
  801. if variant.target.Os.Class == android.Host {
  802. suffix = "_host"
  803. }
  804. sfx := variant.name + suffix + "_" + variant.target.Arch.ArchType.String()
  805. ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+sfx, variant.vdexInstalls.String())
  806. ctx.Strict("DEXPREOPT_IMAGE_"+sfx, variant.imagePathOnHost.String())
  807. ctx.Strict("DEXPREOPT_IMAGE_DEPS_"+sfx, strings.Join(variant.imagesDeps.Strings(), " "))
  808. ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+sfx, variant.installs.String())
  809. ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+sfx, variant.unstrippedInstalls.String())
  810. }
  811. imageLocationsOnHost, imageLocationsOnDevice := current.getAnyAndroidVariant().imageLocations()
  812. ctx.Strict("DEXPREOPT_IMAGE_LOCATIONS_ON_HOST"+current.name, strings.Join(imageLocationsOnHost, ":"))
  813. ctx.Strict("DEXPREOPT_IMAGE_LOCATIONS_ON_DEVICE"+current.name, strings.Join(imageLocationsOnDevice, ":"))
  814. ctx.Strict("DEXPREOPT_IMAGE_ZIP_"+current.name, current.zip.String())
  815. }
  816. ctx.Strict("DEXPREOPT_IMAGE_NAMES", strings.Join(imageNames, " "))
  817. }
  818. }