Merge "Include symlinks in flattened apexs"
diff --git a/androidmk/cmd/androidmk/android.go b/androidmk/cmd/androidmk/android.go
index a5dfcd9..4af5d97 100644
--- a/androidmk/cmd/androidmk/android.go
+++ b/androidmk/cmd/androidmk/android.go
@@ -72,6 +72,7 @@
 	"LOCAL_JAR_EXCLUDE_FILES":       skip, // Soong never excludes files from jars
 
 	"LOCAL_ANNOTATION_PROCESSOR_CLASSES": skip, // Soong gets the processor classes from the plugin
+	"LOCAL_CTS_TEST_PACKAGE":             skip, // Obsolete
 }
 
 // adds a group of properties all having the same type
diff --git a/androidmk/cmd/androidmk/androidmk_test.go b/androidmk/cmd/androidmk/androidmk_test.go
index 618dd42..9af2bea 100644
--- a/androidmk/cmd/androidmk/androidmk_test.go
+++ b/androidmk/cmd/androidmk/androidmk_test.go
@@ -758,6 +758,7 @@
 include $(CLEAR_VARS)
 LOCAL_PACKAGE_NAME := FooTest
 LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 `,
 		expected: `
@@ -765,6 +766,7 @@
     name: "FooTest",
     defaults: ["cts_support_defaults"],
     test_suites: ["cts"],
+
 }
 `,
 	},
@@ -774,6 +776,7 @@
 include $(CLEAR_VARS)
 LOCAL_PACKAGE_NAME := FooTest
 LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := foo.bar
 include $(BUILD_CTS_PACKAGE)
 `,
 		expected: `
@@ -781,6 +784,7 @@
     name: "FooTest",
     defaults: ["cts_defaults"],
     test_suites: ["cts"],
+
 }
 `,
 	},
diff --git a/bpfix/bpfix/bpfix.go b/bpfix/bpfix/bpfix.go
index 11f1877..ba6435e 100644
--- a/bpfix/bpfix/bpfix.go
+++ b/bpfix/bpfix/bpfix.go
@@ -98,6 +98,10 @@
 		name: "removeTags",
 		fix:  runPatchListMod(removeTags),
 	},
+	{
+		name: "rewriteAndroidTest",
+		fix:  rewriteAndroidTest,
+	},
 }
 
 func NewFixRequest() FixRequest {
@@ -561,6 +565,30 @@
 	return nil
 }
 
+func rewriteAndroidTest(f *Fixer) error {
+	for _, def := range f.tree.Defs {
+		mod, ok := def.(*parser.Module)
+		if !(ok && mod.Type == "android_test") {
+			continue
+		}
+		// The rewriter converts LOCAL_MODULE_PATH attribute into a struct attribute
+		// 'local_module_path'. For the android_test module, it should be  $(TARGET_OUT_DATA_APPS),
+		// that is, `local_module_path: { var: "TARGET_OUT_DATA_APPS"}`
+		const local_module_path = "local_module_path"
+		if prop_local_module_path, ok := mod.GetProperty(local_module_path); ok {
+			removeProperty(mod, local_module_path)
+			prefixVariableName := getStringProperty(prop_local_module_path, "var")
+			path := getStringProperty(prop_local_module_path, "fixed")
+			if prefixVariableName == "TARGET_OUT_DATA_APPS" && path == "" {
+				continue
+			}
+			return indicateAttributeError(mod, "filename",
+				"Only LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS) is allowed for the android_test")
+		}
+	}
+	return nil
+}
+
 func runPatchListMod(modFunc func(mod *parser.Module, buf []byte, patchlist *parser.PatchList) error) func(*Fixer) error {
 	return func(f *Fixer) error {
 		// Make sure all the offsets are accurate
diff --git a/bpfix/bpfix/bpfix_test.go b/bpfix/bpfix/bpfix_test.go
index 1394223..459cd36 100644
--- a/bpfix/bpfix/bpfix_test.go
+++ b/bpfix/bpfix/bpfix_test.go
@@ -751,3 +751,36 @@
 		})
 	}
 }
+
+func TestRewriteAndroidTest(t *testing.T) {
+	tests := []struct {
+		name string
+		in   string
+		out  string
+	}{
+		{
+			name: "android_test valid module path",
+			in: `
+				android_test {
+					name: "foo",
+					local_module_path: {
+						var: "TARGET_OUT_DATA_APPS",
+					},
+				}
+			`,
+			out: `
+				android_test {
+					name: "foo",
+
+				}
+			`,
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			runPass(t, test.in, test.out, func(fixer *Fixer) error {
+				return rewriteAndroidTest(fixer)
+			})
+		})
+	}
+}
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index 9981401..15008b9 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -31,6 +31,8 @@
 
 	OnlyPreoptBootImageAndSystemServer bool // only preopt jars in the boot image or system server
 
+	GenerateApexImage bool // generate an extra boot image only containing jars from the runtime apex
+
 	HasSystemOther        bool     // store odex files that match PatternsOnSystemOther on the system_other partition
 	PatternsOnSystemOther []string // patterns (using '%' to denote a prefix match) to put odex on the system_other partition
 
diff --git a/java/dexpreopt_bootjars.go b/java/dexpreopt_bootjars.go
index 0ad7a27..a35e011 100644
--- a/java/dexpreopt_bootjars.go
+++ b/java/dexpreopt_bootjars.go
@@ -70,7 +70,7 @@
 
 func newBootImage(ctx android.PathContext, config bootImageConfig) *bootImage {
 	image := &bootImage{
-		bootImageConfig: defaultBootImageConfig(ctx),
+		bootImageConfig: config,
 
 		installs:           make(map[android.ArchType]android.RuleBuilderInstalls),
 		vdexInstalls:       make(map[android.ArchType]android.RuleBuilderInstalls),
@@ -111,6 +111,7 @@
 
 type dexpreoptBootJars struct {
 	defaultBootImage *bootImage
+	otherImages      []*bootImage
 }
 
 // dexpreoptBoot singleton rules
@@ -131,7 +132,11 @@
 		return
 	}
 
+	// Always create the default boot image first, to get a unique profile rule for all images.
 	d.defaultBootImage = buildBootImage(ctx, defaultBootImageConfig(ctx))
+	if global.GenerateApexImage {
+		d.otherImages = append(d.otherImages, buildBootImage(ctx, apexBootImageConfig(ctx)))
+	}
 }
 
 // buildBootImage takes a bootImageConfig, creates rules to build it, and returns a *bootImage.
@@ -199,7 +204,7 @@
 	global := dexpreoptGlobalConfig(ctx)
 
 	symbolsDir := image.symbolsDir.Join(ctx, "system/framework", arch.String())
-	symbolsFile := symbolsDir.Join(ctx, "boot.oat")
+	symbolsFile := symbolsDir.Join(ctx, image.name+".oat")
 	outputDir := image.dir.Join(ctx, "system/framework", arch.String())
 	outputPath := image.images[arch]
 	oatLocation := pathtools.ReplaceExtension(dexpreopt.PathToLocation(outputPath, arch), "oat")
@@ -283,8 +288,8 @@
 	var unstrippedInstalls android.RuleBuilderInstalls
 
 	// dex preopt on the bootclasspath produces multiple files.  The first dex file
-	// is converted into to boot.art (to match the legacy assumption that boot.art
-	// exists), and the rest are converted to boot-<name>.art.
+	// is converted into to 'name'.art (to match the legacy assumption that 'name'.art
+	// exists), and the rest are converted to 'name'-<jar>.art.
 	// In addition, each .art file has an associated .oat and .vdex file, and an
 	// unstripped .oat file
 	for i, m := range image.modules {
@@ -335,67 +340,73 @@
 	if !global.UseProfileForBootImage || ctx.Config().IsPdkBuild() || ctx.Config().UnbundledBuild() {
 		return nil
 	}
+	return ctx.Config().Once(bootImageProfileRuleKey, func() interface{} {
+		tools := global.Tools
 
-	tools := global.Tools
+		rule := android.NewRuleBuilder()
+		rule.MissingDeps(missingDeps)
 
-	rule := android.NewRuleBuilder()
-	rule.MissingDeps(missingDeps)
-
-	var bootImageProfile android.Path
-	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(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,
-		// and if they do they'll get a missing deps error.
-		defaultProfile := "frameworks/base/config/boot-image-profile.txt"
-		path := android.ExistentPathForSource(ctx, defaultProfile)
-		if path.Valid() {
-			bootImageProfile = path.Path()
+		var bootImageProfile android.Path
+		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(global.BootImageProfiles) == 1 {
+			bootImageProfile = global.BootImageProfiles[0]
 		} else {
-			missingDeps = append(missingDeps, defaultProfile)
-			bootImageProfile = android.PathForOutput(ctx, "missing")
+			// 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,
+			// and if they do they'll get a missing deps error.
+			defaultProfile := "frameworks/base/config/boot-image-profile.txt"
+			path := android.ExistentPathForSource(ctx, defaultProfile)
+			if path.Valid() {
+				bootImageProfile = path.Path()
+			} else {
+				missingDeps = append(missingDeps, defaultProfile)
+				bootImageProfile = android.PathForOutput(ctx, "missing")
+			}
 		}
-	}
 
-	profile := image.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=", image.dexPaths.Paths()).
-		FlagForEachArg("--dex-location=", image.dexLocations).
-		FlagWithOutput("--reference-profile-file=", profile)
+		rule.Command().
+			Text(`ANDROID_LOG_TAGS="*:e"`).
+			Tool(tools.Profman).
+			FlagWithInput("--create-profile-from=", bootImageProfile).
+			FlagForEachInput("--apk=", image.dexPaths.Paths()).
+			FlagForEachArg("--dex-location=", image.dexLocations).
+			FlagWithOutput("--reference-profile-file=", profile)
 
-	rule.Install(profile, "/system/etc/boot-image.prof")
+		rule.Install(profile, "/system/etc/boot-image.prof")
 
-	rule.Build(pctx, ctx, "bootJarsProfile", "profile boot jars")
+		rule.Build(pctx, ctx, "bootJarsProfile", "profile boot jars")
 
-	image.profileInstalls = rule.Installs()
+		image.profileInstalls = rule.Installs()
 
-	return profile
+		return profile
+	}).(android.WritablePath)
 }
 
+var bootImageProfileRuleKey = android.NewOnceKey("bootImageProfileRule")
+
 // 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())
-
-			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, " "))
+
+		var imageNames []string
+		for _, current := range append(d.otherImages, image) {
+			imageNames = append(imageNames, current.name)
+			for arch, _ := range current.images {
+				ctx.Strict("DEXPREOPT_IMAGE_VDEX_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.vdexInstalls[arch].String())
+				ctx.Strict("DEXPREOPT_IMAGE_"+current.name+"_"+arch.String(), current.images[arch].String())
+				ctx.Strict("DEXPREOPT_IMAGE_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.installs[arch].String())
+				ctx.Strict("DEXPREOPT_IMAGE_UNSTRIPPED_BUILT_INSTALLED_"+current.name+"_"+arch.String(), current.unstrippedInstalls[arch].String())
+			}
+		}
+		ctx.Strict("DEXPREOPT_IMAGE_NAMES", strings.Join(imageNames, " "))
 	}
 }
diff --git a/java/dexpreopt_config.go b/java/dexpreopt_config.go
index 3d4042b..31a3e26 100644
--- a/java/dexpreopt_config.go
+++ b/java/dexpreopt_config.go
@@ -131,6 +131,52 @@
 
 var defaultBootImageConfigKey = android.NewOnceKey("defaultBootImageConfig")
 
+func apexBootImageConfig(ctx android.PathContext) bootImageConfig {
+	return ctx.Config().Once(apexBootImageConfigKey, func() interface{} {
+		global := dexpreoptGlobalConfig(ctx)
+
+		runtimeModules := global.RuntimeApexJars
+
+		var runtimeBootLocations []string
+
+		for _, m := range runtimeModules {
+			runtimeBootLocations = append(runtimeBootLocations,
+				filepath.Join("/apex/com.android.runtime/javalib", 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 runtimeBootDexPaths android.WritablePaths
+		for _, m := range runtimeModules {
+			runtimeBootDexPaths = append(runtimeBootDexPaths,
+				android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars_input", m+".jar"))
+		}
+
+		dir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars")
+		symbolsDir := android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars_unstripped")
+		images := make(map[android.ArchType]android.OutputPath)
+
+		for _, target := range ctx.Config().Targets[android.Android] {
+			images[target.Arch.ArchType] = dir.Join(ctx,
+				"system/framework", target.Arch.ArchType.String(), "apex.art")
+		}
+
+		return bootImageConfig{
+			name:         "apex",
+			modules:      runtimeModules,
+			dexLocations: runtimeBootLocations,
+			dexPaths:     runtimeBootDexPaths,
+			dir:          dir,
+			symbolsDir:   symbolsDir,
+			images:       images,
+		}
+	}).(bootImageConfig)
+}
+
+var apexBootImageConfigKey = android.NewOnceKey("apexBootImageConfig")
+
 func defaultBootclasspath(ctx android.PathContext) []string {
 	return ctx.Config().OnceStringSlice(defaultBootclasspathKey, func() []string {
 		global := dexpreoptGlobalConfig(ctx)