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