Merge "Pass --merge-qualifier-annotations to check-api"
diff --git a/apex/apex.go b/apex/apex.go
index 6230236..79b79e8 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -56,12 +56,12 @@
 			`--file_contexts ${file_contexts} ` +
 			`--canned_fs_config ${canned_fs_config} ` +
 			`--payload_type image ` +
-			`--key ${key} ${image_dir} ${out} `,
+			`--key ${key} ${opt_flags} ${image_dir} ${out} `,
 		CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
 			"${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
 			"${soong_zip}", "${zipalign}", "${aapt2}"},
 		Description: "APEX ${image_dir} => ${out}",
-	}, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key")
+	}, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key", "opt_flags")
 
 	zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
 		Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
@@ -518,6 +518,7 @@
 	filesInfo := []apexFile{}
 
 	var keyFile android.Path
+	var pubKeyFile android.Path
 	var certificate java.Certificate
 
 	if a.properties.Payload_type == nil || *a.properties.Payload_type == "image" {
@@ -576,6 +577,12 @@
 			case keyTag:
 				if key, ok := child.(*apexKey); ok {
 					keyFile = key.private_key_file
+					if !key.installable() && ctx.Config().Debuggable() {
+						// If the key is not installed, bundled it with the APEX.
+						// Note: this bundled key is valid only for non-production builds
+						// (eng/userdebug).
+						pubKeyFile = key.public_key_file
+					}
 					return false
 				} else {
 					ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
@@ -640,18 +647,19 @@
 	a.filesInfo = filesInfo
 
 	if a.apexTypes.zip() {
-		a.buildUnflattenedApex(ctx, keyFile, certificate, zipApex)
+		a.buildUnflattenedApex(ctx, keyFile, pubKeyFile, certificate, zipApex)
 	}
 	if a.apexTypes.image() {
 		if ctx.Config().FlattenApex() {
 			a.buildFlattenedApex(ctx)
 		} else {
-			a.buildUnflattenedApex(ctx, keyFile, certificate, imageApex)
+			a.buildUnflattenedApex(ctx, keyFile, pubKeyFile, certificate, imageApex)
 		}
 	}
 }
 
-func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
+func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path,
+	pubKeyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
 	cert := String(a.properties.Certificate)
 	if cert != "" && android.SrcIsModule(cert) == "" {
 		defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
@@ -739,8 +747,14 @@
 		}
 		fileContexts := fileContextsOptionalPath.Path()
 
+		optFlags := []string{}
+
 		// Additional implicit inputs.
 		implicitInputs = append(implicitInputs, cannedFsConfig, fileContexts, keyFile)
+		if pubKeyFile != nil {
+			implicitInputs = append(implicitInputs, pubKeyFile)
+			optFlags = append(optFlags, "--pubkey "+pubKeyFile.String())
+		}
 
 		ctx.Build(pctx, android.BuildParams{
 			Rule:        apexRule,
@@ -755,6 +769,7 @@
 				"file_contexts":    fileContexts.String(),
 				"canned_fs_config": cannedFsConfig.String(),
 				"key":              keyFile.String(),
+				"opt_flags":        strings.Join(optFlags, " "),
 			},
 		})
 
@@ -863,7 +878,7 @@
 					fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
 					fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
 					fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
-					fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
+					fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.builtFile.Base())
 					fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
 					fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
 					fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !a.installable())
@@ -897,7 +912,7 @@
 				fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
 				fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFiles[apexType].String())
 				fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
-				fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexType.suffix())
+				fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", name+apexType.suffix())
 				fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !a.installable())
 				fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
 				fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
diff --git a/apex/apex_test.go b/apex/apex_test.go
index dd5bf70..63d2aab 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -664,5 +664,5 @@
 	ldFlags := ctx.ModuleForTests("not_in_apex", "android_arm64_armv8-a_core").Rule("ld").Args["libFlags"]
 
 	// Ensure that not_in_apex is linking with the static variant of mylib
-	ensureContains(t, ldFlags, "mylib/android_arm64_armv8-a_core_static/mylib.a")
+	ensureContains(t, ldFlags, "mylib/android_arm64_armv8-a_core_static_platform/mylib.a")
 }
diff --git a/apex/key.go b/apex/key.go
index ff348a8..6fbc9b0 100644
--- a/apex/key.go
+++ b/apex/key.go
@@ -45,6 +45,9 @@
 	Public_key *string
 	// Path to the private key file in pem format. Used to sign APEXs.
 	Private_key *string
+
+	// Whether this key is installable to one of the partitions. Defualt: true.
+	Installable *bool
 }
 
 func apexKeyFactory() android.Module {
@@ -54,6 +57,10 @@
 	return module
 }
 
+func (m *apexKey) installable() bool {
+	return m.properties.Installable == nil || proptools.Bool(m.properties.Installable)
+}
+
 func (m *apexKey) DepsMutator(ctx android.BottomUpMutatorContext) {
 }
 
@@ -71,7 +78,9 @@
 	}
 	m.keyName = pubKeyName
 
-	ctx.InstallFile(android.PathForModuleInstall(ctx, "etc/security/apex"), m.keyName, m.public_key_file)
+	if m.installable() {
+		ctx.InstallFile(android.PathForModuleInstall(ctx, "etc/security/apex"), m.keyName, m.public_key_file)
+	}
 }
 
 func (m *apexKey) AndroidMk() android.AndroidMkData {
@@ -82,6 +91,7 @@
 			func(w io.Writer, outputFile android.Path) {
 				fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", "$(TARGET_OUT)/etc/security/apex")
 				fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", m.keyName)
+				fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !m.installable())
 			},
 		},
 	}
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 1f5a8ad..82feec8 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -59,7 +59,7 @@
 
 	ret := android.AndroidMkData{
 		OutputFile: c.outputFile,
-		Required:   c.Properties.AndroidMkRuntimeLibs,
+		Required:   append(c.Properties.AndroidMkRuntimeLibs, c.Properties.ApexesProvidingSharedLibs...),
 		Include:    "$(BUILD_SYSTEM)/soong_cc_prebuilt.mk",
 
 		Extra: []android.AndroidMkExtraFunc{
@@ -76,9 +76,6 @@
 				if len(c.Properties.AndroidMkWholeStaticLibs) > 0 {
 					fmt.Fprintln(w, "LOCAL_WHOLE_STATIC_LIBRARIES := "+strings.Join(c.Properties.AndroidMkWholeStaticLibs, " "))
 				}
-				if len(c.Properties.ApexesProvidingSharedLibs) > 0 {
-					fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES := "+strings.Join(c.Properties.ApexesProvidingSharedLibs, " "))
-				}
 				fmt.Fprintln(w, "LOCAL_SOONG_LINK_TYPE :=", c.getMakeLinkType())
 				if c.useVndk() {
 					fmt.Fprintln(w, "LOCAL_USE_VNDK := true")
diff --git a/cc/library.go b/cc/library.go
index 40c1b4f..da223dc 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -1059,7 +1059,7 @@
 			stubsVersionsFor(mctx.Config())[mctx.ModuleName()] = copiedVersions
 
 			// "" is for the non-stubs variant
-			versions = append(versions, "")
+			versions = append([]string{""}, versions...)
 
 			modules := mctx.CreateVariations(versions...)
 			for i, m := range modules {
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index 6a4fd4a..c24caac 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -83,14 +83,14 @@
 }
 
 type ModuleConfig struct {
-	Name            string
-	DexLocation     string // dex location on device
-	BuildPath       string
-	DexPath         string
-	PreferIntegrity bool
-	UncompressedDex bool
-	HasApkLibraries bool
-	PreoptFlags     []string
+	Name                string
+	DexLocation         string // dex location on device
+	BuildPath           string
+	DexPath             string
+	PreferCodeIntegrity bool
+	UncompressedDex     bool
+	HasApkLibraries     bool
+	PreoptFlags         []string
 
 	ProfileClassListing  string
 	ProfileIsTextListing bool
diff --git a/dexpreopt/dexpreopt_test.go b/dexpreopt/dexpreopt_test.go
index 5265248..fef85a7 100644
--- a/dexpreopt/dexpreopt_test.go
+++ b/dexpreopt/dexpreopt_test.go
@@ -66,7 +66,7 @@
 	DexLocation:            "",
 	BuildPath:              "",
 	DexPath:                "",
-	PreferIntegrity:        false,
+	PreferCodeIntegrity:    false,
 	UncompressedDex:        false,
 	HasApkLibraries:        false,
 	PreoptFlags:            nil,
diff --git a/java/dexpreopt.go b/java/dexpreopt.go
index ae8d369..de9c5f3 100644
--- a/java/dexpreopt.go
+++ b/java/dexpreopt.go
@@ -147,14 +147,14 @@
 	}
 
 	dexpreoptConfig := dexpreopt.ModuleConfig{
-		Name:            ctx.ModuleName(),
-		DexLocation:     dexLocation,
-		BuildPath:       android.PathForModuleOut(ctx, "dexpreopt", ctx.ModuleName()+".jar").String(),
-		DexPath:         dexJarFile.String(),
-		PreferIntegrity: false,
-		UncompressedDex: uncompressedDex,
-		HasApkLibraries: false,
-		PreoptFlags:     nil,
+		Name:                ctx.ModuleName(),
+		DexLocation:         dexLocation,
+		BuildPath:           android.PathForModuleOut(ctx, "dexpreopt", ctx.ModuleName()+".jar").String(),
+		DexPath:             dexJarFile.String(),
+		PreferCodeIntegrity: false,
+		UncompressedDex:     uncompressedDex,
+		HasApkLibraries:     false,
+		PreoptFlags:         nil,
 
 		ProfileClassListing:  profileClassListing.String(),
 		ProfileIsTextListing: profileIsTextListing,
diff --git a/scripts/manifest_fixer.py b/scripts/manifest_fixer.py
index 64f49cb..ebfc4d8 100755
--- a/scripts/manifest_fixer.py
+++ b/scripts/manifest_fixer.py
@@ -61,9 +61,9 @@
                       help='specify additional <uses-library> tag to add. android:requred is set to false')
   parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
                       help='manifest is for a package built against the platform')
-  parser.add_argument('--prefer-integrity', dest='prefer_integrity', action='store_true',
-                      help=('specify if the app prefers strict integrity. Should not be conflict if ' +
-                            'already declared in the manifest.'))
+  parser.add_argument('--prefer-code-integrity', dest='prefer_code_integrity', action='store_true',
+                      help=('specify if the app prefers strict code integrity. Should not be conflict '
+                            'if already declared in the manifest.'))
   parser.add_argument('input', help='input AndroidManifest.xml file')
   parser.add_argument('output', help='output AndroidManifest.xml file')
   return parser.parse_args()
@@ -272,7 +272,7 @@
     application.setAttributeNode(attr)
 
 
-def add_prefer_integrity(doc):
+def add_prefer_code_integrity(doc):
   manifest = parse_manifest(doc)
   elems = get_children_with_tag(manifest, 'application')
   application = elems[0] if len(elems) == 1 else None
@@ -285,13 +285,13 @@
     manifest.insertBefore(doc.createTextNode(indent), first)
     manifest.insertBefore(application, first)
 
-  attr = application.getAttributeNodeNS(android_ns, 'preferIntegrity')
+  attr = application.getAttributeNodeNS(android_ns, 'preferCodeIntegrity')
   if attr is None:
-    attr = doc.createAttributeNS(android_ns, 'android:preferIntegrity')
+    attr = doc.createAttributeNS(android_ns, 'android:preferCodeIntegrity')
     attr.value = 'true'
     application.setAttributeNode(attr)
   elif attr.value != 'true':
-    raise RuntimeError('existing attribute mismatches the option of --prefer-integrity')
+    raise RuntimeError('existing attribute mismatches the option of --prefer-code-integrity')
 
 
 def write_xml(f, doc):
@@ -321,8 +321,8 @@
     if args.uses_non_sdk_api:
       add_uses_non_sdk_api(doc)
 
-    if args.prefer_integrity:
-      add_prefer_integrity(doc)
+    if args.prefer_code_integrity:
+      add_prefer_code_integrity(doc)
 
     with open(args.output, 'wb') as f:
       write_xml(f, doc)
diff --git a/scripts/manifest_fixer_test.py b/scripts/manifest_fixer_test.py
index a621445..edc98cd 100755
--- a/scripts/manifest_fixer_test.py
+++ b/scripts/manifest_fixer_test.py
@@ -346,12 +346,12 @@
     self.assertEqual(output, expected)
 
 
-class PreferIntegrityTest(unittest.TestCase):
-  """Unit tests for add_prefer_integrity function."""
+class PreferCodeIntegrityTest(unittest.TestCase):
+  """Unit tests for add_prefer_code_integrity function."""
 
   def run_test(self, input_manifest):
     doc = minidom.parseString(input_manifest)
-    manifest_fixer.add_prefer_integrity(doc)
+    manifest_fixer.add_prefer_code_integrity(doc)
     output = StringIO.StringIO()
     manifest_fixer.write_xml(output, doc)
     return output.getvalue()
@@ -362,23 +362,23 @@
       '    <application%s/>\n'
       '</manifest>\n')
 
-  def prefer_integrity(self, value):
-    return ' android:preferIntegrity="%s"' % value
+  def prefer_code_integrity(self, value):
+    return ' android:preferCodeIntegrity="%s"' % value
 
   def test_manifest_with_undeclared_preference(self):
     manifest_input = self.manifest_tmpl % ''
-    expected = self.manifest_tmpl % self.prefer_integrity('true')
+    expected = self.manifest_tmpl % self.prefer_code_integrity('true')
     output = self.run_test(manifest_input)
     self.assertEqual(output, expected)
 
-  def test_manifest_with_prefer_integrity(self):
-    manifest_input = self.manifest_tmpl % self.prefer_integrity('true')
+  def test_manifest_with_prefer_code_integrity(self):
+    manifest_input = self.manifest_tmpl % self.prefer_code_integrity('true')
     expected = manifest_input
     output = self.run_test(manifest_input)
     self.assertEqual(output, expected)
 
-  def test_manifest_with_not_prefer_integrity(self):
-    manifest_input = self.manifest_tmpl % self.prefer_integrity('false')
+  def test_manifest_with_not_prefer_code_integrity(self):
+    manifest_input = self.manifest_tmpl % self.prefer_code_integrity('false')
     self.assertRaises(RuntimeError, self.run_test, manifest_input)
 
 if __name__ == '__main__':