dexpreopt.go 24 KB

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