Merge changes from topic "soong_instrumentation_for"

* changes:
  Fix instrumentation_for to match LOCAL_INSTRUMENTATION_FOR
  Fix incremental build issue in aapt2
  Support main_class property in java_binary modules
  Always allow duplicates with identical CRC32 and size
diff --git a/Android.bp b/Android.bp
index 2037818..bdc34d0 100644
--- a/Android.bp
+++ b/Android.bp
@@ -348,6 +348,7 @@
     ],
     srcs: [
         "apex/apex.go",
+        "apex/key.go",
     ],
     pluginFor: ["soong_build"],
 }
diff --git a/apex/apex.go b/apex/apex.go
index 68d9cb8..619ac33 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -75,6 +75,7 @@
 	executableTag = dependencyTag{name: "executable"}
 	javaLibTag    = dependencyTag{name: "javaLib"}
 	prebuiltTag   = dependencyTag{name: "prebuilt"}
+	keyTag        = dependencyTag{name: "key"}
 )
 
 func init() {
@@ -172,6 +173,9 @@
 
 	// List of prebuilt files that are embedded inside this APEX bundle
 	Prebuilts []string
+
+	// Name of the apex_key module that provides the private key to sign APEX
+	Key *string
 }
 
 type apexBundle struct {
@@ -185,14 +189,6 @@
 }
 
 func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
-	// Native shared libs are added for all architectures of the device
-	// i.e., native_shared_lib_modules: ["libc"] adds both 64 and 32 variation
-	// of the module
-	arches := ctx.DeviceConfig().Arches()
-	if len(arches) == 0 {
-		panic("device build with no primary arch")
-	}
-
 	for _, arch := range ctx.MultiTargets() {
 		// Use *FarVariation* to be able to depend on modules having
 		// conflicting variations with this module. This is required since
@@ -208,16 +204,21 @@
 			{Mutator: "arch", Variation: arch.String()},
 			{Mutator: "image", Variation: "core"},
 		}, executableTag, a.properties.Binaries...)
-
-		ctx.AddFarVariationDependencies([]blueprint.Variation{
-			{Mutator: "arch", Variation: "android_common"},
-		}, javaLibTag, a.properties.Java_libs...)
-
-		ctx.AddFarVariationDependencies([]blueprint.Variation{
-			{Mutator: "arch", Variation: "android_common"},
-		}, prebuiltTag, a.properties.Prebuilts...)
 	}
 
+	ctx.AddFarVariationDependencies([]blueprint.Variation{
+		{Mutator: "arch", Variation: "android_common"},
+	}, javaLibTag, a.properties.Java_libs...)
+
+	ctx.AddFarVariationDependencies([]blueprint.Variation{
+		{Mutator: "arch", Variation: "android_common"},
+	}, prebuiltTag, a.properties.Prebuilts...)
+
+	if String(a.properties.Key) == "" {
+		ctx.ModuleErrorf("key is missing")
+		return
+	}
+	ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
 }
 
 func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
@@ -259,34 +260,52 @@
 	// files to copy -> dir in apex
 	copyManifest := make(map[android.Path]string)
 
+	var keyFile android.Path
+
 	ctx.WalkDeps(func(child, parent android.Module) bool {
 		if _, ok := parent.(*apexBundle); ok {
 			// direct dependencies
 			depTag := ctx.OtherModuleDependencyTag(child)
+			depName := ctx.OtherModuleName(child)
 			switch depTag {
 			case sharedLibTag:
 				if cc, ok := child.(*cc.Module); ok {
 					fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
 					copyManifest[fileToCopy] = dirInApex
 					return true
+				} else {
+					ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
 				}
 			case executableTag:
 				if cc, ok := child.(*cc.Module); ok {
 					fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
 					copyManifest[fileToCopy] = dirInApex
 					return true
+				} else {
+					ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
 				}
 			case javaLibTag:
 				if java, ok := child.(*java.Library); ok {
 					fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
 					copyManifest[fileToCopy] = dirInApex
 					return true
+				} else {
+					ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
 				}
 			case prebuiltTag:
 				if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
 					fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
 					copyManifest[fileToCopy] = dirInApex
 					return true
+				} else {
+					ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
+				}
+			case keyTag:
+				if key, ok := child.(*apexKey); ok {
+					keyFile = key.private_key_file
+					return false
+				} else {
+					ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
 				}
 			}
 		} else {
@@ -330,8 +349,6 @@
 
 	manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
 	fileContexts := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.File_contexts, "file_contexts"))
-	// TODO(b/114488804) make this customizable
-	key := android.PathForSource(ctx, "system/apex/apexer/testdata/testkey.pem")
 
 	a.outputFile = android.PathForModuleOut(ctx, a.ModuleBase.Name()+apexSuffix)
 
@@ -351,7 +368,7 @@
 		copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
 	}
 	implicitInputs := append(android.Paths(nil), filesToCopy...)
-	implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, key)
+	implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
 	outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
 	prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
 	ctx.ModuleBuild(pctx, android.ModuleBuildParams{
@@ -365,7 +382,7 @@
 			"manifest":         manifest.String(),
 			"file_contexts":    fileContexts.String(),
 			"canned_fs_config": cannedFsConfig.String(),
-			"key":              key.String(),
+			"key":              keyFile.String(),
 		},
 	})
 
@@ -382,6 +399,7 @@
 			fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
 			fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
 			fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
+			fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
 			fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
 		}}
 }
diff --git a/apex/key.go b/apex/key.go
new file mode 100644
index 0000000..ff348a8
--- /dev/null
+++ b/apex/key.go
@@ -0,0 +1,88 @@
+// Copyright (C) 2018 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package apex
+
+import (
+	"fmt"
+	"io"
+
+	"android/soong/android"
+	"github.com/google/blueprint/proptools"
+)
+
+var String = proptools.String
+
+func init() {
+	android.RegisterModuleType("apex_key", apexKeyFactory)
+}
+
+type apexKey struct {
+	android.ModuleBase
+
+	properties apexKeyProperties
+
+	public_key_file  android.Path
+	private_key_file android.Path
+
+	keyName string
+}
+
+type apexKeyProperties struct {
+	// Path to the public key file in avbpubkey format. Installed to the device.
+	// Base name of the file is used as the ID for the key.
+	Public_key *string
+	// Path to the private key file in pem format. Used to sign APEXs.
+	Private_key *string
+}
+
+func apexKeyFactory() android.Module {
+	module := &apexKey{}
+	module.AddProperties(&module.properties)
+	android.InitAndroidModule(module)
+	return module
+}
+
+func (m *apexKey) DepsMutator(ctx android.BottomUpMutatorContext) {
+}
+
+func (m *apexKey) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	m.public_key_file = android.PathForModuleSrc(ctx, String(m.properties.Public_key))
+	m.private_key_file = android.PathForModuleSrc(ctx, String(m.properties.Private_key))
+
+	pubKeyName := m.public_key_file.Base()[0 : len(m.public_key_file.Base())-len(m.public_key_file.Ext())]
+	privKeyName := m.private_key_file.Base()[0 : len(m.private_key_file.Base())-len(m.private_key_file.Ext())]
+
+	if pubKeyName != privKeyName {
+		ctx.ModuleErrorf("public_key %q (keyname:%q) and private_key %q (keyname:%q) do not have same keyname",
+			m.public_key_file.String(), pubKeyName, m.private_key_file, privKeyName)
+		return
+	}
+	m.keyName = pubKeyName
+
+	ctx.InstallFile(android.PathForModuleInstall(ctx, "etc/security/apex"), m.keyName, m.public_key_file)
+}
+
+func (m *apexKey) AndroidMk() android.AndroidMkData {
+	return android.AndroidMkData{
+		Class:      "ETC",
+		OutputFile: android.OptionalPathForPath(m.public_key_file),
+		Extra: []android.AndroidMkExtraFunc{
+			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)
+			},
+		},
+	}
+}
diff --git a/build_test.bash b/build_test.bash
index 4c43224..ee979e7 100755
--- a/build_test.bash
+++ b/build_test.bash
@@ -27,6 +27,10 @@
 # that's detected in the Go code, which skips calculating the startup time.
 export TRACE_BEGIN_SOONG=$(date +%s%N)
 
+# Remove BUILD_NUMBER so that incremental builds on build servers don't
+# re-read makefiles every time.
+unset BUILD_NUMBER
+
 export TOP=$(cd $(dirname ${BASH_SOURCE[0]})/../..; PWD= /bin/pwd)
 cd "${TOP}"
 source "${TOP}/build/soong/scripts/microfactory.bash"
diff --git a/cc/config/clang.go b/cc/config/clang.go
index 5cf2421..b58223f 100644
--- a/cc/config/clang.go
+++ b/cc/config/clang.go
@@ -92,12 +92,7 @@
 	"-Wl,-m,aarch64_elf64_le_vec",
 })
 
-var ClangLibToolingUnknownCflags = []string{
-	// Remove -flto and other flto dependent flags.
-	"-flto*",
-	"-fsanitize*",
-	"-fwhole-program-vtables",
-}
+var ClangLibToolingUnknownCflags []string = nil
 
 func init() {
 	pctx.StaticVariable("ClangExtraCflags", strings.Join([]string{
diff --git a/cc/sabi.go b/cc/sabi.go
index 72a3c5c..4a86499 100644
--- a/cc/sabi.go
+++ b/cc/sabi.go
@@ -73,17 +73,6 @@
 	flags.ToolingCFlags = filterOutWithPrefix(flags.CFlags, config.ClangLibToolingUnknownCflags)
 	flags.ToolingCppFlags = filterOutWithPrefix(flags.CppFlags, config.ClangLibToolingUnknownCflags)
 
-	// RSClang does not support recent mcpu option likes exynos-m2.
-	// So we need overriding mcpu option when we want to use it.
-	mappedArch := map[string]string{
-		"exynos-m2":  "cortex-a53",
-		"cortex-a55": "cortex-a53",
-		"cortex-a75": "cortex-a57",
-	}
-	if arch, ok := mappedArch[ctx.Arch().CpuVariant]; ok {
-		flags.ToolingCFlags = append(flags.ToolingCFlags, "-mcpu="+arch)
-	}
-
 	return flags
 }
 
diff --git a/cc/vndk.go b/cc/vndk.go
index 5a24a98..1a9b77a 100644
--- a/cc/vndk.go
+++ b/cc/vndk.go
@@ -15,6 +15,7 @@
 package cc
 
 import (
+	"errors"
 	"sort"
 	"strings"
 	"sync"
@@ -151,38 +152,42 @@
 	}
 
 	// Check the dependencies of VNDK shared libraries.
-	if !vndkIsVndkDepAllowed(vndk, to.vndkdep) {
-		ctx.ModuleErrorf("(%s) should not link to %q (%s)",
-			vndk.typeName(), to.Name(), to.vndkdep.typeName())
+	if err := vndkIsVndkDepAllowed(vndk, to.vndkdep); err != nil {
+		ctx.ModuleErrorf("(%s) should not link to %q (%s): %v",
+			vndk.typeName(), to.Name(), to.vndkdep.typeName(), err)
 		return
 	}
 }
 
-func vndkIsVndkDepAllowed(from *vndkdep, to *vndkdep) bool {
+func vndkIsVndkDepAllowed(from *vndkdep, to *vndkdep) error {
 	// Check the dependencies of VNDK, VNDK-Ext, VNDK-SP, VNDK-SP-Ext and vendor modules.
 	if from.isVndkExt() {
 		if from.isVndkSp() {
-			// VNDK-SP-Ext may depend on VNDK-SP, VNDK-SP-Ext, or vendor libs (excluding
-			// VNDK and VNDK-Ext).
-			return to.isVndkSp() || !to.isVndk()
+			if to.isVndk() && !to.isVndkSp() {
+				return errors.New("VNDK-SP extensions must not depend on VNDK or VNDK extensions")
+			}
+			return nil
 		}
 		// VNDK-Ext may depend on VNDK, VNDK-Ext, VNDK-SP, VNDK-SP-Ext, or vendor libs.
-		return true
+		return nil
 	}
 	if from.isVndk() {
 		if to.isVndkExt() {
-			// VNDK-core and VNDK-SP must not depend on VNDK extensions.
-			return false
+			return errors.New("VNDK-core and VNDK-SP must not depend on VNDK extensions")
 		}
 		if from.isVndkSp() {
-			// VNDK-SP must only depend on VNDK-SP.
-			return to.isVndkSp()
+			if !to.isVndkSp() {
+				return errors.New("VNDK-SP must only depend on VNDK-SP")
+			}
+			return nil
 		}
-		// VNDK-core may depend on VNDK-core or VNDK-SP.
-		return to.isVndk()
+		if !to.isVndk() {
+			return errors.New("VNDK-core must only depend on VNDK-core or VNDK-SP")
+		}
+		return nil
 	}
 	// Vendor modules may depend on VNDK, VNDK-Ext, VNDK-SP, VNDK-SP-Ext, or vendor libs.
-	return true
+	return nil
 }
 
 var (
diff --git a/java/config/config.go b/java/config/config.go
index 85cb588..d2a8c46 100644
--- a/java/config/config.go
+++ b/java/config/config.go
@@ -27,8 +27,8 @@
 var (
 	pctx = android.NewPackageContext("android/soong/java/config")
 
-	DefaultBootclasspathLibraries = []string{"core-oj", "core-libart", "core-simple", "bouncycastle", "conscrypt", "okhttp"}
-	DefaultSystemModules          = "core-system-modules"
+	DefaultBootclasspathLibraries = []string{"core.platform.api.stubs", "core-lambda-stubs"}
+	DefaultSystemModules          = "core-platform-api-stubs-system-modules"
 	DefaultLibraries              = []string{"ext", "framework"}
 	DefaultLambdaStubsLibrary     = "core-lambda-stubs"
 	SdkLambdaStubsPath            = "prebuilts/sdk/tools/core-lambda-stubs.jar"
diff --git a/java/java_test.go b/java/java_test.go
index 76244f0..86349fe 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -111,19 +111,14 @@
 	ctx.Register()
 
 	extraModules := []string{
-		"core-oj",
-		"core-libart",
 		"core-lambda-stubs",
-		"core-simple",
-		"bouncycastle",
-		"conscrypt",
-		"okhttp",
 		"framework",
 		"ext",
 		"android_stubs_current",
 		"android_system_stubs_current",
 		"android_test_stubs_current",
 		"core.current.stubs",
+		"core.platform.api.stubs",
 		"kotlin-stdlib",
 	}
 
@@ -134,7 +129,7 @@
 				srcs: ["a.java"],
 				no_standard_libs: true,
 				sdk_version: "core_current",
-				system_modules: "core-system-modules",
+				system_modules: "core-platform-api-stubs-system-modules",
 			}
 		`, extra)
 	}
@@ -148,6 +143,7 @@
 
 	systemModules := []string{
 		"core-system-modules",
+		"core-platform-api-stubs-system-modules",
 		"android_stubs_current_system_modules",
 		"android_system_stubs_current_system_modules",
 		"android_test_stubs_current_system_modules",
@@ -367,15 +363,15 @@
 }{
 	{
 		name:          "default",
-		bootclasspath: []string{"core-oj", "core-libart", "core-simple", "bouncycastle", "conscrypt", "okhttp"},
-		system:        "core-system-modules",
+		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
+		system:        "core-platform-api-stubs-system-modules",
 		classpath:     []string{"ext", "framework"},
 	},
 	{
 		name:          "blank sdk version",
 		properties:    `sdk_version: "",`,
-		bootclasspath: []string{"core-oj", "core-libart", "core-simple", "bouncycastle", "conscrypt", "okhttp"},
-		system:        "core-system-modules",
+		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
+		system:        "core-platform-api-stubs-system-modules",
 		classpath:     []string{"ext", "framework"},
 	},
 	{
@@ -433,8 +429,8 @@
 	{
 
 		name:          "nostdlib system_modules",
-		properties:    `no_standard_libs: true, system_modules: "core-system-modules"`,
-		system:        "core-system-modules",
+		properties:    `no_standard_libs: true, system_modules: "core-platform-api-stubs-system-modules"`,
+		system:        "core-platform-api-stubs-system-modules",
 		bootclasspath: []string{`""`},
 		classpath:     []string{},
 	},
diff --git a/python/scripts/stub_template_host.txt b/python/scripts/stub_template_host.txt
index e686211..213401d 100644
--- a/python/scripts/stub_template_host.txt
+++ b/python/scripts/stub_template_host.txt
@@ -41,6 +41,7 @@
   args = sys.argv[1:]
 
   new_env = {}
+  runfiles_path = None
 
   try:
     runfiles_path = ExtractRunfiles()
@@ -82,7 +83,8 @@
   except:
     raise
   finally:
-    shutil.rmtree(runfiles_path, True)
+    if runfiles_path is not None:
+      shutil.rmtree(runfiles_path, True)
 
 if __name__ == '__main__':
   Main()
diff --git a/scripts/manifest_fixer.py b/scripts/manifest_fixer.py
index 05bd66e..9256cb2 100755
--- a/scripts/manifest_fixer.py
+++ b/scripts/manifest_fixer.py
@@ -56,7 +56,9 @@
   parser.add_argument('--library', dest='library', action='store_true',
                       help='manifest is for a static library')
   parser.add_argument('--uses-library', dest='uses_libraries', action='append',
-                      help='specify additional <uses-library> tag to add')
+                      help='specify additional <uses-library> tag to add. android:requred is set to true')
+  parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
+                      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('input', help='input AndroidManifest.xml file')
@@ -190,12 +192,13 @@
     element.setAttributeNode(target_attr)
 
 
-def add_uses_libraries(doc, new_uses_libraries):
-  """Add additional <uses-library> tags with android:required=false.
+def add_uses_libraries(doc, new_uses_libraries, required):
+  """Add additional <uses-library> tags
 
   Args:
     doc: The XML document. May be modified by this function.
     new_uses_libraries: The names of libraries to be added by this function.
+    required: The value of android:required attribute. Can be true or false.
   Raises:
     RuntimeError: Invalid manifest
   """
@@ -227,7 +230,7 @@
 
     ul = doc.createElement('uses-library')
     ul.setAttributeNS(android_ns, 'android:name', name)
-    ul.setAttributeNS(android_ns, 'android:required', 'false')
+    ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
 
     application.insertBefore(doc.createTextNode(indent), last)
     application.insertBefore(ul, last)
@@ -285,7 +288,10 @@
       raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
 
     if args.uses_libraries:
-      add_uses_libraries(doc, args.uses_libraries)
+      add_uses_libraries(doc, args.uses_libraries, True)
+
+    if args.optional_uses_libraries:
+      add_uses_libraries(doc, args.optional_uses_libraries, False)
 
     if args.uses_non_sdk_api:
       add_uses_non_sdk_api(doc)
diff --git a/scripts/strip.sh b/scripts/strip.sh
index 29594dc..4634c18 100755
--- a/scripts/strip.sh
+++ b/scripts/strip.sh
@@ -98,6 +98,7 @@
         else
             "${CROSS_COMPILE}objcopy" --add-section .gnu_debugdata="${outfile}.mini_debuginfo.xz" "${outfile}.tmp"
         fi
+        rm -f "${outfile}.dynsyms" "${outfile}.funcsyms" "${outfile}.keep_symbols" "${outfile}.debug" "${outfile}.mini_debuginfo" "${outfile}.mini_debuginfo.xz"
     else
         cp -f "${infile}" "${outfile}.tmp"
     fi
diff --git a/ui/build/config.go b/ui/build/config.go
index d470b96..d65d97f 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -86,6 +86,9 @@
 		ret.environ.Set("OUT_DIR", outDir)
 	}
 
+	// Make sure DIST_DIR is set appropriately
+	ret.environ.Set("DIST_DIR", ret.DistDir())
+
 	ret.environ.Unset(
 		// We're already using it
 		"USE_SOONG_UI",
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index 6851e8c..7e19da6 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -41,8 +41,8 @@
 
 var Log = PathConfig{
 	Symlink: true,
-	Log: true,
-	Error: false,
+	Log:     true,
+	Error:   false,
 }
 
 // The configuration used if the tool is not listed in the config below.
@@ -110,7 +110,6 @@
 	"openssl":   Allowed,
 	"paste":     Allowed,
 	"patch":     Allowed,
-	"perl":      Log,
 	"pgrep":     Allowed,
 	"pkill":     Allowed,
 	"ps":        Allowed,