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