Refactor dexpreopt_bootjars.go to prepare for multiple boot images

Refactor dexpreopt_bootjars.go so that buildBootImage can be called
with a bootImageConfig to create rules to build the boot image in
preparation for building multiple boot images.

Test: m checkbuild
Change-Id: I7ba40a0988c8acbd6c1ee4e36f4bbb34fb4e2d24
diff --git a/java/dexpreopt_bootjars.go b/java/dexpreopt_bootjars.go
index fe425b1..0ad7a27 100644
--- a/java/dexpreopt_bootjars.go
+++ b/java/dexpreopt_bootjars.go
@@ -48,56 +48,36 @@
 // The location is passed as an argument to the ART tools like dex2oat instead of the real path. The ART tools
 // will then reconstruct the real path, so the rules must have a dependency on the real path.
 
-type bootJarsInfo struct {
-	dir        android.OutputPath
-	symbolsDir android.OutputPath
-	images     map[android.ArchType]android.OutputPath
-	installs   map[android.ArchType]android.RuleBuilderInstalls
-
-	vdexInstalls       map[android.ArchType]android.RuleBuilderInstalls
-	unstrippedInstalls map[android.ArchType]android.RuleBuilderInstalls
-	profileInstalls    android.RuleBuilderInstalls
-
-	global dexpreopt.GlobalConfig
-
-	preoptBootModules     []string
-	preoptBootLocations   []string
-	preoptBootDex         android.WritablePaths
-	allBootModules        []string
-	allBootLocations      []string
-	bootclasspath         string
-	systemServerClasspath string
+type bootImageConfig struct {
+	name         string
+	modules      []string
+	dexLocations []string
+	dexPaths     android.WritablePaths
+	dir          android.OutputPath
+	symbolsDir   android.OutputPath
+	images       map[android.ArchType]android.OutputPath
 }
 
-var dexpreoptBootJarsInfoKey = android.NewOnceKey("dexpreoptBootJarsInfoKey")
+type bootImage struct {
+	bootImageConfig
 
-// dexpreoptBootJarsInfo creates all the paths for singleton files the first time it is called, which may be
-// from a ModuleContext that needs to reference a file that will be created by a singleton rule that hasn't
-// yet been created.
-func dexpreoptBootJarsInfo(ctx android.PathContext) *bootJarsInfo {
-	return ctx.Config().Once(dexpreoptBootJarsInfoKey, func() interface{} {
+	installs           map[android.ArchType]android.RuleBuilderInstalls
+	vdexInstalls       map[android.ArchType]android.RuleBuilderInstalls
+	unstrippedInstalls map[android.ArchType]android.RuleBuilderInstalls
 
-		info := &bootJarsInfo{
-			dir:        android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_bootjars"),
-			symbolsDir: android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_bootjars_unstripped"),
-			images:     make(map[android.ArchType]android.OutputPath),
-			installs:   make(map[android.ArchType]android.RuleBuilderInstalls),
+	profileInstalls android.RuleBuilderInstalls
+}
 
-			vdexInstalls:       make(map[android.ArchType]android.RuleBuilderInstalls),
-			unstrippedInstalls: make(map[android.ArchType]android.RuleBuilderInstalls),
-		}
+func newBootImage(ctx android.PathContext, config bootImageConfig) *bootImage {
+	image := &bootImage{
+		bootImageConfig: defaultBootImageConfig(ctx),
 
-		for _, target := range ctx.Config().Targets[android.Android] {
-			info.images[target.Arch.ArchType] = info.dir.Join(ctx,
-				"system/framework", target.Arch.ArchType.String(), "boot.art")
-		}
+		installs:           make(map[android.ArchType]android.RuleBuilderInstalls),
+		vdexInstalls:       make(map[android.ArchType]android.RuleBuilderInstalls),
+		unstrippedInstalls: make(map[android.ArchType]android.RuleBuilderInstalls),
+	}
 
-		info.global = dexpreoptGlobalConfig(ctx)
-		computeBootClasspath(ctx, info)
-		computeSystemServerClasspath(ctx, info)
-
-		return info
-	}).(*bootJarsInfo)
+	return image
 }
 
 func concat(lists ...[]string) []string {
@@ -112,60 +92,8 @@
 	return ret
 }
 
-func computeBootClasspath(ctx android.PathContext, info *bootJarsInfo) {
-	runtimeModules := info.global.RuntimeApexJars
-	nonFrameworkModules := concat(runtimeModules, info.global.ProductUpdatableBootModules)
-	frameworkModules := android.RemoveListFromList(info.global.BootJars, nonFrameworkModules)
-
-	var nonUpdatableBootModules []string
-	var nonUpdatableBootLocations []string
-
-	for _, m := range runtimeModules {
-		nonUpdatableBootModules = append(nonUpdatableBootModules, m)
-		nonUpdatableBootLocations = append(nonUpdatableBootLocations,
-			filepath.Join("/apex/com.android.runtime/javalib", m+".jar"))
-	}
-
-	for _, m := range frameworkModules {
-		nonUpdatableBootModules = append(nonUpdatableBootModules, m)
-		nonUpdatableBootLocations = append(nonUpdatableBootLocations,
-			filepath.Join("/system/framework", m+".jar"))
-	}
-
-	// The path to bootclasspath dex files needs to be known at module GenerateAndroidBuildAction time, before
-	// the bootclasspath modules have been compiled.  Set up known paths for them, the singleton rules will copy
-	// them there.
-	// TODO: use module dependencies instead
-	var nonUpdatableBootDex android.WritablePaths
-	for _, m := range nonUpdatableBootModules {
-		nonUpdatableBootDex = append(nonUpdatableBootDex,
-			android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_bootjars_input", m+".jar"))
-	}
-
-	allBootModules := concat(nonUpdatableBootModules, info.global.ProductUpdatableBootModules)
-	allBootLocations := concat(nonUpdatableBootLocations, info.global.ProductUpdatableBootLocations)
-
-	bootclasspath := strings.Join(allBootLocations, ":")
-
-	info.preoptBootModules = nonUpdatableBootModules
-	info.preoptBootLocations = nonUpdatableBootLocations
-	info.preoptBootDex = nonUpdatableBootDex
-	info.allBootModules = allBootModules
-	info.allBootLocations = allBootLocations
-	info.bootclasspath = bootclasspath
-}
-
-func computeSystemServerClasspath(ctx android.PathContext, info *bootJarsInfo) {
-	var systemServerClasspathLocations []string
-	for _, m := range info.global.SystemServerJars {
-		systemServerClasspathLocations = append(systemServerClasspathLocations,
-			filepath.Join("/system/framework", m+".jar"))
-	}
-
-	info.systemServerClasspath = strings.Join(systemServerClasspathLocations, ":")
-}
 func dexpreoptBootJarsFactory() android.Singleton {
-	return dexpreoptBootJars{}
+	return &dexpreoptBootJars{}
 }
 
 func skipDexpreoptBootJars(ctx android.PathContext) bool {
@@ -181,15 +109,17 @@
 	return false
 }
 
-type dexpreoptBootJars struct{}
+type dexpreoptBootJars struct {
+	defaultBootImage *bootImage
+}
 
 // dexpreoptBoot singleton rules
-func (dexpreoptBootJars) GenerateBuildActions(ctx android.SingletonContext) {
+func (d *dexpreoptBootJars) GenerateBuildActions(ctx android.SingletonContext) {
 	if skipDexpreoptBootJars(ctx) {
 		return
 	}
 
-	info := dexpreoptBootJarsInfo(ctx)
+	global := dexpreoptGlobalConfig(ctx)
 
 	// Skip recompiling the boot image for the second sanitization phase. We'll get separate paths
 	// and invalidate first-stage artifacts which are crucial to SANITIZE_LITE builds.
@@ -197,17 +127,26 @@
 	//       on ASAN settings.
 	if len(ctx.Config().SanitizeDevice()) == 1 &&
 		ctx.Config().SanitizeDevice()[0] == "address" &&
-		info.global.SanitizeLite {
+		global.SanitizeLite {
 		return
 	}
 
-	bootDexJars := make(android.Paths, len(info.preoptBootModules))
+	d.defaultBootImage = buildBootImage(ctx, defaultBootImageConfig(ctx))
+}
+
+// buildBootImage takes a bootImageConfig, creates rules to build it, and returns a *bootImage.
+func buildBootImage(ctx android.SingletonContext, config bootImageConfig) *bootImage {
+	global := dexpreoptGlobalConfig(ctx)
+
+	image := newBootImage(ctx, config)
+
+	bootDexJars := make(android.Paths, len(image.modules))
 
 	ctx.VisitAllModules(func(module android.Module) {
 		// Collect dex jar paths for the modules listed above.
 		if j, ok := module.(Dependency); ok {
 			name := ctx.ModuleName(module)
-			if i := android.IndexList(name, info.preoptBootModules); i != -1 {
+			if i := android.IndexList(name, image.modules); i != -1 {
 				bootDexJars[i] = j.DexJar()
 			}
 		}
@@ -218,11 +157,11 @@
 	for i := range bootDexJars {
 		if bootDexJars[i] == nil {
 			if ctx.Config().AllowMissingDependencies() {
-				missingDeps = append(missingDeps, info.preoptBootModules[i])
+				missingDeps = append(missingDeps, image.modules[i])
 				bootDexJars[i] = android.PathForOutput(ctx, "missing")
 			} else {
 				ctx.Errorf("failed to find dex jar path for module %q",
-					info.preoptBootModules[i])
+					image.modules[i])
 			}
 		}
 	}
@@ -234,31 +173,35 @@
 		ctx.Build(pctx, android.BuildParams{
 			Rule:   android.Cp,
 			Input:  bootDexJars[i],
-			Output: info.preoptBootDex[i],
+			Output: image.dexPaths[i],
 		})
 	}
 
-	profile := bootImageProfileRule(ctx, info, missingDeps)
+	profile := bootImageProfileRule(ctx, image, missingDeps)
 
-	if !info.global.DisablePreopt {
+	if !global.DisablePreopt {
 		targets := ctx.Config().Targets[android.Android]
 		if ctx.Config().SecondArchIsTranslated() {
 			targets = targets[:1]
 		}
 
 		for _, target := range targets {
-			dexPreoptBootImageRule(ctx, info, target.Arch.ArchType, profile, missingDeps)
+			buildBootImageRuleForArch(ctx, image, target.Arch.ArchType, profile, missingDeps)
 		}
 	}
+
+	return image
 }
 
-func dexPreoptBootImageRule(ctx android.SingletonContext, info *bootJarsInfo,
+func buildBootImageRuleForArch(ctx android.SingletonContext, image *bootImage,
 	arch android.ArchType, profile android.Path, missingDeps []string) {
 
-	symbolsDir := info.symbolsDir.Join(ctx, "system/framework", arch.String())
+	global := dexpreoptGlobalConfig(ctx)
+
+	symbolsDir := image.symbolsDir.Join(ctx, "system/framework", arch.String())
 	symbolsFile := symbolsDir.Join(ctx, "boot.oat")
-	outputDir := info.dir.Join(ctx, "system/framework", arch.String())
-	outputPath := info.images[arch]
+	outputDir := image.dir.Join(ctx, "system/framework", arch.String())
+	outputPath := image.images[arch]
 	oatLocation := pathtools.ReplaceExtension(dexpreopt.PathToLocation(outputPath, arch), "oat")
 
 	rule := android.NewRuleBuilder()
@@ -287,26 +230,26 @@
 
 	invocationPath := outputPath.ReplaceExtension(ctx, "invocation")
 
-	cmd.Tool(info.global.Tools.Dex2oat).
+	cmd.Tool(global.Tools.Dex2oat).
 		Flag("--avoid-storing-invocation").
 		FlagWithOutput("--write-invocation-to=", invocationPath).ImplicitOutput(invocationPath).
-		Flag("--runtime-arg").FlagWithArg("-Xms", info.global.Dex2oatImageXms).
-		Flag("--runtime-arg").FlagWithArg("-Xmx", info.global.Dex2oatImageXmx)
+		Flag("--runtime-arg").FlagWithArg("-Xms", global.Dex2oatImageXms).
+		Flag("--runtime-arg").FlagWithArg("-Xmx", global.Dex2oatImageXmx)
 
 	if profile != nil {
 		cmd.FlagWithArg("--compiler-filter=", "speed-profile")
 		cmd.FlagWithInput("--profile-file=", profile)
-	} else if info.global.PreloadedClasses.Valid() {
-		cmd.FlagWithInput("--image-classes=", info.global.PreloadedClasses.Path())
+	} else if global.PreloadedClasses.Valid() {
+		cmd.FlagWithInput("--image-classes=", global.PreloadedClasses.Path())
 	}
 
-	if info.global.DirtyImageObjects.Valid() {
-		cmd.FlagWithInput("--dirty-image-objects=", info.global.DirtyImageObjects.Path())
+	if global.DirtyImageObjects.Valid() {
+		cmd.FlagWithInput("--dirty-image-objects=", global.DirtyImageObjects.Path())
 	}
 
 	cmd.
-		FlagForEachInput("--dex-file=", info.preoptBootDex.Paths()).
-		FlagForEachArg("--dex-location=", info.preoptBootLocations).
+		FlagForEachInput("--dex-file=", image.dexPaths.Paths()).
+		FlagForEachArg("--dex-location=", image.dexLocations).
 		Flag("--generate-debug-info").
 		Flag("--generate-build-id").
 		FlagWithOutput("--oat-symbols=", symbolsFile).
@@ -316,14 +259,14 @@
 		FlagWithOutput("--image=", outputPath).
 		FlagWithArg("--base=", ctx.Config().LibartImgDeviceBaseAddress()).
 		FlagWithArg("--instruction-set=", arch.String()).
-		FlagWithArg("--instruction-set-variant=", info.global.CpuVariant[arch]).
-		FlagWithArg("--instruction-set-features=", info.global.InstructionSetFeatures[arch]).
-		FlagWithArg("--android-root=", info.global.EmptyDirectory).
+		FlagWithArg("--instruction-set-variant=", global.CpuVariant[arch]).
+		FlagWithArg("--instruction-set-features=", global.InstructionSetFeatures[arch]).
+		FlagWithArg("--android-root=", global.EmptyDirectory).
 		FlagWithArg("--no-inline-from=", "core-oj.jar").
 		Flag("--abort-on-hard-verifier-error")
 
-	if info.global.BootFlags != "" {
-		cmd.Flag(info.global.BootFlags)
+	if global.BootFlags != "" {
+		cmd.Flag(global.BootFlags)
 	}
 
 	if extraFlags != "" {
@@ -344,8 +287,8 @@
 	// exists), and the rest are converted to boot-<name>.art.
 	// In addition, each .art file has an associated .oat and .vdex file, and an
 	// unstripped .oat file
-	for i, m := range info.preoptBootModules {
-		name := "boot"
+	for i, m := range image.modules {
+		name := image.name
 		if i != 0 {
 			name += "-" + m
 		}
@@ -374,35 +317,37 @@
 
 	cmd.ImplicitOutputs(extraFiles)
 
-	rule.Build(pctx, ctx, "bootJarsDexpreopt_"+arch.String(), "dexpreopt boot jars "+arch.String())
+	rule.Build(pctx, ctx, image.name+"JarsDexpreopt_"+arch.String(), "dexpreopt "+image.name+" jars "+arch.String())
 
 	// save output and installed files for makevars
-	info.installs[arch] = rule.Installs()
-	info.vdexInstalls[arch] = vdexInstalls
-	info.unstrippedInstalls[arch] = unstrippedInstalls
+	image.installs[arch] = rule.Installs()
+	image.vdexInstalls[arch] = vdexInstalls
+	image.unstrippedInstalls[arch] = unstrippedInstalls
 }
 
 const failureMessage = `ERROR: Dex2oat failed to compile a boot image.
 It is likely that the boot classpath is inconsistent.
 Rebuild with ART_BOOT_IMAGE_EXTRA_ARGS="--runtime-arg -verbose:verifier" to see verification errors.`
 
-func bootImageProfileRule(ctx android.SingletonContext, info *bootJarsInfo, missingDeps []string) android.WritablePath {
-	if !info.global.UseProfileForBootImage || ctx.Config().IsPdkBuild() || ctx.Config().UnbundledBuild() {
+func bootImageProfileRule(ctx android.SingletonContext, image *bootImage, missingDeps []string) android.WritablePath {
+	global := dexpreoptGlobalConfig(ctx)
+
+	if !global.UseProfileForBootImage || ctx.Config().IsPdkBuild() || ctx.Config().UnbundledBuild() {
 		return nil
 	}
 
-	tools := info.global.Tools
+	tools := global.Tools
 
 	rule := android.NewRuleBuilder()
 	rule.MissingDeps(missingDeps)
 
 	var bootImageProfile android.Path
-	if len(info.global.BootImageProfiles) > 1 {
-		combinedBootImageProfile := info.dir.Join(ctx, "boot-image-profile.txt")
-		rule.Command().Text("cat").Inputs(info.global.BootImageProfiles).Text(">").Output(combinedBootImageProfile)
+	if len(global.BootImageProfiles) > 1 {
+		combinedBootImageProfile := image.dir.Join(ctx, "boot-image-profile.txt")
+		rule.Command().Text("cat").Inputs(global.BootImageProfiles).Text(">").Output(combinedBootImageProfile)
 		bootImageProfile = combinedBootImageProfile
-	} else if len(info.global.BootImageProfiles) == 1 {
-		bootImageProfile = info.global.BootImageProfiles[0]
+	} else if len(global.BootImageProfiles) == 1 {
+		bootImageProfile = global.BootImageProfiles[0]
 	} else {
 		// If not set, use the default.  Some branches like master-art-host don't have frameworks/base, so manually
 		// handle the case that the default is missing.  Those branches won't attempt to build the profile rule,
@@ -417,49 +362,40 @@
 		}
 	}
 
-	profile := info.dir.Join(ctx, "boot.prof")
+	profile := image.dir.Join(ctx, "boot.prof")
 
 	rule.Command().
 		Text(`ANDROID_LOG_TAGS="*:e"`).
 		Tool(tools.Profman).
 		FlagWithInput("--create-profile-from=", bootImageProfile).
-		FlagForEachInput("--apk=", info.preoptBootDex.Paths()).
-		FlagForEachArg("--dex-location=", info.preoptBootLocations).
+		FlagForEachInput("--apk=", image.dexPaths.Paths()).
+		FlagForEachArg("--dex-location=", image.dexLocations).
 		FlagWithOutput("--reference-profile-file=", profile)
 
 	rule.Install(profile, "/system/etc/boot-image.prof")
 
 	rule.Build(pctx, ctx, "bootJarsProfile", "profile boot jars")
 
-	info.profileInstalls = rule.Installs()
+	image.profileInstalls = rule.Installs()
 
 	return profile
 }
 
-func init() {
-	android.RegisterMakeVarsProvider(pctx, bootImageMakeVars)
-}
+// Export paths for default boot image to Make
+func (d *dexpreoptBootJars) MakeVars(ctx android.MakeVarsContext) {
+	image := d.defaultBootImage
+	if image != nil {
+		for arch, _ := range image.images {
+			ctx.Strict("DEXPREOPT_IMAGE_"+arch.String(), image.images[arch].String())
 
-// Export paths to Make.  INTERNAL_PLATFORM_HIDDENAPI_FLAGS is used by Make rules in art/ and cts/.
-// Both paths are used to call dist-for-goals.
-func bootImageMakeVars(ctx android.MakeVarsContext) {
-	if skipDexpreoptBootJars(ctx) {
-		return
+			ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+arch.String(), image.installs[arch].String())
+			ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+arch.String(), image.unstrippedInstalls[arch].String())
+			ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+arch.String(), image.vdexInstalls[arch].String())
+		}
+
+		ctx.Strict("DEXPREOPT_IMAGE_PROFILE_BUILT_INSTALLED", image.profileInstalls.String())
+
+		ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_FILES", strings.Join(image.dexPaths.Strings(), " "))
+		ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS", strings.Join(image.dexLocations, " "))
 	}
-
-	info := dexpreoptBootJarsInfo(ctx)
-	for arch, _ := range info.images {
-		ctx.Strict("DEXPREOPT_IMAGE_"+arch.String(), info.images[arch].String())
-
-		ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+arch.String(), info.installs[arch].String())
-		ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+arch.String(), info.unstrippedInstalls[arch].String())
-		ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+arch.String(), info.vdexInstalls[arch].String())
-	}
-
-	ctx.Strict("DEXPREOPT_IMAGE_PROFILE_BUILT_INSTALLED", info.profileInstalls.String())
-
-	ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_FILES", strings.Join(info.preoptBootDex.Strings(), " "))
-	ctx.Strict("DEXPREOPT_BOOTCLASSPATH_DEX_LOCATIONS", strings.Join(info.preoptBootLocations, " "))
-	ctx.Strict("PRODUCT_BOOTCLASSPATH", info.bootclasspath)
-	ctx.Strict("PRODUCT_SYSTEM_SERVER_CLASSPATH", info.systemServerClasspath)
 }