Merge "Reverse merge order of resources and implementation"
diff --git a/android/neverallow.go b/android/neverallow.go
index fba43b3..9314483 100644
--- a/android/neverallow.go
+++ b/android/neverallow.go
@@ -97,32 +97,15 @@
 		"external/wycheproof",
 	}
 
-	var coreModules = []string{
-		"core-all",
-		"core-oj",
-		"core-libart",
-		"okhttp",
-		"bouncycastle",
-		"conscrypt",
-		"apache-xml",
-	}
-
-	// Core library constraints. Prevent targets adding dependencies on core
-	// library internals, which could lead to compatibility issues with the ART
-	// mainline module. They should use core.platform.api.stubs instead.
+	// Core library constraints. The no_standard_libs can only be used in core
+	// library projects. Access to core library targets is restricted using
+	// visibility rules.
 	rules := []*rule{
 		neverallow().
 			notIn(append(coreLibraryProjects, "development")...).
 			with("no_standard_libs", "true"),
 	}
 
-	for _, m := range coreModules {
-		r := neverallow().
-			notIn(coreLibraryProjects...).
-			with("libs", m).
-			because("Only core libraries projects can depend on " + m)
-		rules = append(rules, r)
-	}
 	return rules
 }
 
diff --git a/android/neverallow_test.go b/android/neverallow_test.go
index d55ca57..00c51ea 100644
--- a/android/neverallow_test.go
+++ b/android/neverallow_test.go
@@ -138,17 +138,6 @@
 		expectedError: "",
 	},
 	{
-		name: "dependency on core-libart",
-		fs: map[string][]byte{
-			"Blueprints": []byte(`
-				java_library {
-					name: "needs_core_libart",
-					libs: ["core-libart"],
-				}`),
-		},
-		expectedError: "Only core libraries projects can depend on core-libart",
-	},
-	{
 		name: "java_device_for_host",
 		fs: map[string][]byte{
 			"Blueprints": []byte(`
diff --git a/android/paths.go b/android/paths.go
index 0f20b84..da387a8 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -967,7 +967,7 @@
 // PathForVndkRefAbiDump returns an OptionalPath representing the path of the
 // reference abi dump for the given module. This is not guaranteed to be valid.
 func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
-	isLlndk, isGzip bool) OptionalPath {
+	isLlndkOrNdk, isVndk, isGzip bool) OptionalPath {
 
 	arches := ctx.DeviceConfig().Arches()
 	if len(arches) == 0 {
@@ -980,10 +980,12 @@
 	}
 
 	var dirName string
-	if isLlndk {
+	if isLlndkOrNdk {
 		dirName = "ndk"
-	} else {
+	} else if isVndk {
 		dirName = "vndk"
+	} else {
+		dirName = "platform" // opt-in libs
 	}
 
 	binderBitness := ctx.DeviceConfig().BinderBitness()
diff --git a/android/prebuilt.go b/android/prebuilt.go
index df25a89..2556770 100644
--- a/android/prebuilt.go
+++ b/android/prebuilt.go
@@ -74,6 +74,10 @@
 	}
 }
 
+func (p *Prebuilt) UsePrebuilt() bool {
+	return p.properties.UsePrebuilt
+}
+
 func InitPrebuiltModule(module PrebuiltInterface, srcs *[]string) {
 	p := module.Prebuilt()
 	module.AddProperties(&p.properties)
diff --git a/apex/apex.go b/apex/apex.go
index 509e0f2..68d0bc1 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -1184,8 +1184,11 @@
 			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
 		} else if fi.class == nativeSharedLib || fi.class == nativeExecutable {
 			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.builtFile.Base())
-			if cc, ok := fi.module.(*cc.Module); ok && cc.UnstrippedOutputFile() != nil {
-				fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", cc.UnstrippedOutputFile().String())
+			if cc, ok := fi.module.(*cc.Module); ok {
+				if cc.UnstrippedOutputFile() != nil {
+					fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", cc.UnstrippedOutputFile().String())
+				}
+				cc.AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
 			}
 			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_cc_prebuilt.mk")
 		} else {
@@ -1373,11 +1376,15 @@
 	return android.Paths{p.outputApex}
 }
 
+func (p *Prebuilt) InstallFilename() string {
+	return proptools.StringDefault(p.properties.Filename, p.BaseModuleName()+imageApexSuffix)
+}
+
 func (p *Prebuilt) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	// TODO(jungjw): Check the key validity.
 	p.inputApex = p.Prebuilt().SingleSourcePath(ctx)
 	p.installDir = android.PathForModuleInstall(ctx, "apex")
-	p.installFilename = proptools.StringDefault(p.properties.Filename, ctx.ModuleName()+imageApexSuffix)
+	p.installFilename = p.InstallFilename()
 	if !strings.HasSuffix(p.installFilename, imageApexSuffix) {
 		ctx.ModuleErrorf("filename should end in %s for prebuilt_apex", imageApexSuffix)
 	}
diff --git a/apex/key.go b/apex/key.go
index 229d593..08cd45e 100644
--- a/apex/key.go
+++ b/apex/key.go
@@ -16,6 +16,7 @@
 
 import (
 	"fmt"
+	"sort"
 	"strings"
 
 	"android/soong/android"
@@ -105,12 +106,31 @@
 
 func (s *apexKeysText) GenerateBuildActions(ctx android.SingletonContext) {
 	s.output = android.PathForOutput(ctx, "apexkeys.txt")
-	var filecontent strings.Builder
+	apexModulesMap := make(map[string]android.Module)
 	ctx.VisitAllModules(func(module android.Module) {
-		if m, ok := module.(android.Module); ok && !m.Enabled() {
-			return
+		if m, ok := module.(*apexBundle); ok && m.Enabled() && m.installable() {
+			apexModulesMap[m.Name()] = m
 		}
+	})
 
+	// Find prebuilts and let them override apexBundle if they are preferred
+	ctx.VisitAllModules(func(module android.Module) {
+		if m, ok := module.(*Prebuilt); ok && m.Enabled() && m.installable() &&
+			m.Prebuilt().UsePrebuilt() {
+			apexModulesMap[m.BaseModuleName()] = m
+		}
+	})
+
+	// iterating over map does not give consistent ordering in golang
+	var moduleNames []string
+	for key, _ := range apexModulesMap {
+		moduleNames = append(moduleNames, key)
+	}
+	sort.Strings(moduleNames)
+
+	var filecontent strings.Builder
+	for _, key := range moduleNames {
+		module := apexModulesMap[key]
 		if m, ok := module.(*apexBundle); ok {
 			fmt.Fprintf(&filecontent,
 				"name=%q public_key=%q private_key=%q container_certificate=%q container_private_key=%q\\n",
@@ -119,8 +139,14 @@
 				m.private_key_file.String(),
 				m.container_certificate_file.String(),
 				m.container_private_key_file.String())
+		} else if m, ok := module.(*Prebuilt); ok {
+			fmt.Fprintf(&filecontent,
+				"name=%q public_key=%q private_key=%q container_certificate=%q container_private_key=%q\\n",
+				m.InstallFilename(),
+				"PRESIGNED", "PRESIGNED", "PRESIGNED", "PRESIGNED")
 		}
-	})
+	}
+
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        android.WriteFile,
 		Description: "apexkeys.txt",
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 02806f9..79469ee 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -145,6 +145,16 @@
 	}
 }
 
+func (library *libraryDecorator) androidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
+	if library.sAbiOutputFile.Valid() {
+		fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES +=", library.sAbiOutputFile.String())
+		if library.sAbiDiff.Valid() && !library.static() {
+			fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES +=", library.sAbiDiff.String())
+			fmt.Fprintln(w, "HEADER_ABI_DIFFS +=", library.sAbiDiff.String())
+		}
+	}
+}
+
 func (library *libraryDecorator) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
 	if library.static() {
 		ret.Class = "STATIC_LIBRARIES"
@@ -169,14 +179,7 @@
 	ret.DistFile = library.distFile
 	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
 		library.androidMkWriteExportedFlags(w)
-		fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES := ")
-		if library.sAbiOutputFile.Valid() {
-			fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES += ", library.sAbiOutputFile.String())
-			if library.sAbiDiff.Valid() && !library.static() {
-				fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES += ", library.sAbiDiff.String())
-				fmt.Fprintln(w, "HEADER_ABI_DIFFS += ", library.sAbiDiff.String())
-			}
-		}
+		library.androidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
 
 		_, _, ext := splitFileExt(outputFile.Base())
 
diff --git a/cc/cc.go b/cc/cc.go
index bec39ca..0f5c68a 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -19,6 +19,7 @@
 // is handled in builder.go
 
 import (
+	"io"
 	"strconv"
 	"strings"
 
@@ -1966,6 +1967,14 @@
 	dpInfo.Srcs = append(dpInfo.Srcs, c.Srcs().Strings()...)
 }
 
+func (c *Module) AndroidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
+	if c.linker != nil {
+		if library, ok := c.linker.(*libraryDecorator); ok {
+			library.androidMkWriteAdditionalDependenciesForSourceAbiDiff(w)
+		}
+	}
+}
+
 //
 // Defaults
 //
diff --git a/cc/library.go b/cc/library.go
index 13972cc..1f79bec 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -15,6 +15,7 @@
 package cc
 
 import (
+	"io"
 	"path/filepath"
 	"regexp"
 	"sort"
@@ -96,6 +97,9 @@
 
 	// Properties for ABI compatibility checker
 	Header_abi_checker struct {
+		// Enable ABI checks (even if this is not an LLNDK/VNDK lib)
+		Enabled *bool
+
 		// Path to a symbol file that specifies the symbols to be included in the generated
 		// ABI dump file
 		Symbol_file *string `android:"path"`
@@ -421,6 +425,13 @@
 	return exportedIncludes
 }
 
+func (library *libraryDecorator) shouldCreateVndkSourceAbiDump(ctx ModuleContext) bool {
+	if library.Properties.Header_abi_checker.Enabled != nil {
+		return Bool(library.Properties.Header_abi_checker.Enabled)
+	}
+	return ctx.shouldCreateVndkSourceAbiDump()
+}
+
 func (library *libraryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects {
 	if library.buildStubs() {
 		objs, versionScript := compileStubLibrary(ctx, flags, String(library.Properties.Stubs.Symbol_file), library.MutatedProperties.StubsVersion, "--apex")
@@ -440,7 +451,7 @@
 		}
 		return Objects{}
 	}
-	if ctx.shouldCreateVndkSourceAbiDump() || library.sabi.Properties.CreateSAbiDumps {
+	if library.shouldCreateVndkSourceAbiDump(ctx) || library.sabi.Properties.CreateSAbiDumps {
 		exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
 		var SourceAbiFlags []string
 		for _, dir := range exportIncludeDirs.Strings() {
@@ -487,6 +498,9 @@
 	// Sets whether a specific variant is static or shared
 	setStatic()
 	setShared()
+
+	// Write LOCAL_ADDITIONAL_DEPENDENCIES for ABI diff
+	androidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer)
 }
 
 func (library *libraryDecorator) getLibName(ctx ModuleContext) string {
@@ -769,10 +783,10 @@
 }
 
 func getRefAbiDumpFile(ctx ModuleContext, vndkVersion, fileName string) android.Path {
-	isLlndk := inList(ctx.baseModuleName(), llndkLibraries) || inList(ctx.baseModuleName(), ndkMigratedLibs)
+	isLlndkOrNdk := inList(ctx.baseModuleName(), llndkLibraries) || inList(ctx.baseModuleName(), ndkMigratedLibs)
 
-	refAbiDumpTextFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndk, false)
-	refAbiDumpGzipFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndk, true)
+	refAbiDumpTextFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndkOrNdk, ctx.isVndk(), false)
+	refAbiDumpGzipFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndkOrNdk, ctx.isVndk(), true)
 
 	if refAbiDumpTextFile.Valid() {
 		if refAbiDumpGzipFile.Valid() {
@@ -790,7 +804,7 @@
 }
 
 func (library *libraryDecorator) linkSAbiDumpFiles(ctx ModuleContext, objs Objects, fileName string, soFile android.Path) {
-	if len(objs.sAbiDumpFiles) > 0 && ctx.shouldCreateVndkSourceAbiDump() {
+	if len(objs.sAbiDumpFiles) > 0 && library.shouldCreateVndkSourceAbiDump(ctx) {
 		vndkVersion := ctx.DeviceConfig().PlatformVndkVersion()
 		if ver := ctx.DeviceConfig().VndkVersion(); ver != "" && ver != "current" {
 			vndkVersion = ver
diff --git a/cmd/diff_target_files/known_nondeterminism.whitelist b/cmd/diff_target_files/known_nondeterminism.whitelist
index 6d71403..a8ade49 100644
--- a/cmd/diff_target_files/known_nondeterminism.whitelist
+++ b/cmd/diff_target_files/known_nondeterminism.whitelist
@@ -3,8 +3,6 @@
 [
   {
     "Paths": [
-       // b/120039850
-      "system/framework/oat/*/services.art"
     ]
   }
 ]
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index f1fa0ff..3b77042 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -59,6 +59,7 @@
 	NeverAllowStripping bool // whether stripping should not be done - used as build time check to make sure dex files are always available
 
 	NoDebugInfo                 bool // don't generate debug info by default
+	DontResolveStartupStrings   bool // don't resolve string literals loaded during application startup.
 	AlwaysSystemServerDebugInfo bool // always generate mini debug info for system server modules (overrides NoDebugInfo=true)
 	NeverSystemServerDebugInfo  bool // never generate mini debug info for system server modules (overrides NoDebugInfo=false)
 	AlwaysOtherDebugInfo        bool // always generate mini debug info for non-system server modules (overrides NoDebugInfo=true)
@@ -301,6 +302,7 @@
 		GenerateDMFiles:                    false,
 		NeverAllowStripping:                false,
 		NoDebugInfo:                        false,
+		DontResolveStartupStrings:          false,
 		AlwaysSystemServerDebugInfo:        false,
 		NeverSystemServerDebugInfo:         false,
 		AlwaysOtherDebugInfo:               false,
diff --git a/dexpreopt/dexpreopt.go b/dexpreopt/dexpreopt.go
index 01ee15e..5b658d9 100644
--- a/dexpreopt/dexpreopt.go
+++ b/dexpreopt/dexpreopt.go
@@ -461,6 +461,9 @@
 		appImageInstallPath := pathtools.ReplaceExtension(odexInstallPath, "art")
 		cmd.FlagWithOutput("--app-image-file=", appImagePath).
 			FlagWithArg("--image-format=", "lz4")
+		if !global.DontResolveStartupStrings {
+			cmd.FlagWithArg("--resolve-startup-const-strings=", "true")
+		}
 		rule.Install(appImagePath, appImageInstallPath)
 	}
 
diff --git a/java/OWNERS b/java/OWNERS
index d68a5b0..16ef4d8 100644
--- a/java/OWNERS
+++ b/java/OWNERS
@@ -1 +1 @@
-per-file dexpreopt.go = ngeoffray@google.com,calin@google.com,mathieuc@google.com
+per-file dexpreopt*.go = ngeoffray@google.com,calin@google.com,mathieuc@google.com
diff --git a/java/dexpreopt_config.go b/java/dexpreopt_config.go
index b30bd00..a0b1ea5 100644
--- a/java/dexpreopt_config.go
+++ b/java/dexpreopt_config.go
@@ -138,21 +138,29 @@
 		global := dexpreoptGlobalConfig(ctx)
 
 		runtimeModules := global.RuntimeApexJars
+		nonFrameworkModules := concat(runtimeModules, global.ProductUpdatableBootModules)
+		frameworkModules := android.RemoveListFromList(global.BootJars, nonFrameworkModules)
+		imageModules := concat(runtimeModules, frameworkModules)
 
-		var runtimeBootLocations []string
+		var bootLocations []string
 
 		for _, m := range runtimeModules {
-			runtimeBootLocations = append(runtimeBootLocations,
+			bootLocations = append(bootLocations,
 				filepath.Join("/apex/com.android.runtime/javalib", m+".jar"))
 		}
 
+		for _, m := range frameworkModules {
+			bootLocations = append(bootLocations,
+				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 runtimeBootDexPaths android.WritablePaths
-		for _, m := range runtimeModules {
-			runtimeBootDexPaths = append(runtimeBootDexPaths,
+		var bootDexPaths android.WritablePaths
+		for _, m := range imageModules {
+			bootDexPaths = append(bootDexPaths,
 				android.PathForOutput(ctx, ctx.Config().DeviceName(), "dex_apexjars_input", m+".jar"))
 		}
 
@@ -167,9 +175,9 @@
 
 		return bootImageConfig{
 			name:         "apex",
-			modules:      runtimeModules,
-			dexLocations: runtimeBootLocations,
-			dexPaths:     runtimeBootDexPaths,
+			modules:      imageModules,
+			dexLocations: bootLocations,
+			dexPaths:     bootDexPaths,
 			dir:          dir,
 			symbolsDir:   symbolsDir,
 			images:       images,