1// Copyright 2018 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15// The dexpreopt package converts a global dexpreopt config and a module dexpreopt config into rules to perform 16// dexpreopting. 17// 18// It is used in two places; in the dexpeopt_gen binary for modules defined in Make, and directly linked into Soong. 19// 20// For Make modules it is built into the dexpreopt_gen binary, which is executed as a Make rule using global config and 21// module config specified in JSON files. The binary writes out two shell scripts, only updating them if they have 22// changed. One script takes an APK or JAR as an input and produces a zip file containing any outputs of preopting, 23// in the location they should be on the device. The Make build rules will unzip the zip file into $(PRODUCT_OUT) when 24// installing the APK, which will install the preopt outputs into $(PRODUCT_OUT)/system or $(PRODUCT_OUT)/system_other 25// as necessary. The zip file may be empty if preopting was disabled for any reason. 26// 27// The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts 28// but only require re-executing preopting if the script has changed. 29// 30// For Soong modules this package is linked directly into Soong and run from the java package. It generates the same 31// commands as for make, using athe same global config JSON file used by make, but using a module config structure 32// provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file, 33// with no extra shell scripts involved. 34package dexpreopt 35 36import ( 37 "fmt" 38 "path/filepath" 39 "runtime" 40 "sort" 41 "strings" 42 43 "android/soong/android" 44 45 "github.com/google/blueprint/pathtools" 46) 47 48const SystemPartition = "/system/" 49const SystemOtherPartition = "/system_other/" 50 51var DexpreoptRunningInSoong = false 52 53// GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a 54// ModuleConfig. The produced files and their install locations will be available through rule.Installs(). 55func GenerateDexpreoptRule(ctx android.PathContext, globalSoong *GlobalSoongConfig, 56 global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) { 57 58 defer func() { 59 if r := recover(); r != nil { 60 if _, ok := r.(runtime.Error); ok { 61 panic(r) 62 } else if e, ok := r.(error); ok { 63 err = e 64 rule = nil 65 } else { 66 panic(r) 67 } 68 } 69 }() 70 71 rule = android.NewRuleBuilder() 72 73 generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile 74 generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile 75 76 var profile android.WritablePath 77 if generateProfile { 78 profile = profileCommand(ctx, globalSoong, global, module, rule) 79 } 80 if generateBootProfile { 81 bootProfileCommand(ctx, globalSoong, global, module, rule) 82 } 83 84 if !dexpreoptDisabled(ctx, global, module) { 85 // Don't preopt individual boot jars, they will be preopted together. 86 if !contains(android.GetJarsFromApexJarPairs(ctx, global.BootJars), module.Name) { 87 appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) && 88 !module.NoCreateAppImage 89 90 generateDM := shouldGenerateDM(module, global) 91 92 for archIdx, _ := range module.Archs { 93 dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM) 94 } 95 } 96 } 97 98 return rule, nil 99} 100 101func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool { 102 if contains(global.DisablePreoptModules, module.Name) { 103 return true 104 } 105 106 // Don't preopt system server jars that are updatable. 107 for _, p := range global.UpdatableSystemServerJars { 108 if _, jar := android.SplitApexJarPair(ctx, p); jar == module.Name { 109 return true 110 } 111 } 112 113 // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip 114 // Also preopt system server jars since selinux prevents system server from loading anything from 115 // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage 116 // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options. 117 if global.OnlyPreoptBootImageAndSystemServer && !contains(android.GetJarsFromApexJarPairs(ctx, global.BootJars), module.Name) && 118 !contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk { 119 return true 120 } 121 122 return false 123} 124 125func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig, 126 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath { 127 128 profilePath := module.BuildPath.InSameDir(ctx, "profile.prof") 129 profileInstalledPath := module.DexLocation + ".prof" 130 131 if !module.ProfileIsTextListing { 132 rule.Command().FlagWithOutput("touch ", profilePath) 133 } 134 135 cmd := rule.Command(). 136 Text(`ANDROID_LOG_TAGS="*:e"`). 137 Tool(globalSoong.Profman) 138 139 if module.ProfileIsTextListing { 140 // The profile is a test listing of classes (used for framework jars). 141 // We need to generate the actual binary profile before being able to compile. 142 cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path()) 143 } else { 144 // The profile is binary profile (used for apps). Run it through profman to 145 // ensure the profile keys match the apk. 146 cmd. 147 Flag("--copy-and-update-profile-key"). 148 FlagWithInput("--profile-file=", module.ProfileClassListing.Path()) 149 } 150 151 cmd. 152 FlagWithInput("--apk=", module.DexPath). 153 Flag("--dex-location="+module.DexLocation). 154 FlagWithOutput("--reference-profile-file=", profilePath) 155 156 if !module.ProfileIsTextListing { 157 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath)) 158 } 159 rule.Install(profilePath, profileInstalledPath) 160 161 return profilePath 162} 163 164func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig, 165 module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath { 166 167 profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof") 168 profileInstalledPath := module.DexLocation + ".bprof" 169 170 if !module.ProfileIsTextListing { 171 rule.Command().FlagWithOutput("touch ", profilePath) 172 } 173 174 cmd := rule.Command(). 175 Text(`ANDROID_LOG_TAGS="*:e"`). 176 Tool(globalSoong.Profman) 177 178 // The profile is a test listing of methods. 179 // We need to generate the actual binary profile. 180 cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path()) 181 182 cmd. 183 Flag("--generate-boot-profile"). 184 FlagWithInput("--apk=", module.DexPath). 185 Flag("--dex-location="+module.DexLocation). 186 FlagWithOutput("--reference-profile-file=", profilePath) 187 188 if !module.ProfileIsTextListing { 189 cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath)) 190 } 191 rule.Install(profilePath, profileInstalledPath) 192 193 return profilePath 194} 195 196type classLoaderContext struct { 197 // The class loader context using paths in the build. 198 Host android.Paths 199 200 // The class loader context using paths as they will be on the device. 201 Target []string 202} 203 204// A map of class loader contexts for each SDK version. 205// A map entry for "any" version contains libraries that are unconditionally added to class loader 206// context. Map entries for existing versions contains libraries that were in the default classpath 207// until that API version, and should be added to class loader context if and only if the 208// targetSdkVersion in the manifest or APK is less than that API version. 209type classLoaderContextMap map[int]*classLoaderContext 210 211const anySdkVersion int = 9999 // should go last in class loader context 212 213func (m classLoaderContextMap) getSortedKeys() []int { 214 keys := make([]int, 0, len(m)) 215 for k := range m { 216 keys = append(keys, k) 217 } 218 sort.Ints(keys) 219 return keys 220} 221 222func (m classLoaderContextMap) getValue(sdkVer int) *classLoaderContext { 223 if _, ok := m[sdkVer]; !ok { 224 m[sdkVer] = &classLoaderContext{} 225 } 226 return m[sdkVer] 227} 228 229func (m classLoaderContextMap) addLibs(sdkVer int, module *ModuleConfig, libs ...string) { 230 clc := m.getValue(sdkVer) 231 for _, lib := range libs { 232 p := pathForLibrary(module, lib) 233 clc.Host = append(clc.Host, p.Host) 234 clc.Target = append(clc.Target, p.Device) 235 } 236} 237 238func (m classLoaderContextMap) addSystemServerLibs(sdkVer int, ctx android.PathContext, module *ModuleConfig, libs ...string) { 239 clc := m.getValue(sdkVer) 240 for _, lib := range libs { 241 clc.Host = append(clc.Host, SystemServerDexJarHostPath(ctx, lib)) 242 clc.Target = append(clc.Target, filepath.Join("/system/framework", lib+".jar")) 243 } 244} 245 246func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig, 247 module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath, 248 appImage bool, generateDM bool) { 249 250 arch := module.Archs[archIdx] 251 252 // HACK: make soname in Soong-generated .odex files match Make. 253 base := filepath.Base(module.DexLocation) 254 if filepath.Ext(base) == ".jar" { 255 base = "javalib.jar" 256 } else if filepath.Ext(base) == ".apk" { 257 base = "package.apk" 258 } 259 260 toOdexPath := func(path string) string { 261 return filepath.Join( 262 filepath.Dir(path), 263 "oat", 264 arch.String(), 265 pathtools.ReplaceExtension(filepath.Base(path), "odex")) 266 } 267 268 odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex")) 269 odexInstallPath := toOdexPath(module.DexLocation) 270 if odexOnSystemOther(module, global) { 271 odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath) 272 } 273 274 vdexPath := odexPath.ReplaceExtension(ctx, "vdex") 275 vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex") 276 277 invocationPath := odexPath.ReplaceExtension(ctx, "invocation") 278 279 classLoaderContexts := make(classLoaderContextMap) 280 systemServerJars := NonUpdatableSystemServerJars(ctx, global) 281 282 rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String())) 283 rule.Command().FlagWithOutput("rm -f ", odexPath) 284 285 if jarIndex := android.IndexList(module.Name, systemServerJars); jarIndex >= 0 { 286 // System server jars should be dexpreopted together: class loader context of each jar 287 // should include all preceding jars on the system server classpath. 288 classLoaderContexts.addSystemServerLibs(anySdkVersion, ctx, module, systemServerJars[:jarIndex]...) 289 290 // Copy the system server jar to a predefined location where dex2oat will find it. 291 dexPathHost := SystemServerDexJarHostPath(ctx, module.Name) 292 rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String())) 293 rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost) 294 295 checkSystemServerOrder(ctx, jarIndex) 296 297 clc := classLoaderContexts[anySdkVersion] 298 rule.Command(). 299 Text("class_loader_context_arg=--class-loader-context=PCL[" + strings.Join(clc.Host.Strings(), ":") + "]"). 300 Implicits(clc.Host). 301 Text("stored_class_loader_context_arg=--stored-class-loader-context=PCL[" + strings.Join(clc.Target, ":") + "]") 302 } else if module.EnforceUsesLibraries { 303 // Unconditional class loader context. 304 usesLibs := append(copyOf(module.UsesLibraries), module.OptionalUsesLibraries...) 305 classLoaderContexts.addLibs(anySdkVersion, module, usesLibs...) 306 307 // Conditional class loader context for API version < 28. 308 const httpLegacy = "org.apache.http.legacy" 309 if !contains(usesLibs, httpLegacy) { 310 classLoaderContexts.addLibs(28, module, httpLegacy) 311 } 312 313 // Conditional class loader context for API version < 29. 314 usesLibs29 := []string{ 315 "android.hidl.base-V1.0-java", 316 "android.hidl.manager-V1.0-java", 317 } 318 classLoaderContexts.addLibs(29, module, usesLibs29...) 319 320 // Conditional class loader context for API version < 30. 321 const testBase = "android.test.base" 322 if !contains(usesLibs, testBase) { 323 classLoaderContexts.addLibs(30, module, testBase) 324 } 325 326 // Generate command that saves target SDK version in a shell variable. 327 if module.ManifestPath != nil { 328 rule.Command().Text(`target_sdk_version="$(`). 329 Tool(globalSoong.ManifestCheck). 330 Flag("--extract-target-sdk-version"). 331 Input(module.ManifestPath). 332 Text(`)"`) 333 } else { 334 // No manifest to extract targetSdkVersion from, hope that DexJar is an APK 335 rule.Command().Text(`target_sdk_version="$(`). 336 Tool(globalSoong.Aapt). 337 Flag("dump badging"). 338 Input(module.DexPath). 339 Text(`| grep "targetSdkVersion" | sed -n "s/targetSdkVersion:'\(.*\)'/\1/p"`). 340 Text(`)"`) 341 } 342 343 // Generate command that saves host and target class loader context in shell variables. 344 cmd := rule.Command(). 345 Text(`eval "$(`).Tool(globalSoong.ConstructContext). 346 Text(` --target-sdk-version ${target_sdk_version}`) 347 for _, ver := range classLoaderContexts.getSortedKeys() { 348 clc := classLoaderContexts.getValue(ver) 349 verString := fmt.Sprintf("%d", ver) 350 if ver == anySdkVersion { 351 verString = "any" // a special keyword that means any SDK version 352 } 353 cmd.Textf(`--host-classpath-for-sdk %s %s`, verString, strings.Join(clc.Host.Strings(), ":")). 354 Implicits(clc.Host). 355 Textf(`--target-classpath-for-sdk %s %s`, verString, strings.Join(clc.Target, ":")) 356 } 357 cmd.Text(`)"`) 358 } else { 359 // Pass special class loader context to skip the classpath and collision check. 360 // This will get removed once LOCAL_USES_LIBRARIES is enforced. 361 // Right now LOCAL_USES_LIBRARIES is opt in, for the case where it's not specified we still default 362 // to the &. 363 rule.Command(). 364 Text(`class_loader_context_arg=--class-loader-context=\&`). 365 Text(`stored_class_loader_context_arg=""`) 366 } 367 368 // Devices that do not have a product partition use a symlink from /product to /system/product. 369 // Because on-device dexopt will see dex locations starting with /product, we change the paths 370 // to mimic this behavior. 371 dexLocationArg := module.DexLocation 372 if strings.HasPrefix(dexLocationArg, "/system/product/") { 373 dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system") 374 } 375 376 cmd := rule.Command(). 377 Text(`ANDROID_LOG_TAGS="*:e"`). 378 Tool(globalSoong.Dex2oat). 379 Flag("--avoid-storing-invocation"). 380 FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath). 381 Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms). 382 Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx). 383 Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":"). 384 Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":"). 385 Flag("${class_loader_context_arg}"). 386 Flag("${stored_class_loader_context_arg}"). 387 FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocations, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()). 388 FlagWithInput("--dex-file=", module.DexPath). 389 FlagWithArg("--dex-location=", dexLocationArg). 390 FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath). 391 // Pass an empty directory, dex2oat shouldn't be reading arbitrary files 392 FlagWithArg("--android-root=", global.EmptyDirectory). 393 FlagWithArg("--instruction-set=", arch.String()). 394 FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]). 395 FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]). 396 Flag("--no-generate-debug-info"). 397 Flag("--generate-build-id"). 398 Flag("--abort-on-hard-verifier-error"). 399 Flag("--force-determinism"). 400 FlagWithArg("--no-inline-from=", "core-oj.jar") 401 402 var preoptFlags []string 403 if len(module.PreoptFlags) > 0 { 404 preoptFlags = module.PreoptFlags 405 } else if len(global.PreoptFlags) > 0 { 406 preoptFlags = global.PreoptFlags 407 } 408 409 if len(preoptFlags) > 0 { 410 cmd.Text(strings.Join(preoptFlags, " ")) 411 } 412 413 if module.UncompressedDex { 414 cmd.FlagWithArg("--copy-dex-files=", "false") 415 } 416 417 if !android.PrefixInList(preoptFlags, "--compiler-filter=") { 418 var compilerFilter string 419 if contains(global.SystemServerJars, module.Name) { 420 // Jars of system server, use the product option if it is set, speed otherwise. 421 if global.SystemServerCompilerFilter != "" { 422 compilerFilter = global.SystemServerCompilerFilter 423 } else { 424 compilerFilter = "speed" 425 } 426 } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) { 427 // Apps loaded into system server, and apps the product default to being compiled with the 428 // 'speed' compiler filter. 429 compilerFilter = "speed" 430 } else if profile != nil { 431 // For non system server jars, use speed-profile when we have a profile. 432 compilerFilter = "speed-profile" 433 } else if global.DefaultCompilerFilter != "" { 434 compilerFilter = global.DefaultCompilerFilter 435 } else { 436 compilerFilter = "quicken" 437 } 438 cmd.FlagWithArg("--compiler-filter=", compilerFilter) 439 } 440 441 if generateDM { 442 cmd.FlagWithArg("--copy-dex-files=", "false") 443 dmPath := module.BuildPath.InSameDir(ctx, "generated.dm") 444 dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm") 445 tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex") 446 rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath) 447 rule.Command().Tool(globalSoong.SoongZip). 448 FlagWithArg("-L", "9"). 449 FlagWithOutput("-o", dmPath). 450 Flag("-j"). 451 Input(tmpPath) 452 rule.Install(dmPath, dmInstalledPath) 453 } 454 455 // By default, emit debug info. 456 debugInfo := true 457 if global.NoDebugInfo { 458 // If the global setting suppresses mini-debug-info, disable it. 459 debugInfo = false 460 } 461 462 // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO. 463 // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO. 464 if contains(global.SystemServerJars, module.Name) { 465 if global.AlwaysSystemServerDebugInfo { 466 debugInfo = true 467 } else if global.NeverSystemServerDebugInfo { 468 debugInfo = false 469 } 470 } else { 471 if global.AlwaysOtherDebugInfo { 472 debugInfo = true 473 } else if global.NeverOtherDebugInfo { 474 debugInfo = false 475 } 476 } 477 478 // Never enable on eng. 479 if global.IsEng { 480 debugInfo = false 481 } 482 483 if debugInfo { 484 cmd.Flag("--generate-mini-debug-info") 485 } else { 486 cmd.Flag("--no-generate-mini-debug-info") 487 } 488 489 // Set the compiler reason to 'prebuilt' to identify the oat files produced 490 // during the build, as opposed to compiled on the device. 491 cmd.FlagWithArg("--compilation-reason=", "prebuilt") 492 493 if appImage { 494 appImagePath := odexPath.ReplaceExtension(ctx, "art") 495 appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art") 496 cmd.FlagWithOutput("--app-image-file=", appImagePath). 497 FlagWithArg("--image-format=", "lz4") 498 if !global.DontResolveStartupStrings { 499 cmd.FlagWithArg("--resolve-startup-const-strings=", "true") 500 } 501 rule.Install(appImagePath, appImageInstallPath) 502 } 503 504 if profile != nil { 505 cmd.FlagWithInput("--profile-file=", profile) 506 } 507 508 rule.Install(odexPath, odexInstallPath) 509 rule.Install(vdexPath, vdexInstallPath) 510} 511 512func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool { 513 // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs. 514 // No reason to use a dm file if the dex is already uncompressed. 515 return global.GenerateDMFiles && !module.UncompressedDex && 516 contains(module.PreoptFlags, "--compiler-filter=verify") 517} 518 519func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool { 520 if !global.HasSystemOther { 521 return false 522 } 523 524 if global.SanitizeLite { 525 return false 526 } 527 528 if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) { 529 return false 530 } 531 532 for _, f := range global.PatternsOnSystemOther { 533 if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) { 534 return true 535 } 536 } 537 538 return false 539} 540 541func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool { 542 return OdexOnSystemOtherByName(module.Name, module.DexLocation, global) 543} 544 545// PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art 546func PathToLocation(path android.Path, arch android.ArchType) string { 547 pathArch := filepath.Base(filepath.Dir(path.String())) 548 if pathArch != arch.String() { 549 panic(fmt.Errorf("last directory in %q must be %q", path, arch.String())) 550 } 551 return filepath.Join(filepath.Dir(filepath.Dir(path.String())), filepath.Base(path.String())) 552} 553 554func pathForLibrary(module *ModuleConfig, lib string) *LibraryPath { 555 path, ok := module.LibraryPaths[lib] 556 if !ok { 557 panic(fmt.Errorf("unknown library path for %q", lib)) 558 } 559 return path 560} 561 562func makefileMatch(pattern, s string) bool { 563 percent := strings.IndexByte(pattern, '%') 564 switch percent { 565 case -1: 566 return pattern == s 567 case len(pattern) - 1: 568 return strings.HasPrefix(s, pattern[:len(pattern)-1]) 569 default: 570 panic(fmt.Errorf("unsupported makefile pattern %q", pattern)) 571 } 572} 573 574// Expected format for apexJarValue = <apex name>:<jar name> 575func GetJarLocationFromApexJarPair(ctx android.PathContext, apexJarValue string) string { 576 apex, jar := android.SplitApexJarPair(ctx, apexJarValue) 577 return filepath.Join("/apex", apex, "javalib", jar+".jar") 578} 579 580var nonUpdatableSystemServerJarsKey = android.NewOnceKey("nonUpdatableSystemServerJars") 581 582// TODO: eliminate the superficial global config parameter by moving global config definition 583// from java subpackage to dexpreopt. 584func NonUpdatableSystemServerJars(ctx android.PathContext, global *GlobalConfig) []string { 585 return ctx.Config().Once(nonUpdatableSystemServerJarsKey, func() interface{} { 586 return android.RemoveListFromList(global.SystemServerJars, 587 android.GetJarsFromApexJarPairs(ctx, global.UpdatableSystemServerJars)) 588 }).([]string) 589} 590 591// A predefined location for the system server dex jars. This is needed in order to generate 592// class loader context for dex2oat, as the path to the jar in the Soong module may be unknown 593// at that time (Soong processes the jars in dependency order, which may be different from the 594// the system server classpath order). 595func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath { 596 if DexpreoptRunningInSoong { 597 // Soong module, just use the default output directory $OUT/soong. 598 return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar") 599 } else { 600 // Make module, default output directory is $OUT (passed via the "null config" created 601 // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths. 602 return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar") 603 } 604} 605 606// Check the order of jars on the system server classpath and give a warning/error if a jar precedes 607// one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't 608// have the dependency jar in the class loader context, and it won't be able to resolve any 609// references to its classes and methods. 610func checkSystemServerOrder(ctx android.PathContext, jarIndex int) { 611 mctx, isModule := ctx.(android.ModuleContext) 612 if isModule { 613 config := GetGlobalConfig(ctx) 614 jars := NonUpdatableSystemServerJars(ctx, config) 615 mctx.WalkDeps(func(dep android.Module, parent android.Module) bool { 616 depIndex := android.IndexList(dep.Name(), jars) 617 if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars { 618 jar := jars[jarIndex] 619 dep := jars[depIndex] 620 mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+ 621 " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+ 622 " references from '%s' to '%s'.\n", jar, dep, jar, dep) 623 } 624 return true 625 }) 626 } 627} 628 629func contains(l []string, s string) bool { 630 for _, e := range l { 631 if e == s { 632 return true 633 } 634 } 635 return false 636} 637 638var copyOf = android.CopyOf 639