dexpreopt.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. // The dexpreopt package converts a global dexpreopt config and a module dexpreopt config into rules to perform
  15. // dexpreopting.
  16. //
  17. // It is used in two places; in the dexpeopt_gen binary for modules defined in Make, and directly linked into Soong.
  18. //
  19. // For Make modules it is built into the dexpreopt_gen binary, which is executed as a Make rule using global config and
  20. // module config specified in JSON files. The binary writes out two shell scripts, only updating them if they have
  21. // changed. One script takes an APK or JAR as an input and produces a zip file containing any outputs of preopting,
  22. // in the location they should be on the device. The Make build rules will unzip the zip file into $(PRODUCT_OUT) when
  23. // installing the APK, which will install the preopt outputs into $(PRODUCT_OUT)/system or $(PRODUCT_OUT)/system_other
  24. // as necessary. The zip file may be empty if preopting was disabled for any reason.
  25. //
  26. // The intermediate shell scripts allow changes to this package or to the global config to regenerate the shell scripts
  27. // but only require re-executing preopting if the script has changed.
  28. //
  29. // For Soong modules this package is linked directly into Soong and run from the java package. It generates the same
  30. // commands as for make, using athe same global config JSON file used by make, but using a module config structure
  31. // provided by Soong. The generated commands are then converted into Soong rule and written directly to the ninja file,
  32. // with no extra shell scripts involved.
  33. package dexpreopt
  34. import (
  35. "fmt"
  36. "path/filepath"
  37. "runtime"
  38. "strings"
  39. "android/soong/android"
  40. "github.com/google/blueprint/pathtools"
  41. )
  42. const SystemPartition = "/system/"
  43. const SystemOtherPartition = "/system_other/"
  44. var DexpreoptRunningInSoong = false
  45. // GenerateDexpreoptRule generates a set of commands that will preopt a module based on a GlobalConfig and a
  46. // ModuleConfig. The produced files and their install locations will be available through rule.Installs().
  47. func GenerateDexpreoptRule(ctx android.BuilderContext, globalSoong *GlobalSoongConfig,
  48. global *GlobalConfig, module *ModuleConfig) (rule *android.RuleBuilder, err error) {
  49. defer func() {
  50. if r := recover(); r != nil {
  51. if _, ok := r.(runtime.Error); ok {
  52. panic(r)
  53. } else if e, ok := r.(error); ok {
  54. err = e
  55. rule = nil
  56. } else {
  57. panic(r)
  58. }
  59. }
  60. }()
  61. rule = android.NewRuleBuilder(pctx, ctx)
  62. generateProfile := module.ProfileClassListing.Valid() && !global.DisableGenerateProfile
  63. generateBootProfile := module.ProfileBootListing.Valid() && !global.DisableGenerateProfile
  64. var profile android.WritablePath
  65. if generateProfile {
  66. profile = profileCommand(ctx, globalSoong, global, module, rule)
  67. }
  68. if generateBootProfile {
  69. bootProfileCommand(ctx, globalSoong, global, module, rule)
  70. }
  71. if !dexpreoptDisabled(ctx, global, module) {
  72. if valid, err := validateClassLoaderContext(module.ClassLoaderContexts); err != nil {
  73. android.ReportPathErrorf(ctx, err.Error())
  74. } else if valid {
  75. fixClassLoaderContext(module.ClassLoaderContexts)
  76. appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
  77. !module.NoCreateAppImage
  78. generateDM := shouldGenerateDM(module, global)
  79. for archIdx, _ := range module.Archs {
  80. dexpreoptCommand(ctx, globalSoong, global, module, rule, archIdx, profile, appImage, generateDM)
  81. }
  82. }
  83. }
  84. return rule, nil
  85. }
  86. // If dexpreopt is applicable to the module, returns whether dexpreopt is disabled. Otherwise, the
  87. // behavior is undefined.
  88. // When it returns true, dexpreopt artifacts will not be generated, but profile will still be
  89. // generated if profile-guided compilation is requested.
  90. func dexpreoptDisabled(ctx android.PathContext, global *GlobalConfig, module *ModuleConfig) bool {
  91. if ctx.Config().UnbundledBuild() {
  92. return true
  93. }
  94. if global.DisablePreopt {
  95. return true
  96. }
  97. if contains(global.DisablePreoptModules, module.Name) {
  98. return true
  99. }
  100. // Don't preopt individual boot jars, they will be preopted together.
  101. if global.BootJars.ContainsJar(module.Name) {
  102. return true
  103. }
  104. // If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
  105. // Also preopt system server jars since selinux prevents system server from loading anything from
  106. // /data. If we don't do this they will need to be extracted which is not favorable for RAM usage
  107. // or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
  108. if global.OnlyPreoptBootImageAndSystemServer && !global.BootJars.ContainsJar(module.Name) &&
  109. !global.AllSystemServerJars(ctx).ContainsJar(module.Name) && !module.PreoptExtractedApk {
  110. return true
  111. }
  112. return false
  113. }
  114. func profileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
  115. module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
  116. profilePath := module.BuildPath.InSameDir(ctx, "profile.prof")
  117. profileInstalledPath := module.DexLocation + ".prof"
  118. if !module.ProfileIsTextListing {
  119. rule.Command().Text("rm -f").Output(profilePath)
  120. rule.Command().Text("touch").Output(profilePath)
  121. }
  122. cmd := rule.Command().
  123. Text(`ANDROID_LOG_TAGS="*:e"`).
  124. Tool(globalSoong.Profman)
  125. if module.ProfileIsTextListing {
  126. // The profile is a test listing of classes (used for framework jars).
  127. // We need to generate the actual binary profile before being able to compile.
  128. cmd.FlagWithInput("--create-profile-from=", module.ProfileClassListing.Path())
  129. } else {
  130. // The profile is binary profile (used for apps). Run it through profman to
  131. // ensure the profile keys match the apk.
  132. cmd.
  133. Flag("--copy-and-update-profile-key").
  134. FlagWithInput("--profile-file=", module.ProfileClassListing.Path())
  135. }
  136. cmd.
  137. Flag("--output-profile-type=app").
  138. FlagWithInput("--apk=", module.DexPath).
  139. Flag("--dex-location="+module.DexLocation).
  140. FlagWithOutput("--reference-profile-file=", profilePath)
  141. if !module.ProfileIsTextListing {
  142. cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
  143. }
  144. rule.Install(profilePath, profileInstalledPath)
  145. return profilePath
  146. }
  147. func bootProfileCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
  148. module *ModuleConfig, rule *android.RuleBuilder) android.WritablePath {
  149. profilePath := module.BuildPath.InSameDir(ctx, "profile.bprof")
  150. profileInstalledPath := module.DexLocation + ".bprof"
  151. if !module.ProfileIsTextListing {
  152. rule.Command().Text("rm -f").Output(profilePath)
  153. rule.Command().Text("touch").Output(profilePath)
  154. }
  155. cmd := rule.Command().
  156. Text(`ANDROID_LOG_TAGS="*:e"`).
  157. Tool(globalSoong.Profman)
  158. // The profile is a test listing of methods.
  159. // We need to generate the actual binary profile.
  160. cmd.FlagWithInput("--create-profile-from=", module.ProfileBootListing.Path())
  161. cmd.
  162. Flag("--output-profile-type=bprof").
  163. FlagWithInput("--apk=", module.DexPath).
  164. Flag("--dex-location="+module.DexLocation).
  165. FlagWithOutput("--reference-profile-file=", profilePath)
  166. if !module.ProfileIsTextListing {
  167. cmd.Text(fmt.Sprintf(`|| echo "Profile out of date for %s"`, module.DexPath))
  168. }
  169. rule.Install(profilePath, profileInstalledPath)
  170. return profilePath
  171. }
  172. // Returns the dex location of a system server java library.
  173. func GetSystemServerDexLocation(ctx android.PathContext, global *GlobalConfig, lib string) string {
  174. if apex := global.AllApexSystemServerJars(ctx).ApexOfJar(lib); apex != "" {
  175. return fmt.Sprintf("/apex/%s/javalib/%s.jar", apex, lib)
  176. }
  177. if apex := global.AllPlatformSystemServerJars(ctx).ApexOfJar(lib); apex == "system_ext" {
  178. return fmt.Sprintf("/system_ext/framework/%s.jar", lib)
  179. }
  180. return fmt.Sprintf("/system/framework/%s.jar", lib)
  181. }
  182. // Returns the location to the odex file for the dex file at `path`.
  183. func ToOdexPath(path string, arch android.ArchType) string {
  184. if strings.HasPrefix(path, "/apex/") {
  185. return filepath.Join("/system/framework/oat", arch.String(),
  186. strings.ReplaceAll(path[1:], "/", "@")+"@classes.odex")
  187. }
  188. return filepath.Join(filepath.Dir(path), "oat", arch.String(),
  189. pathtools.ReplaceExtension(filepath.Base(path), "odex"))
  190. }
  191. func dexpreoptCommand(ctx android.PathContext, globalSoong *GlobalSoongConfig, global *GlobalConfig,
  192. module *ModuleConfig, rule *android.RuleBuilder, archIdx int, profile android.WritablePath,
  193. appImage bool, generateDM bool) {
  194. arch := module.Archs[archIdx]
  195. // HACK: make soname in Soong-generated .odex files match Make.
  196. base := filepath.Base(module.DexLocation)
  197. if filepath.Ext(base) == ".jar" {
  198. base = "javalib.jar"
  199. } else if filepath.Ext(base) == ".apk" {
  200. base = "package.apk"
  201. }
  202. odexPath := module.BuildPath.InSameDir(ctx, "oat", arch.String(), pathtools.ReplaceExtension(base, "odex"))
  203. odexInstallPath := ToOdexPath(module.DexLocation, arch)
  204. if odexOnSystemOther(module, global) {
  205. odexInstallPath = filepath.Join(SystemOtherPartition, odexInstallPath)
  206. }
  207. vdexPath := odexPath.ReplaceExtension(ctx, "vdex")
  208. vdexInstallPath := pathtools.ReplaceExtension(odexInstallPath, "vdex")
  209. invocationPath := odexPath.ReplaceExtension(ctx, "invocation")
  210. systemServerJars := global.AllSystemServerJars(ctx)
  211. systemServerClasspathJars := global.AllSystemServerClasspathJars(ctx)
  212. rule.Command().FlagWithArg("mkdir -p ", filepath.Dir(odexPath.String()))
  213. rule.Command().FlagWithOutput("rm -f ", odexPath)
  214. if jarIndex := systemServerJars.IndexOfJar(module.Name); jarIndex >= 0 {
  215. // System server jars should be dexpreopted together: class loader context of each jar
  216. // should include all preceding jars on the system server classpath.
  217. var clcHost android.Paths
  218. var clcTarget []string
  219. endIndex := systemServerClasspathJars.IndexOfJar(module.Name)
  220. if endIndex < 0 {
  221. // The jar is a standalone one. Use the full classpath as the class loader context.
  222. endIndex = systemServerClasspathJars.Len()
  223. }
  224. for i := 0; i < endIndex; i++ {
  225. lib := systemServerClasspathJars.Jar(i)
  226. clcHost = append(clcHost, SystemServerDexJarHostPath(ctx, lib))
  227. clcTarget = append(clcTarget, GetSystemServerDexLocation(ctx, global, lib))
  228. }
  229. if DexpreoptRunningInSoong {
  230. // Copy the system server jar to a predefined location where dex2oat will find it.
  231. dexPathHost := SystemServerDexJarHostPath(ctx, module.Name)
  232. rule.Command().Text("mkdir -p").Flag(filepath.Dir(dexPathHost.String()))
  233. rule.Command().Text("cp -f").Input(module.DexPath).Output(dexPathHost)
  234. } else {
  235. // For Make modules the copy rule is generated in the makefiles, not in dexpreopt.sh.
  236. // This is necessary to expose the rule to Ninja, otherwise it has rules that depend on
  237. // the jar (namely, dexpreopt commands for all subsequent system server jars that have
  238. // this one in their class loader context), but no rule that creates it (because Ninja
  239. // cannot see the rule in the generated dexpreopt.sh script).
  240. }
  241. clcHostString := "PCL[" + strings.Join(clcHost.Strings(), ":") + "]"
  242. clcTargetString := "PCL[" + strings.Join(clcTarget, ":") + "]"
  243. if systemServerClasspathJars.ContainsJar(module.Name) {
  244. checkSystemServerOrder(ctx, jarIndex)
  245. } else {
  246. // Standalone jars are loaded by separate class loaders with SYSTEMSERVERCLASSPATH as the
  247. // parent.
  248. clcHostString = "PCL[];" + clcHostString
  249. clcTargetString = "PCL[];" + clcTargetString
  250. }
  251. rule.Command().
  252. Text(`class_loader_context_arg=--class-loader-context="` + clcHostString + `"`).
  253. Implicits(clcHost).
  254. Text(`stored_class_loader_context_arg=--stored-class-loader-context="` + clcTargetString + `"`)
  255. } else {
  256. // There are three categories of Java modules handled here:
  257. //
  258. // - Modules that have passed verify_uses_libraries check. They are AOT-compiled and
  259. // expected to be loaded on device without CLC mismatch errors.
  260. //
  261. // - Modules that have failed the check in relaxed mode, so it didn't cause a build error.
  262. // They are dexpreopted with "verify" filter and not AOT-compiled.
  263. // TODO(b/132357300): ensure that CLC mismatch errors are ignored with "verify" filter.
  264. //
  265. // - Modules that didn't run the check. They are AOT-compiled, but it's unknown if they
  266. // will have CLC mismatch errors on device (the check is disabled by default).
  267. //
  268. // TODO(b/132357300): enable the check by default and eliminate the last category, so that
  269. // no time/space is wasted on AOT-compiling modules that will fail CLC check on device.
  270. var manifestOrApk android.Path
  271. if module.ManifestPath.Valid() {
  272. // Ok, there is an XML manifest.
  273. manifestOrApk = module.ManifestPath.Path()
  274. } else if filepath.Ext(base) == ".apk" {
  275. // Ok, there is is an APK with the manifest inside.
  276. manifestOrApk = module.DexPath
  277. }
  278. // Generate command that saves target SDK version in a shell variable.
  279. if manifestOrApk == nil {
  280. // There is neither an XML manifest nor APK => nowhere to extract targetSdkVersion from.
  281. // Set the latest ("any") version: then construct_context will not add any compatibility
  282. // libraries (if this is incorrect, there will be a CLC mismatch and dexopt on device).
  283. rule.Command().Textf(`target_sdk_version=%d`, AnySdkVersion)
  284. } else {
  285. rule.Command().Text(`target_sdk_version="$(`).
  286. Tool(globalSoong.ManifestCheck).
  287. Flag("--extract-target-sdk-version").
  288. Input(manifestOrApk).
  289. FlagWithInput("--aapt ", globalSoong.Aapt).
  290. Text(`)"`)
  291. }
  292. // Generate command that saves host and target class loader context in shell variables.
  293. clc, paths := ComputeClassLoaderContext(module.ClassLoaderContexts)
  294. rule.Command().
  295. Text(`eval "$(`).Tool(globalSoong.ConstructContext).
  296. Text(` --target-sdk-version ${target_sdk_version}`).
  297. Text(clc).Implicits(paths).
  298. Text(`)"`)
  299. }
  300. // Devices that do not have a product partition use a symlink from /product to /system/product.
  301. // Because on-device dexopt will see dex locations starting with /product, we change the paths
  302. // to mimic this behavior.
  303. dexLocationArg := module.DexLocation
  304. if strings.HasPrefix(dexLocationArg, "/system/product/") {
  305. dexLocationArg = strings.TrimPrefix(dexLocationArg, "/system")
  306. }
  307. cmd := rule.Command().
  308. Text(`ANDROID_LOG_TAGS="*:e"`).
  309. Tool(globalSoong.Dex2oat).
  310. Flag("--avoid-storing-invocation").
  311. FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
  312. Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatXms).
  313. Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatXmx).
  314. Flag("--runtime-arg").FlagWithInputList("-Xbootclasspath:", module.PreoptBootClassPathDexFiles, ":").
  315. Flag("--runtime-arg").FlagWithList("-Xbootclasspath-locations:", module.PreoptBootClassPathDexLocations, ":").
  316. Flag("${class_loader_context_arg}").
  317. Flag("${stored_class_loader_context_arg}").
  318. FlagWithArg("--boot-image=", strings.Join(module.DexPreoptImageLocationsOnHost, ":")).Implicits(module.DexPreoptImagesDeps[archIdx].Paths()).
  319. FlagWithInput("--dex-file=", module.DexPath).
  320. FlagWithArg("--dex-location=", dexLocationArg).
  321. FlagWithOutput("--oat-file=", odexPath).ImplicitOutput(vdexPath).
  322. // Pass an empty directory, dex2oat shouldn't be reading arbitrary files
  323. FlagWithArg("--android-root=", global.EmptyDirectory).
  324. FlagWithArg("--instruction-set=", arch.String()).
  325. FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
  326. FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
  327. Flag("--no-generate-debug-info").
  328. Flag("--generate-build-id").
  329. Flag("--abort-on-hard-verifier-error").
  330. Flag("--force-determinism").
  331. FlagWithArg("--no-inline-from=", "core-oj.jar")
  332. var preoptFlags []string
  333. if len(module.PreoptFlags) > 0 {
  334. preoptFlags = module.PreoptFlags
  335. } else if len(global.PreoptFlags) > 0 {
  336. preoptFlags = global.PreoptFlags
  337. }
  338. if len(preoptFlags) > 0 {
  339. cmd.Text(strings.Join(preoptFlags, " "))
  340. }
  341. if module.UncompressedDex {
  342. cmd.FlagWithArg("--copy-dex-files=", "false")
  343. }
  344. if !android.PrefixInList(preoptFlags, "--compiler-filter=") {
  345. var compilerFilter string
  346. if systemServerJars.ContainsJar(module.Name) {
  347. if global.SystemServerCompilerFilter != "" {
  348. // Use the product option if it is set.
  349. compilerFilter = global.SystemServerCompilerFilter
  350. } else if profile != nil {
  351. // Use "speed-profile" for system server jars that have a profile.
  352. compilerFilter = "speed-profile"
  353. } else {
  354. // Use "speed" for system server jars that do not have a profile.
  355. compilerFilter = "speed"
  356. }
  357. } else if contains(global.SpeedApps, module.Name) || contains(global.SystemServerApps, module.Name) {
  358. // Apps loaded into system server, and apps the product default to being compiled with the
  359. // 'speed' compiler filter.
  360. compilerFilter = "speed"
  361. } else if profile != nil {
  362. // For non system server jars, use speed-profile when we have a profile.
  363. compilerFilter = "speed-profile"
  364. } else if global.DefaultCompilerFilter != "" {
  365. compilerFilter = global.DefaultCompilerFilter
  366. } else {
  367. compilerFilter = "quicken"
  368. }
  369. if module.EnforceUsesLibraries {
  370. // If the verify_uses_libraries check failed (in this case status file contains a
  371. // non-empty error message), then use "verify" compiler filter to avoid compiling any
  372. // code (it would be rejected on device because of a class loader context mismatch).
  373. cmd.Text("--compiler-filter=$(if test -s ").
  374. Input(module.EnforceUsesLibrariesStatusFile).
  375. Text(" ; then echo verify ; else echo " + compilerFilter + " ; fi)")
  376. } else {
  377. cmd.FlagWithArg("--compiler-filter=", compilerFilter)
  378. }
  379. }
  380. if generateDM {
  381. cmd.FlagWithArg("--copy-dex-files=", "false")
  382. dmPath := module.BuildPath.InSameDir(ctx, "generated.dm")
  383. dmInstalledPath := pathtools.ReplaceExtension(module.DexLocation, "dm")
  384. tmpPath := module.BuildPath.InSameDir(ctx, "primary.vdex")
  385. rule.Command().Text("cp -f").Input(vdexPath).Output(tmpPath)
  386. rule.Command().Tool(globalSoong.SoongZip).
  387. FlagWithArg("-L", "9").
  388. FlagWithOutput("-o", dmPath).
  389. Flag("-j").
  390. Input(tmpPath)
  391. rule.Install(dmPath, dmInstalledPath)
  392. }
  393. // By default, emit debug info.
  394. debugInfo := true
  395. if global.NoDebugInfo {
  396. // If the global setting suppresses mini-debug-info, disable it.
  397. debugInfo = false
  398. }
  399. // PRODUCT_SYSTEM_SERVER_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
  400. // PRODUCT_OTHER_JAVA_DEBUG_INFO overrides WITH_DEXPREOPT_DEBUG_INFO.
  401. if systemServerJars.ContainsJar(module.Name) {
  402. if global.AlwaysSystemServerDebugInfo {
  403. debugInfo = true
  404. } else if global.NeverSystemServerDebugInfo {
  405. debugInfo = false
  406. }
  407. } else {
  408. if global.AlwaysOtherDebugInfo {
  409. debugInfo = true
  410. } else if global.NeverOtherDebugInfo {
  411. debugInfo = false
  412. }
  413. }
  414. if debugInfo {
  415. cmd.Flag("--generate-mini-debug-info")
  416. } else {
  417. cmd.Flag("--no-generate-mini-debug-info")
  418. }
  419. // Set the compiler reason to 'prebuilt' to identify the oat files produced
  420. // during the build, as opposed to compiled on the device.
  421. cmd.FlagWithArg("--compilation-reason=", "prebuilt")
  422. if appImage {
  423. appImagePath := odexPath.ReplaceExtension(ctx, "art")
  424. appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
  425. cmd.FlagWithOutput("--app-image-file=", appImagePath).
  426. FlagWithArg("--image-format=", "lz4")
  427. if !global.DontResolveStartupStrings {
  428. cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
  429. }
  430. rule.Install(appImagePath, appImageInstallPath)
  431. }
  432. if profile != nil {
  433. cmd.FlagWithInput("--profile-file=", profile)
  434. }
  435. if global.EnableUffdGc {
  436. cmd.Flag("--runtime-arg").Flag("-Xgc:CMC")
  437. }
  438. rule.Install(odexPath, odexInstallPath)
  439. rule.Install(vdexPath, vdexInstallPath)
  440. }
  441. func shouldGenerateDM(module *ModuleConfig, global *GlobalConfig) bool {
  442. // Generating DM files only makes sense for verify, avoid doing for non verify compiler filter APKs.
  443. // No reason to use a dm file if the dex is already uncompressed.
  444. return global.GenerateDMFiles && !module.UncompressedDex &&
  445. contains(module.PreoptFlags, "--compiler-filter=verify")
  446. }
  447. func OdexOnSystemOtherByName(name string, dexLocation string, global *GlobalConfig) bool {
  448. if !global.HasSystemOther {
  449. return false
  450. }
  451. if global.SanitizeLite {
  452. return false
  453. }
  454. if contains(global.SpeedApps, name) || contains(global.SystemServerApps, name) {
  455. return false
  456. }
  457. for _, f := range global.PatternsOnSystemOther {
  458. if makefileMatch(filepath.Join(SystemPartition, f), dexLocation) {
  459. return true
  460. }
  461. }
  462. return false
  463. }
  464. func odexOnSystemOther(module *ModuleConfig, global *GlobalConfig) bool {
  465. return OdexOnSystemOtherByName(module.Name, module.DexLocation, global)
  466. }
  467. // PathToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
  468. func PathToLocation(path android.Path, arch android.ArchType) string {
  469. return PathStringToLocation(path.String(), arch)
  470. }
  471. // PathStringToLocation converts .../system/framework/arm64/boot.art to .../system/framework/boot.art
  472. func PathStringToLocation(path string, arch android.ArchType) string {
  473. pathArch := filepath.Base(filepath.Dir(path))
  474. if pathArch != arch.String() {
  475. panic(fmt.Errorf("last directory in %q must be %q", path, arch.String()))
  476. }
  477. return filepath.Join(filepath.Dir(filepath.Dir(path)), filepath.Base(path))
  478. }
  479. func makefileMatch(pattern, s string) bool {
  480. percent := strings.IndexByte(pattern, '%')
  481. switch percent {
  482. case -1:
  483. return pattern == s
  484. case len(pattern) - 1:
  485. return strings.HasPrefix(s, pattern[:len(pattern)-1])
  486. default:
  487. panic(fmt.Errorf("unsupported makefile pattern %q", pattern))
  488. }
  489. }
  490. // A predefined location for the system server dex jars. This is needed in order to generate
  491. // class loader context for dex2oat, as the path to the jar in the Soong module may be unknown
  492. // at that time (Soong processes the jars in dependency order, which may be different from the
  493. // the system server classpath order).
  494. func SystemServerDexJarHostPath(ctx android.PathContext, jar string) android.OutputPath {
  495. if DexpreoptRunningInSoong {
  496. // Soong module, just use the default output directory $OUT/soong.
  497. return android.PathForOutput(ctx, "system_server_dexjars", jar+".jar")
  498. } else {
  499. // Make module, default output directory is $OUT (passed via the "null config" created
  500. // by dexpreopt_gen). Append Soong subdirectory to match Soong module paths.
  501. return android.PathForOutput(ctx, "soong", "system_server_dexjars", jar+".jar")
  502. }
  503. }
  504. // Check the order of jars on the system server classpath and give a warning/error if a jar precedes
  505. // one of its dependencies. This is not an error, but a missed optimization, as dexpreopt won't
  506. // have the dependency jar in the class loader context, and it won't be able to resolve any
  507. // references to its classes and methods.
  508. func checkSystemServerOrder(ctx android.PathContext, jarIndex int) {
  509. mctx, isModule := ctx.(android.ModuleContext)
  510. if isModule {
  511. config := GetGlobalConfig(ctx)
  512. jars := config.AllSystemServerClasspathJars(ctx)
  513. mctx.WalkDeps(func(dep android.Module, parent android.Module) bool {
  514. depIndex := jars.IndexOfJar(dep.Name())
  515. if jarIndex < depIndex && !config.BrokenSuboptimalOrderOfSystemServerJars {
  516. jar := jars.Jar(jarIndex)
  517. dep := jars.Jar(depIndex)
  518. mctx.ModuleErrorf("non-optimal order of jars on the system server classpath:"+
  519. " '%s' precedes its dependency '%s', so dexpreopt is unable to resolve any"+
  520. " references from '%s' to '%s'.\n", jar, dep, jar, dep)
  521. }
  522. return true
  523. })
  524. }
  525. }
  526. // Returns path to a file containing the reult of verify_uses_libraries check (empty if the check
  527. // has succeeded, or an error message if it failed).
  528. func UsesLibrariesStatusFile(ctx android.ModuleContext) android.WritablePath {
  529. return android.PathForModuleOut(ctx, "enforce_uses_libraries.status")
  530. }
  531. func contains(l []string, s string) bool {
  532. for _, e := range l {
  533. if e == s {
  534. return true
  535. }
  536. }
  537. return false
  538. }
  539. var copyOf = android.CopyOf