Merge "Add libbinder_ndk to the NDK."
diff --git a/Android.bp b/Android.bp
index 2f7b051..dcbc030 100644
--- a/Android.bp
+++ b/Android.bp
@@ -134,7 +134,6 @@
         "cc/pgo.go",
         "cc/prebuilt.go",
         "cc/proto.go",
-        "cc/relocation_packer.go",
         "cc/rs.go",
         "cc/sanitize.go",
         "cc/sabi.go",
diff --git a/android/androidmk.go b/android/androidmk.go
index 1d11161..44c266a 100644
--- a/android/androidmk.go
+++ b/android/androidmk.go
@@ -141,6 +141,13 @@
 }
 
 func translateAndroidMkModule(ctx SingletonContext, w io.Writer, mod blueprint.Module) error {
+	defer func() {
+		if r := recover(); r != nil {
+			panic(fmt.Errorf("%s in translateAndroidMkModule for module %s variant %s",
+				r, ctx.ModuleName(mod), ctx.ModuleSubDir(mod)))
+		}
+	}()
+
 	provider, ok := mod.(AndroidMkDataProvider)
 	if !ok {
 		return nil
diff --git a/android/arch.go b/android/arch.go
index d84c829..c5f242f 100644
--- a/android/arch.go
+++ b/android/arch.go
@@ -201,7 +201,7 @@
 	osArchTypeMap = map[OsType][]ArchType{
 		Linux:       []ArchType{X86, X86_64},
 		LinuxBionic: []ArchType{X86_64},
-		Darwin:      []ArchType{X86, X86_64},
+		Darwin:      []ArchType{X86_64},
 		Windows:     []ArchType{X86, X86_64},
 		Android:     []ArchType{Arm, Arm64, Mips, Mips64, X86, X86_64},
 	}
@@ -1100,11 +1100,11 @@
 	return ret
 }
 
-func preferTargets(targets []Target, filters ...string) []Target {
+func firstTarget(targets []Target, filters ...string) []Target {
 	for _, filter := range filters {
 		buildTargets := filterMultilibTargets(targets, filter)
 		if len(buildTargets) > 0 {
-			return buildTargets
+			return buildTargets[:1]
 		}
 	}
 	return nil
@@ -1120,9 +1120,9 @@
 	case "common_first":
 		buildTargets = getCommonTargets(targets)
 		if prefer32 {
-			buildTargets = append(buildTargets, preferTargets(targets, "lib32", "lib64")...)
+			buildTargets = append(buildTargets, firstTarget(targets, "lib32", "lib64")...)
 		} else {
-			buildTargets = append(buildTargets, preferTargets(targets, "lib64", "lib32")...)
+			buildTargets = append(buildTargets, firstTarget(targets, "lib64", "lib32")...)
 		}
 	case "both":
 		if prefer32 {
@@ -1138,12 +1138,15 @@
 		buildTargets = filterMultilibTargets(targets, "lib64")
 	case "first":
 		if prefer32 {
-			buildTargets = preferTargets(targets, "lib32", "lib64")
+			buildTargets = firstTarget(targets, "lib32", "lib64")
 		} else {
-			buildTargets = preferTargets(targets, "lib64", "lib32")
+			buildTargets = firstTarget(targets, "lib64", "lib32")
 		}
 	case "prefer32":
-		buildTargets = preferTargets(targets, "lib32", "lib64")
+		buildTargets = filterMultilibTargets(targets, "lib32")
+		if len(buildTargets) == 0 {
+			buildTargets = filterMultilibTargets(targets, "lib64")
+		}
 	default:
 		return nil, fmt.Errorf(`compile_multilib must be "both", "first", "32", "64", or "prefer32" found %q`,
 			multilib)
diff --git a/android/config.go b/android/config.go
index 3a2a005..3ef202b 100644
--- a/android/config.go
+++ b/android/config.go
@@ -572,6 +572,10 @@
 	return Bool(c.productVariables.MinimizeJavaDebugInfo) && !Bool(c.productVariables.Eng)
 }
 
+func (c *config) Debuggable() bool {
+	return Bool(c.productVariables.Debuggable)
+}
+
 func (c *config) DevicePrefer32BitExecutables() bool {
 	return Bool(c.productVariables.DevicePrefer32BitExecutables)
 }
diff --git a/android/module.go b/android/module.go
index a058199..ae12274 100644
--- a/android/module.go
+++ b/android/module.go
@@ -23,6 +23,7 @@
 
 	"github.com/google/blueprint"
 	"github.com/google/blueprint/pathtools"
+	"github.com/google/blueprint/proptools"
 )
 
 var (
@@ -601,6 +602,10 @@
 	return Bool(p.commonProperties.Recovery)
 }
 
+func (a *ModuleBase) Owner() string {
+	return String(a.commonProperties.Owner)
+}
+
 func (a *ModuleBase) generateModuleTarget(ctx ModuleContext) {
 	allInstalledFiles := Paths{}
 	allCheckbuildFiles := Paths{}
@@ -844,6 +849,13 @@
 		bparams.Implicits = append(bparams.Implicits, params.Implicit.String())
 	}
 
+	bparams.Outputs = proptools.NinjaEscape(bparams.Outputs)
+	bparams.ImplicitOutputs = proptools.NinjaEscape(bparams.ImplicitOutputs)
+	bparams.Inputs = proptools.NinjaEscape(bparams.Inputs)
+	bparams.Implicits = proptools.NinjaEscape(bparams.Implicits)
+	bparams.OrderOnly = proptools.NinjaEscape(bparams.OrderOnly)
+	bparams.Depfile = proptools.NinjaEscape([]string{bparams.Depfile})[0]
+
 	return bparams
 }
 
@@ -1067,6 +1079,16 @@
 	return a.kind == productServicesSpecificModule
 }
 
+// Makes this module a platform module, i.e. not specific to soc, device,
+// product, or product_services.
+func (a *ModuleBase) MakeAsPlatform() {
+	a.commonProperties.Vendor = boolPtr(false)
+	a.commonProperties.Proprietary = boolPtr(false)
+	a.commonProperties.Soc_specific = boolPtr(false)
+	a.commonProperties.Product_specific = boolPtr(false)
+	a.commonProperties.Product_services_specific = boolPtr(false)
+}
+
 func (a *androidModuleContext) InstallInData() bool {
 	return a.module.InstallInData()
 }
diff --git a/android/mutator.go b/android/mutator.go
index 64d9fdd..b9c44e8 100644
--- a/android/mutator.go
+++ b/android/mutator.go
@@ -205,7 +205,7 @@
 }
 
 func depsMutator(ctx BottomUpMutatorContext) {
-	if m, ok := ctx.Module().(Module); ok {
+	if m, ok := ctx.Module().(Module); ok && m.Enabled() {
 		m.DepsMutator(ctx)
 	}
 }
diff --git a/android/package_ctx.go b/android/package_ctx.go
index e228bba..00b99ff 100644
--- a/android/package_ctx.go
+++ b/android/package_ctx.go
@@ -124,7 +124,11 @@
 // package-scoped variable's initialization.
 func (p PackageContext) SourcePathVariable(name, path string) blueprint.Variable {
 	return p.VariableFunc(name, func(ctx PackageVarContext) string {
-		return safePathForSource(ctx, path).String()
+		p, err := safePathForSource(ctx, path)
+		if err != nil {
+			ctx.Errorf("%s", err.Error())
+		}
+		return p.String()
 	})
 }
 
@@ -136,7 +140,10 @@
 	return p.VariableFunc(name, func(ctx PackageVarContext) string {
 		var ret []string
 		for _, path := range paths {
-			p := safePathForSource(ctx, path)
+			p, err := safePathForSource(ctx, path)
+			if err != nil {
+				ctx.Errorf("%s", err.Error())
+			}
 			ret = append(ret, p.String())
 		}
 		return strings.Join(ret, separator)
@@ -150,7 +157,10 @@
 // as part of a package-scoped variable's initialization.
 func (p PackageContext) SourcePathVariableWithEnvOverride(name, path, env string) blueprint.Variable {
 	return p.VariableFunc(name, func(ctx PackageVarContext) string {
-		p := safePathForSource(ctx, path)
+		p, err := safePathForSource(ctx, path)
+		if err != nil {
+			ctx.Errorf("%s", err.Error())
+		}
 		return ctx.Config().GetenvWithDefault(env, p.String())
 	})
 }
diff --git a/android/paths.go b/android/paths.go
index 57ebae2..91abeba 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -230,6 +230,8 @@
 // pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
 // source directory, but strip the local source directory from the beginning of
 // each string. If incDirs is false, strip paths with a trailing '/' from the list.
+// It intended for use in globs that only list files that exist, so it allows '$' in
+// filenames.
 func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
 	prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
 	if prefix == "./" {
@@ -246,7 +248,7 @@
 			continue
 		}
 
-		srcPath, err := pathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
+		srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
 		if err != nil {
 			reportPathError(ctx, err)
 			continue
@@ -494,29 +496,26 @@
 
 // safePathForSource is for paths that we expect are safe -- only for use by go
 // code that is embedding ninja variables in paths
-func safePathForSource(ctx PathContext, path string) SourcePath {
-	p, err := validateSafePath(path)
-	if err != nil {
-		reportPathError(ctx, err)
-	}
+func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
+	p, err := validateSafePath(pathComponents...)
 	ret := SourcePath{basePath{p, ctx.Config(), ""}}
+	if err != nil {
+		return ret, err
+	}
 
 	abs, err := filepath.Abs(ret.String())
 	if err != nil {
-		reportPathError(ctx, err)
-		return ret
+		return ret, err
 	}
 	buildroot, err := filepath.Abs(ctx.Config().buildDir)
 	if err != nil {
-		reportPathError(ctx, err)
-		return ret
+		return ret, err
 	}
 	if strings.HasPrefix(abs, buildroot) {
-		reportPathErrorf(ctx, "source path %s is in output", abs)
-		return ret
+		return ret, fmt.Errorf("source path %s is in output", abs)
 	}
 
-	return ret
+	return ret, err
 }
 
 // pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
diff --git a/android/variable.go b/android/variable.go
index b4ed1b7..b478389 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -43,8 +43,8 @@
 		} `android:"arch_variant"`
 
 		Malloc_not_svelte struct {
-			Cflags []string
-		}
+			Cflags []string `android:"arch_variant"`
+		} `android:"arch_variant"`
 
 		Safestack struct {
 			Cflags []string `android:"arch_variant"`
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 7595db1..bb82529 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -60,24 +60,17 @@
 	ret := android.AndroidMkData{
 		OutputFile: c.outputFile,
 		Required:   c.Properties.AndroidMkRuntimeLibs,
+		Include:    "$(BUILD_SYSTEM)/soong_cc_prebuilt.mk",
 
 		Extra: []android.AndroidMkExtraFunc{
 			func(w io.Writer, outputFile android.Path) {
 				if len(c.Properties.Logtags) > 0 {
 					fmt.Fprintln(w, "LOCAL_LOGTAGS_FILES :=", strings.Join(c.Properties.Logtags, " "))
 				}
-				fmt.Fprintln(w, "LOCAL_SANITIZE := never")
 				if len(c.Properties.AndroidMkSharedLibs) > 0 {
 					fmt.Fprintln(w, "LOCAL_SHARED_LIBRARIES := "+strings.Join(c.Properties.AndroidMkSharedLibs, " "))
 				}
-				if c.Target().Os == android.Android &&
-					String(c.Properties.Sdk_version) != "" && !c.useVndk() && !c.inRecovery() {
-					fmt.Fprintln(w, "LOCAL_SDK_VERSION := "+String(c.Properties.Sdk_version))
-					fmt.Fprintln(w, "LOCAL_NDK_STL_VARIANT := none")
-				} else {
-					// These are already included in LOCAL_SHARED_LIBRARIES
-					fmt.Fprintln(w, "LOCAL_CXX_STL := none")
-				}
+				fmt.Fprintln(w, "LOCAL_SOONG_LINK_TYPE :=", c.getMakeLinkType())
 				if c.useVndk() {
 					fmt.Fprintln(w, "LOCAL_USE_VNDK := true")
 				}
@@ -140,45 +133,13 @@
 	if library.static() {
 		ret.Class = "STATIC_LIBRARIES"
 	} else if library.shared() {
-		ctx.subAndroidMk(ret, &library.stripper)
-		ctx.subAndroidMk(ret, &library.relocationPacker)
-
 		ret.Class = "SHARED_LIBRARIES"
+		ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
+			fmt.Fprintln(w, "LOCAL_SOONG_TOC :=", library.toc().String())
+			fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", library.unstrippedOutputFile.String())
+		})
 	} else if library.header() {
-		ret.Custom = func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
-			fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
-			fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
-			fmt.Fprintln(w, "LOCAL_MODULE :=", name+data.SubName)
-
-			archStr := ctx.Target().Arch.ArchType.String()
-			var host bool
-			switch ctx.Target().Os.Class {
-			case android.Host:
-				fmt.Fprintln(w, "LOCAL_MODULE_HOST_ARCH := ", archStr)
-				host = true
-			case android.HostCross:
-				fmt.Fprintln(w, "LOCAL_MODULE_HOST_CROSS_ARCH := ", archStr)
-				host = true
-			case android.Device:
-				fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH := ", archStr)
-			}
-
-			if host {
-				makeOs := ctx.Target().Os.String()
-				if ctx.Target().Os == android.Linux || ctx.Target().Os == android.LinuxBionic {
-					makeOs = "linux"
-				}
-				fmt.Fprintln(w, "LOCAL_MODULE_HOST_OS :=", makeOs)
-				fmt.Fprintln(w, "LOCAL_IS_HOST_MODULE := true")
-			} else if ctx.useVndk() {
-				fmt.Fprintln(w, "LOCAL_USE_VNDK := true")
-			}
-
-			library.androidMkWriteExportedFlags(w)
-			fmt.Fprintln(w, "include $(BUILD_HEADER_LIBRARY)")
-		}
-
-		return
+		ret.Class = "HEADER_LIBRARIES"
 	}
 
 	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
@@ -196,8 +157,6 @@
 
 		fmt.Fprintln(w, "LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE)"+ext)
 
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
-
 		if library.coverageOutputFile.Valid() {
 			fmt.Fprintln(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE :=", library.coverageOutputFile.String())
 		}
@@ -205,6 +164,10 @@
 
 	if library.shared() {
 		ctx.subAndroidMk(ret, library.baseInstaller)
+	} else {
+		ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
+			fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
+		})
 	}
 }
 
@@ -219,15 +182,10 @@
 
 func (binary *binaryDecorator) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
 	ctx.subAndroidMk(ret, binary.baseInstaller)
-	ctx.subAndroidMk(ret, &binary.stripper)
 
 	ret.Class = "EXECUTABLES"
 	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
-		if Bool(binary.Properties.Static_executable) {
-			fmt.Fprintln(w, "LOCAL_FORCE_STATIC_EXECUTABLE := true")
-		}
-
+		fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", binary.unstrippedOutputFile.String())
 		if len(binary.symlinks) > 0 {
 			fmt.Fprintln(w, "LOCAL_MODULE_SYMLINKS := "+strings.Join(binary.symlinks, " "))
 		}
@@ -288,33 +246,6 @@
 	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
 		_, suffix, _ := splitFileExt(outputFile.Base())
 		fmt.Fprintln(w, "LOCAL_MODULE_SUFFIX := "+suffix)
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
-	})
-}
-
-func (stripper *stripper) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
-	// Make only supports stripping target modules
-	if ctx.Target().Os != android.Android {
-		return
-	}
-
-	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
-		if Bool(stripper.StripProperties.Strip.None) {
-
-			fmt.Fprintln(w, "LOCAL_STRIP_MODULE := false")
-		} else if Bool(stripper.StripProperties.Strip.Keep_symbols) {
-			fmt.Fprintln(w, "LOCAL_STRIP_MODULE := keep_symbols")
-		} else {
-			fmt.Fprintln(w, "LOCAL_STRIP_MODULE := mini-debug-info")
-		}
-	})
-}
-
-func (packer *relocationPacker) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
-	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
-		if packer.Properties.PackingRelocations {
-			fmt.Fprintln(w, "LOCAL_PACK_MODULE_RELOCATIONS := true")
-		}
 	})
 }
 
@@ -342,7 +273,6 @@
 	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
 		path, file := filepath.Split(c.installPath.String())
 		stem, suffix, _ := splitFileExt(file)
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
 		fmt.Fprintln(w, "LOCAL_MODULE_SUFFIX := "+suffix)
 		fmt.Fprintln(w, "LOCAL_MODULE_PATH := "+path)
 		fmt.Fprintln(w, "LOCAL_MODULE_STEM := "+stem)
@@ -364,11 +294,9 @@
 		_, _, ext := splitFileExt(outputFile.Base())
 
 		fmt.Fprintln(w, "LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE)"+ext)
-		fmt.Fprintln(w, "LOCAL_STRIP_MODULE := false")
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
 		fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
 		fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
-		fmt.Fprintln(w, "LOCAL_USE_VNDK := true")
+		fmt.Fprintln(w, "LOCAL_SOONG_TOC :=", c.toc().String())
 	})
 }
 
@@ -383,9 +311,6 @@
 		path := c.path.RelPathString()
 		dir, file := filepath.Split(path)
 		stem, suffix, ext := splitFileExt(file)
-		fmt.Fprintln(w, "LOCAL_STRIP_MODULE := false")
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
-		fmt.Fprintln(w, "LOCAL_USE_VNDK := true")
 		fmt.Fprintln(w, "LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE)"+ext)
 		fmt.Fprintln(w, "LOCAL_MODULE_SUFFIX := "+suffix)
 		fmt.Fprintln(w, "LOCAL_MODULE_PATH := $(OUT_DIR)/"+filepath.Clean(dir))
@@ -413,8 +338,6 @@
 		_, _, ext := splitFileExt(outputFile.Base())
 
 		fmt.Fprintln(w, "LOCAL_BUILT_MODULE_STEM := $(LOCAL_MODULE)"+ext)
-		fmt.Fprintln(w, "LOCAL_STRIP_MODULE := false")
-		fmt.Fprintln(w, "LOCAL_SYSTEM_SHARED_LIBRARIES :=")
 		fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
 		fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
 	})
diff --git a/cc/binary.go b/cc/binary.go
index be79032..07d503b 100644
--- a/cc/binary.go
+++ b/cc/binary.go
@@ -78,6 +78,9 @@
 
 	toolPath android.OptionalPath
 
+	// Location of the linked, unstripped binary
+	unstrippedOutputFile android.Path
+
 	// Names of symlinks to be installed for use in LOCAL_MODULE_SYMLINKS
 	symlinks []string
 
@@ -205,7 +208,7 @@
 func (binary *binaryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
 	flags = binary.baseLinker.linkerFlags(ctx, flags)
 
-	if ctx.Host() && !binary.static() {
+	if ctx.Host() && !ctx.Windows() && !binary.static() {
 		if !ctx.Config().IsEnvTrue("DISABLE_HOST_PIE") {
 			flags.LdFlags = append(flags.LdFlags, "-pie")
 		}
@@ -306,6 +309,8 @@
 		binary.stripper.strip(ctx, outputFile, strippedOutputFile, builderFlags)
 	}
 
+	binary.unstrippedOutputFile = outputFile
+
 	if String(binary.Properties.Prefix_symbols) != "" {
 		afterPrefixSymbols := outputFile
 		outputFile = android.PathForModuleOut(ctx, "unprefixed", fileName)
diff --git a/cc/builder.go b/cc/builder.go
index 7d207b0..58196f4 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -144,18 +144,16 @@
 		blueprint.RuleParams{
 			Depfile:     "${out}.d",
 			Deps:        blueprint.DepsGCC,
-			Command:     "CROSS_COMPILE=$crossCompile $tocPath -i ${in} -o ${out} -d ${out}.d",
+			Command:     "CROSS_COMPILE=$crossCompile $tocPath $format -i ${in} -o ${out} -d ${out}.d",
 			CommandDeps: []string{"$tocPath"},
 			Restat:      true,
 		},
-		"crossCompile")
-
-	_ = pctx.SourcePathVariable("tidyPath", "build/soong/scripts/clang-tidy.sh")
+		"crossCompile", "format")
 
 	clangTidy = pctx.AndroidStaticRule("clangTidy",
 		blueprint.RuleParams{
-			Command:     "rm -f $out && CLANG_TIDY=${config.ClangBin}/clang-tidy $tidyPath $tidyFlags $in -- $cFlags && touch $out",
-			CommandDeps: []string{"${config.ClangBin}/clang-tidy", "$tidyPath"},
+			Command:     "rm -f $out && CLANG_TIDY=${config.ClangBin}/clang-tidy ${config.ClangTidyShellPath} $tidyFlags $in -- $cFlags && touch $out",
+			CommandDeps: []string{"${config.ClangBin}/clang-tidy", "${config.ClangTidyShellPath}"},
 		},
 		"cFlags", "tidyFlags")
 
@@ -761,7 +759,18 @@
 func TransformSharedObjectToToc(ctx android.ModuleContext, inputFile android.Path,
 	outputFile android.WritablePath, flags builderFlags) {
 
-	crossCompile := gccCmd(flags.toolchain, "")
+	var format string
+	var crossCompile string
+	if ctx.Darwin() {
+		format = "--macho"
+		crossCompile = "${config.MacToolPath}"
+	} else if ctx.Windows() {
+		format = "--pe"
+		crossCompile = gccCmd(flags.toolchain, "")
+	} else {
+		format = "--elf"
+		crossCompile = gccCmd(flags.toolchain, "")
+	}
 
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        toc,
@@ -770,6 +779,7 @@
 		Input:       inputFile,
 		Args: map[string]string{
 			"crossCompile": crossCompile,
+			"format":       format,
 		},
 	})
 }
diff --git a/cc/cc.go b/cc/cc.go
index 7f65640..d31a38a 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -366,6 +366,10 @@
 	staticVariant *Module
 }
 
+func (c *Module) OutputFile() android.OptionalPath {
+	return c.outputFile
+}
+
 func (c *Module) Init() android.Module {
 	c.AddProperties(&c.Properties, &c.VendorProperties)
 	if c.compiler != nil {
@@ -585,6 +589,9 @@
 	if inList(ctx.baseModuleName(), llndkLibraries) {
 		return true
 	}
+	if inList(ctx.baseModuleName(), ndkMigratedLibs) {
+		return true
+	}
 	if ctx.useVndk() && ctx.isVndk() {
 		// Return true if this is VNDK-core, VNDK-SP, or VNDK-Ext and this is not
 		// VNDK-private.
@@ -922,10 +929,6 @@
 }
 
 func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
-	if !c.Enabled() {
-		return
-	}
-
 	ctx := &depsContext{
 		BottomUpMutatorContext: actx,
 		moduleContextImpl: moduleContextImpl{
@@ -1043,13 +1046,13 @@
 		actx.AddDependency(c, depTag, gen)
 	}
 
-	actx.AddDependency(c, objDepTag, deps.ObjFiles...)
+	actx.AddVariationDependencies(nil, objDepTag, deps.ObjFiles...)
 
 	if deps.CrtBegin != "" {
-		actx.AddDependency(c, crtBeginDepTag, deps.CrtBegin)
+		actx.AddVariationDependencies(nil, crtBeginDepTag, deps.CrtBegin)
 	}
 	if deps.CrtEnd != "" {
-		actx.AddDependency(c, crtEndDepTag, deps.CrtEnd)
+		actx.AddVariationDependencies(nil, crtEndDepTag, deps.CrtEnd)
 	}
 	if deps.LinkerScript != "" {
 		actx.AddDependency(c, linkerScriptDepTag, deps.LinkerScript)
@@ -1090,10 +1093,6 @@
 		ctx.PropertyErrorf("clang", "false (GCC) is no longer supported")
 	}
 
-	if !c.toolchain(ctx).ClangSupported() {
-		panic("GCC is no longer supported")
-	}
-
 	return !c.Properties.Gcc
 }
 
@@ -1182,7 +1181,7 @@
 		// We can be permissive with the system "STL" since it is only the C++
 		// ABI layer, but in the future we should make sure that everyone is
 		// using either libc++ or nothing.
-	} else if getNdkStlFamily(ctx, from) != getNdkStlFamily(ctx, to) {
+	} else if getNdkStlFamily(from) != getNdkStlFamily(to) {
 		ctx.ModuleErrorf("uses %q and depends on %q which uses incompatible %q",
 			from.stl.Properties.SelectedStl, ctx.OtherModuleName(to),
 			to.stl.Properties.SelectedStl)
@@ -1492,6 +1491,29 @@
 	return false
 }
 
+func (c *Module) getMakeLinkType() string {
+	if c.useVndk() {
+		if inList(c.Name(), vndkCoreLibraries) || inList(c.Name(), vndkSpLibraries) || inList(c.Name(), llndkLibraries) {
+			if inList(c.Name(), vndkPrivateLibraries) {
+				return "native:vndk_private"
+			} else {
+				return "native:vndk"
+			}
+		} else {
+			return "native:vendor"
+		}
+	} else if c.inRecovery() {
+		return "native:recovery"
+	} else if c.Target().Os == android.Android && String(c.Properties.Sdk_version) != "" {
+		return "native:ndk:none:none"
+		// TODO(b/114741097): use the correct ndk stl once build errors have been fixed
+		//family, link := getNdkStlFamilyAndLinkType(c)
+		//return fmt.Sprintf("native:ndk:%s:%s", family, link)
+	} else {
+		return "native:platform"
+	}
+}
+
 //
 // Defaults
 //
@@ -1741,6 +1763,7 @@
 		} else if v == recoveryMode {
 			m := mod[i].(*Module)
 			m.Properties.InRecovery = true
+			m.MakeAsPlatform()
 			squashRecoverySrcs(m)
 		}
 	}
diff --git a/cc/cc_test.go b/cc/cc_test.go
index 3d162e7..3d5dfb1 100644
--- a/cc/cc_test.go
+++ b/cc/cc_test.go
@@ -158,11 +158,13 @@
 		cc_object {
 			name: "crtbegin_so",
 			recovery_available: true,
+			vendor_available: true,
 		}
 
 		cc_object {
 			name: "crtend_so",
 			recovery_available: true,
+			vendor_available: true,
 		}
 
 		cc_library {
@@ -236,8 +238,9 @@
 }
 
 const (
-	coreVariant   = "android_arm64_armv8-a_core_shared"
-	vendorVariant = "android_arm64_armv8-a_vendor_shared"
+	coreVariant     = "android_arm64_armv8-a_core_shared"
+	vendorVariant   = "android_arm64_armv8-a_vendor_shared"
+	recoveryVariant = "android_arm64_armv8-a_recovery_shared"
 )
 
 func TestVendorSrc(t *testing.T) {
@@ -1674,6 +1677,11 @@
 			recovery: true,
 			compile_multilib:"32",
 		}
+		cc_library_shared {
+			name: "libHalInRecovery",
+			recovery_available: true,
+			vendor: true,
+		}
 	`)
 
 	variants := ctx.ModuleVariantsForTests("librecovery")
@@ -1686,4 +1694,10 @@
 	if android.InList(arm64, variants) {
 		t.Errorf("multilib was set to 32 for librecovery32, but its variants has %s.", arm64)
 	}
+
+	recoveryModule := ctx.ModuleForTests("libHalInRecovery", recoveryVariant).Module().(*Module)
+	if !recoveryModule.Platform() {
+		t.Errorf("recovery variant of libHalInRecovery must not specific to device, soc, or product")
+	}
+
 }
diff --git a/cc/config/arm64_device.go b/cc/config/arm64_device.go
index f412583..6fdd524 100644
--- a/cc/config/arm64_device.go
+++ b/cc/config/arm64_device.go
@@ -238,7 +238,7 @@
 	return t.toolchainClangCflags
 }
 
-func (toolchainArm64) SanitizerRuntimeLibraryArch() string {
+func (toolchainArm64) LibclangRuntimeLibraryArch() string {
 	return "aarch64"
 }
 
diff --git a/cc/config/arm_device.go b/cc/config/arm_device.go
index 4719fb7..4135179 100644
--- a/cc/config/arm_device.go
+++ b/cc/config/arm_device.go
@@ -397,7 +397,7 @@
 	}
 }
 
-func (toolchainArm) SanitizerRuntimeLibraryArch() string {
+func (toolchainArm) LibclangRuntimeLibraryArch() string {
 	return "arm"
 }
 
diff --git a/cc/config/global.go b/cc/config/global.go
index a49e509..8b02f02 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -209,6 +209,7 @@
 	})
 	pctx.StaticVariable("ClangPath", "${ClangBase}/${HostPrebuiltTag}/${ClangVersion}")
 	pctx.StaticVariable("ClangBin", "${ClangPath}/bin")
+	pctx.StaticVariable("ClangTidyShellPath", "build/soong/scripts/clang-tidy.sh")
 
 	pctx.VariableFunc("ClangShortVersion", func(ctx android.PackageVarContext) string {
 		if override := ctx.Config().Getenv("LLVM_RELEASE_VERSION"); override != "" {
diff --git a/cc/config/mips64_device.go b/cc/config/mips64_device.go
index 6fa2571..0c4640b 100644
--- a/cc/config/mips64_device.go
+++ b/cc/config/mips64_device.go
@@ -160,7 +160,7 @@
 	return "${config.Mips64ClangLdflags}"
 }
 
-func (toolchainMips64) SanitizerRuntimeLibraryArch() string {
+func (toolchainMips64) LibclangRuntimeLibraryArch() string {
 	return "mips64"
 }
 
diff --git a/cc/config/mips_device.go b/cc/config/mips_device.go
index b815fc6..eb44fd5 100644
--- a/cc/config/mips_device.go
+++ b/cc/config/mips_device.go
@@ -210,7 +210,7 @@
 	return "${config.MipsClangLdflags}"
 }
 
-func (toolchainMips) SanitizerRuntimeLibraryArch() string {
+func (toolchainMips) LibclangRuntimeLibraryArch() string {
 	return "mips"
 }
 
diff --git a/cc/config/toolchain.go b/cc/config/toolchain.go
index 39b5df4..930b18f 100644
--- a/cc/config/toolchain.go
+++ b/cc/config/toolchain.go
@@ -57,7 +57,6 @@
 	IncludeFlags() string
 	InstructionSetFlags(string) (string, error)
 
-	ClangSupported() bool
 	ClangTriple() string
 	ToolchainClangCflags() string
 	ToolchainClangLdflags() string
@@ -79,7 +78,7 @@
 	ShlibSuffix() string
 	ExecutableSuffix() string
 
-	SanitizerRuntimeLibraryArch() string
+	LibclangRuntimeLibraryArch() string
 
 	AvailableLibraries() []string
 
@@ -132,10 +131,6 @@
 	return ""
 }
 
-func (toolchainBase) ClangSupported() bool {
-	return true
-}
-
 func (toolchainBase) ShlibSuffix() string {
 	return ".so"
 }
@@ -156,7 +151,7 @@
 	return ""
 }
 
-func (toolchainBase) SanitizerRuntimeLibraryArch() string {
+func (toolchainBase) LibclangRuntimeLibraryArch() string {
 	return ""
 }
 
@@ -214,44 +209,48 @@
 	return list
 }
 
-func SanitizerRuntimeLibrary(t Toolchain, sanitizer string) string {
-	arch := t.SanitizerRuntimeLibraryArch()
+func LibclangRuntimeLibrary(t Toolchain, library string) string {
+	arch := t.LibclangRuntimeLibraryArch()
 	if arch == "" {
 		return ""
 	}
-	return "libclang_rt." + sanitizer + "-" + arch + "-android"
+	return "libclang_rt." + library + "-" + arch + "-android"
+}
+
+func BuiltinsRuntimeLibrary(t Toolchain) string {
+	return LibclangRuntimeLibrary(t, "builtins")
 }
 
 func AddressSanitizerRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "asan")
+	return LibclangRuntimeLibrary(t, "asan")
 }
 
 func HWAddressSanitizerRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "hwasan")
+	return LibclangRuntimeLibrary(t, "hwasan")
 }
 
 func HWAddressSanitizerStaticLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "hwasan_static")
+	return LibclangRuntimeLibrary(t, "hwasan_static")
 }
 
 func UndefinedBehaviorSanitizerRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "ubsan_standalone")
+	return LibclangRuntimeLibrary(t, "ubsan_standalone")
 }
 
 func UndefinedBehaviorSanitizerMinimalRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "ubsan_minimal")
+	return LibclangRuntimeLibrary(t, "ubsan_minimal")
 }
 
 func ThreadSanitizerRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "tsan")
+	return LibclangRuntimeLibrary(t, "tsan")
 }
 
 func ProfileRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "profile")
+	return LibclangRuntimeLibrary(t, "profile")
 }
 
 func ScudoRuntimeLibrary(t Toolchain) string {
-	return SanitizerRuntimeLibrary(t, "scudo")
+	return LibclangRuntimeLibrary(t, "scudo")
 }
 
 func ToolPath(t Toolchain) string {
diff --git a/cc/config/x86_64_device.go b/cc/config/x86_64_device.go
index ba03094..5e2dc49 100644
--- a/cc/config/x86_64_device.go
+++ b/cc/config/x86_64_device.go
@@ -227,7 +227,7 @@
 	return "${config.X86_64YasmFlags}"
 }
 
-func (toolchainX86_64) SanitizerRuntimeLibraryArch() string {
+func (toolchainX86_64) LibclangRuntimeLibraryArch() string {
 	return "x86_64"
 }
 
diff --git a/cc/config/x86_darwin_host.go b/cc/config/x86_darwin_host.go
index 4ec2b31..694137d 100644
--- a/cc/config/x86_darwin_host.go
+++ b/cc/config/x86_darwin_host.go
@@ -37,28 +37,14 @@
 		"-isysroot ${macSdkRoot}",
 		"-mmacosx-version-min=${macMinVersion}",
 		"-DMACOSX_DEPLOYMENT_TARGET=${macMinVersion}",
+
+		"-m64",
 	}
 
 	darwinLdflags = []string{
 		"-isysroot ${macSdkRoot}",
 		"-Wl,-syslibroot,${macSdkRoot}",
 		"-mmacosx-version-min=${macMinVersion}",
-	}
-
-	// Extended cflags
-	darwinX86Cflags = []string{
-		"-m32",
-	}
-
-	darwinX8664Cflags = []string{
-		"-m64",
-	}
-
-	darwinX86Ldflags = []string{
-		"-m32",
-	}
-
-	darwinX8664Ldflags = []string{
 		"-m64",
 	}
 
@@ -67,27 +53,16 @@
 		"-fstack-protector-strong",
 	}...)
 
-	darwinX86ClangCflags = append(ClangFilterUnknownCflags(darwinX86Cflags), []string{
-		"-msse3",
-	}...)
-
 	darwinClangLdflags = ClangFilterUnknownCflags(darwinLdflags)
 
 	darwinClangLldflags = ClangFilterUnknownLldflags(darwinClangLdflags)
 
-	darwinX86ClangLdflags = ClangFilterUnknownCflags(darwinX86Ldflags)
-
-	darwinX86ClangLldflags = ClangFilterUnknownLldflags(darwinX86ClangLdflags)
-
-	darwinX8664ClangLdflags = ClangFilterUnknownCflags(darwinX8664Ldflags)
-
-	darwinX8664ClangLldflags = ClangFilterUnknownLldflags(darwinX8664ClangLdflags)
-
 	darwinSupportedSdkVersions = []string{
 		"10.10",
 		"10.11",
 		"10.12",
 		"10.13",
+		"10.14",
 	}
 
 	darwinAvailableLibraries = append(
@@ -149,21 +124,7 @@
 	pctx.StaticVariable("DarwinClangLdflags", strings.Join(darwinClangLdflags, " "))
 	pctx.StaticVariable("DarwinClangLldflags", strings.Join(darwinClangLldflags, " "))
 
-	// Extended cflags
-	pctx.StaticVariable("DarwinX86Cflags", strings.Join(darwinX86Cflags, " "))
-	pctx.StaticVariable("DarwinX8664Cflags", strings.Join(darwinX8664Cflags, " "))
-	pctx.StaticVariable("DarwinX86Ldflags", strings.Join(darwinX86Ldflags, " "))
-	pctx.StaticVariable("DarwinX8664Ldflags", strings.Join(darwinX8664Ldflags, " "))
-
-	pctx.StaticVariable("DarwinX86ClangCflags", strings.Join(darwinX86ClangCflags, " "))
-	pctx.StaticVariable("DarwinX8664ClangCflags",
-		strings.Join(ClangFilterUnknownCflags(darwinX8664Cflags), " "))
-	pctx.StaticVariable("DarwinX86ClangLdflags", strings.Join(darwinX86ClangLdflags, " "))
-	pctx.StaticVariable("DarwinX86ClangLldflags", strings.Join(darwinX86ClangLldflags, " "))
-	pctx.StaticVariable("DarwinX8664ClangLdflags", strings.Join(darwinX8664ClangLdflags, " "))
-	pctx.StaticVariable("DarwinX8664ClangLldflags", strings.Join(darwinX8664ClangLldflags, " "))
-	pctx.StaticVariable("DarwinX86YasmFlags", "-f macho -m x86")
-	pctx.StaticVariable("DarwinX8664YasmFlags", "-f macho -m amd64")
+	pctx.StaticVariable("DarwinYasmFlags", "-f macho -m amd64")
 }
 
 func xcrun(ctx android.PackageVarContext, args ...string) string {
@@ -202,23 +163,10 @@
 
 type toolchainDarwin struct {
 	cFlags, ldFlags string
-}
-
-type toolchainDarwinX86 struct {
-	toolchain32Bit
-	toolchainDarwin
-}
-
-type toolchainDarwinX8664 struct {
 	toolchain64Bit
-	toolchainDarwin
 }
 
-func (t *toolchainDarwinX86) Name() string {
-	return "x86"
-}
-
-func (t *toolchainDarwinX8664) Name() string {
+func (t *toolchainDarwin) Name() string {
 	return "x86_64"
 }
 
@@ -235,71 +183,43 @@
 }
 
 func (t *toolchainDarwin) Cflags() string {
-	return "${config.DarwinCflags} ${config.DarwinX86Cflags}"
-}
-
-func (t *toolchainDarwinX8664) Cflags() string {
-	return "${config.DarwinCflags} ${config.DarwinX8664Cflags}"
+	return "${config.DarwinCflags}"
 }
 
 func (t *toolchainDarwin) Cppflags() string {
 	return ""
 }
 
-func (t *toolchainDarwinX86) Ldflags() string {
-	return "${config.DarwinLdflags} ${config.DarwinX86Ldflags}"
-}
-
-func (t *toolchainDarwinX8664) Ldflags() string {
-	return "${config.DarwinLdflags} ${config.DarwinX8664Ldflags}"
+func (t *toolchainDarwin) Ldflags() string {
+	return "${config.DarwinLdflags}"
 }
 
 func (t *toolchainDarwin) IncludeFlags() string {
 	return ""
 }
 
-func (t *toolchainDarwinX86) ClangTriple() string {
-	return "i686-apple-darwin"
-}
-
-func (t *toolchainDarwinX86) ClangCflags() string {
-	return "${config.DarwinClangCflags} ${config.DarwinX86ClangCflags}"
-}
-
-func (t *toolchainDarwinX8664) ClangTriple() string {
+func (t *toolchainDarwin) ClangTriple() string {
 	return "x86_64-apple-darwin"
 }
 
-func (t *toolchainDarwinX8664) ClangCflags() string {
-	return "${config.DarwinClangCflags} ${config.DarwinX8664ClangCflags}"
+func (t *toolchainDarwin) ClangCflags() string {
+	return "${config.DarwinClangCflags}"
 }
 
 func (t *toolchainDarwin) ClangCppflags() string {
 	return ""
 }
 
-func (t *toolchainDarwinX86) ClangLdflags() string {
-	return "${config.DarwinClangLdflags} ${config.DarwinX86ClangLdflags}"
+func (t *toolchainDarwin) ClangLdflags() string {
+	return "${config.DarwinClangLdflags}"
 }
 
-func (t *toolchainDarwinX86) ClangLldflags() string {
-	return "${config.DarwinClangLldflags} ${config.DarwinX86ClangLldflags}"
+func (t *toolchainDarwin) ClangLldflags() string {
+	return "${config.DarwinClangLldflags}"
 }
 
-func (t *toolchainDarwinX8664) ClangLdflags() string {
-	return "${config.DarwinClangLdflags} ${config.DarwinX8664ClangLdflags}"
-}
-
-func (t *toolchainDarwinX8664) ClangLldflags() string {
-	return "${config.DarwinClangLldflags} ${config.DarwinX8664ClangLldflags}"
-}
-
-func (t *toolchainDarwinX86) YasmFlags() string {
-	return "${config.DarwinX86YasmFlags}"
-}
-
-func (t *toolchainDarwinX8664) YasmFlags() string {
-	return "${config.DarwinX8664YasmFlags}"
+func (t *toolchainDarwin) YasmFlags() string {
+	return "${config.DarwinYasmFlags}"
 }
 
 func (t *toolchainDarwin) ShlibSuffix() string {
@@ -318,18 +238,12 @@
 	return "${config.MacToolPath}"
 }
 
-var toolchainDarwinX86Singleton Toolchain = &toolchainDarwinX86{}
-var toolchainDarwinX8664Singleton Toolchain = &toolchainDarwinX8664{}
+var toolchainDarwinSingleton Toolchain = &toolchainDarwin{}
 
-func darwinX86ToolchainFactory(arch android.Arch) Toolchain {
-	return toolchainDarwinX86Singleton
-}
-
-func darwinX8664ToolchainFactory(arch android.Arch) Toolchain {
-	return toolchainDarwinX8664Singleton
+func darwinToolchainFactory(arch android.Arch) Toolchain {
+	return toolchainDarwinSingleton
 }
 
 func init() {
-	registerToolchainFactory(android.Darwin, android.X86, darwinX86ToolchainFactory)
-	registerToolchainFactory(android.Darwin, android.X86_64, darwinX8664ToolchainFactory)
+	registerToolchainFactory(android.Darwin, android.X86_64, darwinToolchainFactory)
 }
diff --git a/cc/config/x86_device.go b/cc/config/x86_device.go
index 15188cf..ffdf8ea 100644
--- a/cc/config/x86_device.go
+++ b/cc/config/x86_device.go
@@ -251,7 +251,7 @@
 	return "${config.X86YasmFlags}"
 }
 
-func (toolchainX86) SanitizerRuntimeLibraryArch() string {
+func (toolchainX86) LibclangRuntimeLibraryArch() string {
 	return "i686"
 }
 
diff --git a/cc/config/x86_windows_host.go b/cc/config/x86_windows_host.go
index 4cb8fa4..65b9e6c 100644
--- a/cc/config/x86_windows_host.go
+++ b/cc/config/x86_windows_host.go
@@ -62,6 +62,8 @@
 
 	windowsLdflags = []string{
 		"--enable-stdcall-fixup",
+		"-Wl,--dynamicbase",
+		"-Wl,--nxcompat",
 	}
 	windowsClangLdflags  = append(ClangFilterUnknownCflags(windowsLdflags), []string{}...)
 	windowsClangLldflags = ClangFilterUnknownLldflags(windowsClangLdflags)
@@ -96,6 +98,7 @@
 		"-m64",
 		"-L${WindowsGccRoot}/${WindowsGccTriple}/lib64",
 		"-static-libgcc",
+		"-Wl,--high-entropy-va",
 	}
 	windowsX8664ClangLdflags = append(ClangFilterUnknownCflags(windowsX8664Ldflags), []string{
 		"-B${WindowsGccRoot}/${WindowsGccTriple}/bin",
@@ -230,10 +233,6 @@
 	return "-F pe-x86-64"
 }
 
-func (t *toolchainWindows) ClangSupported() bool {
-	return true
-}
-
 func (t *toolchainWindowsX86) ClangTriple() string {
 	return "i686-windows-gnu"
 }
diff --git a/cc/library.go b/cc/library.go
index 147dd8e..0e45af9 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -210,7 +210,6 @@
 
 	flagExporter
 	stripper
-	relocationPacker
 
 	// If we're used as a whole_static_lib, our missing dependencies need
 	// to be given
@@ -238,6 +237,9 @@
 	// not included in the NDK.
 	ndkSysrootPath android.Path
 
+	// Location of the linked, unstripped library for shared libraries
+	unstrippedOutputFile android.Path
+
 	// Decorated interafaces
 	*baseCompiler
 	*baseLinker
@@ -251,8 +253,7 @@
 		&library.Properties,
 		&library.MutatedProperties,
 		&library.flagExporter.Properties,
-		&library.stripper.StripProperties,
-		&library.relocationPacker.Properties)
+		&library.stripper.StripProperties)
 }
 
 func (library *libraryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
@@ -428,8 +429,6 @@
 	library.baseInstaller.location = location
 
 	library.baseLinker.linkerInit(ctx)
-
-	library.relocationPacker.packingInit(ctx)
 }
 
 func (library *libraryDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps {
@@ -548,21 +547,13 @@
 
 	builderFlags := flagsToBuilderFlags(flags)
 
-	if !ctx.Darwin() && !ctx.Windows() {
-		// Optimize out relinking against shared libraries whose interface hasn't changed by
-		// depending on a table of contents file instead of the library itself.
-		tocPath := outputFile.RelPathString()
-		tocPath = pathtools.ReplaceExtension(tocPath, flags.Toolchain.ShlibSuffix()[1:]+".toc")
-		tocFile := android.PathForOutput(ctx, tocPath)
-		library.tocFile = android.OptionalPathForPath(tocFile)
-		TransformSharedObjectToToc(ctx, outputFile, tocFile, builderFlags)
-	}
-
-	if library.relocationPacker.needsPacking(ctx) {
-		packedOutputFile := outputFile
-		outputFile = android.PathForModuleOut(ctx, "unpacked", fileName)
-		library.relocationPacker.pack(ctx, outputFile, packedOutputFile, builderFlags)
-	}
+	// Optimize out relinking against shared libraries whose interface hasn't changed by
+	// depending on a table of contents file instead of the library itself.
+	tocPath := outputFile.RelPathString()
+	tocPath = pathtools.ReplaceExtension(tocPath, flags.Toolchain.ShlibSuffix()[1:]+".toc")
+	tocFile := android.PathForOutput(ctx, tocPath)
+	library.tocFile = android.OptionalPathForPath(tocFile)
+	TransformSharedObjectToToc(ctx, outputFile, tocFile, builderFlags)
 
 	if library.stripper.needsStrip(ctx) {
 		// b/80093681, GNU strip/objcopy bug.
@@ -574,6 +565,8 @@
 		library.stripper.strip(ctx, outputFile, strippedOutputFile, builderFlags)
 	}
 
+	library.unstrippedOutputFile = outputFile
+
 	if Bool(library.baseLinker.Properties.Use_version_lib) && ctx.Host() {
 		versionedOutputFile := outputFile
 		outputFile = android.PathForModuleOut(ctx, "unversioned", fileName)
@@ -604,7 +597,7 @@
 }
 
 func getRefAbiDumpFile(ctx ModuleContext, vndkVersion, fileName string) android.Path {
-	isLlndk := inList(ctx.baseModuleName(), llndkLibraries)
+	isLlndk := inList(ctx.baseModuleName(), llndkLibraries) || inList(ctx.baseModuleName(), ndkMigratedLibs)
 
 	refAbiDumpTextFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndk, false)
 	refAbiDumpGzipFile := android.PathForVndkRefAbiDump(ctx, vndkVersion, fileName, isLlndk, true)
diff --git a/cc/llndk_library.go b/cc/llndk_library.go
index 6e64acf..c23dfd4 100644
--- a/cc/llndk_library.go
+++ b/cc/llndk_library.go
@@ -172,6 +172,7 @@
 		libraryDecorator: library,
 	}
 	stub.Properties.Vendor_available = BoolPtr(true)
+	module.Properties.UseVndk = true
 	module.compiler = stub
 	module.linker = stub
 	module.installer = nil
diff --git a/cc/makevars.go b/cc/makevars.go
index c3ff4ce..17edcdf 100644
--- a/cc/makevars.go
+++ b/cc/makevars.go
@@ -75,6 +75,7 @@
 	ctx.Strict("LLVM_OBJCOPY", "${config.ClangBin}/llvm-objcopy")
 	ctx.Strict("LLVM_STRIP", "${config.ClangBin}/llvm-strip")
 	ctx.Strict("PATH_TO_CLANG_TIDY", "${config.ClangBin}/clang-tidy")
+	ctx.Strict("PATH_TO_CLANG_TIDY_SHELL", "${config.ClangTidyShellPath}")
 	ctx.StrictSorted("CLANG_CONFIG_UNKNOWN_CFLAGS", strings.Join(config.ClangUnknownCflags, " "))
 
 	ctx.Strict("RS_LLVM_PREBUILTS_VERSION", "${config.RSClangVersion}")
@@ -126,14 +127,16 @@
 	ctx.Strict("ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS", strings.Join(asanLdflags, " "))
 	ctx.Strict("ADDRESS_SANITIZER_CONFIG_EXTRA_STATIC_LIBRARIES", strings.Join(asanLibs, " "))
 
+	ctx.Strict("HWADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS", strings.Join(hwasanCflags, " "))
+
 	ctx.Strict("CFI_EXTRA_CFLAGS", strings.Join(cfiCflags, " "))
+	ctx.Strict("CFI_EXTRA_ASFLAGS", strings.Join(cfiAsflags, " "))
 	ctx.Strict("CFI_EXTRA_LDFLAGS", strings.Join(cfiLdflags, " "))
 
 	ctx.Strict("INTEGER_OVERFLOW_EXTRA_CFLAGS", strings.Join(intOverflowCflags, " "))
 
 	ctx.Strict("DEFAULT_C_STD_VERSION", config.CStdVersion)
 	ctx.Strict("DEFAULT_CPP_STD_VERSION", config.CppStdVersion)
-	ctx.Strict("DEFAULT_GCC_CPP_STD_VERSION", config.GccCppStdVersion)
 	ctx.Strict("EXPERIMENTAL_C_STD_VERSION", config.ExperimentalCStdVersion)
 	ctx.Strict("EXPERIMENTAL_CPP_STD_VERSION", config.ExperimentalCppStdVersion)
 
@@ -145,6 +148,9 @@
 
 	ctx.Strict("RS_GLOBAL_INCLUDES", "${config.RsGlobalIncludes}")
 
+	ctx.Strict("SOONG_STRIP_PATH", "${stripPath}")
+	ctx.Strict("XZ", "${xzCmd}")
+
 	nativeHelperIncludeFlags, err := ctx.Eval("${config.CommonNativehelperInclude}")
 	if err != nil {
 		panic(err)
@@ -214,34 +220,6 @@
 		productExtraLdflags += "-static"
 	}
 
-	ctx.Strict(makePrefix+"GLOBAL_CFLAGS", strings.Join([]string{
-		toolchain.Cflags(),
-		"${config.CommonGlobalCflags}",
-		fmt.Sprintf("${config.%sGlobalCflags}", hod),
-		toolchain.ToolchainCflags(),
-		productExtraCflags,
-	}, " "))
-	ctx.Strict(makePrefix+"GLOBAL_CONLYFLAGS", strings.Join([]string{
-		"${config.CommonGlobalConlyflags}",
-	}, " "))
-	ctx.Strict(makePrefix+"GLOBAL_CPPFLAGS", strings.Join([]string{
-		"${config.CommonGlobalCppflags}",
-		fmt.Sprintf("${config.%sGlobalCppflags}", hod),
-		toolchain.Cppflags(),
-	}, " "))
-	ctx.Strict(makePrefix+"GLOBAL_LDFLAGS", strings.Join([]string{
-		fmt.Sprintf("${config.%sGlobalLdflags}", hod),
-		toolchain.Ldflags(),
-		toolchain.ToolchainLdflags(),
-		productExtraLdflags,
-	}, " "))
-	ctx.Strict(makePrefix+"GLOBAL_LLDFLAGS", strings.Join([]string{
-		fmt.Sprintf("${config.%sGlobalLldflags}", hod),
-		toolchain.Ldflags(),
-		toolchain.ToolchainLdflags(),
-		productExtraLdflags,
-	}, " "))
-
 	includeFlags, err := ctx.Eval(toolchain.IncludeFlags())
 	if err != nil {
 		panic(err)
@@ -264,60 +242,51 @@
 		ctx.Strict(makePrefix+"thumb_CFLAGS", flags)
 	}
 
-	if toolchain.ClangSupported() {
-		clangPrefix := secondPrefix + "CLANG_" + typePrefix
-		clangExtras := "-target " + toolchain.ClangTriple()
-		clangExtras += " -B" + config.ToolPath(toolchain)
+	clangPrefix := secondPrefix + "CLANG_" + typePrefix
+	clangExtras := "-target " + toolchain.ClangTriple()
+	clangExtras += " -B" + config.ToolPath(toolchain)
 
-		ctx.Strict(clangPrefix+"GLOBAL_CFLAGS", strings.Join([]string{
-			toolchain.ClangCflags(),
-			"${config.CommonClangGlobalCflags}",
-			fmt.Sprintf("${config.%sClangGlobalCflags}", hod),
-			toolchain.ToolchainClangCflags(),
-			clangExtras,
-			productExtraCflags,
-		}, " "))
-		ctx.Strict(clangPrefix+"GLOBAL_CPPFLAGS", strings.Join([]string{
-			"${config.CommonClangGlobalCppflags}",
-			fmt.Sprintf("${config.%sGlobalCppflags}", hod),
-			toolchain.ClangCppflags(),
-		}, " "))
-		ctx.Strict(clangPrefix+"GLOBAL_LDFLAGS", strings.Join([]string{
-			fmt.Sprintf("${config.%sGlobalLdflags}", hod),
-			toolchain.ClangLdflags(),
-			toolchain.ToolchainClangLdflags(),
-			productExtraLdflags,
-			clangExtras,
-		}, " "))
-		ctx.Strict(clangPrefix+"GLOBAL_LLDFLAGS", strings.Join([]string{
-			fmt.Sprintf("${config.%sGlobalLldflags}", hod),
-			toolchain.ClangLldflags(),
-			toolchain.ToolchainClangLdflags(),
-			productExtraLdflags,
-			clangExtras,
-		}, " "))
+	ctx.Strict(clangPrefix+"GLOBAL_CFLAGS", strings.Join([]string{
+		toolchain.ClangCflags(),
+		"${config.CommonClangGlobalCflags}",
+		fmt.Sprintf("${config.%sClangGlobalCflags}", hod),
+		toolchain.ToolchainClangCflags(),
+		clangExtras,
+		productExtraCflags,
+	}, " "))
+	ctx.Strict(clangPrefix+"GLOBAL_CPPFLAGS", strings.Join([]string{
+		"${config.CommonClangGlobalCppflags}",
+		fmt.Sprintf("${config.%sGlobalCppflags}", hod),
+		toolchain.ClangCppflags(),
+	}, " "))
+	ctx.Strict(clangPrefix+"GLOBAL_LDFLAGS", strings.Join([]string{
+		fmt.Sprintf("${config.%sGlobalLdflags}", hod),
+		toolchain.ClangLdflags(),
+		toolchain.ToolchainClangLdflags(),
+		productExtraLdflags,
+		clangExtras,
+	}, " "))
+	ctx.Strict(clangPrefix+"GLOBAL_LLDFLAGS", strings.Join([]string{
+		fmt.Sprintf("${config.%sGlobalLldflags}", hod),
+		toolchain.ClangLldflags(),
+		toolchain.ToolchainClangLdflags(),
+		productExtraLdflags,
+		clangExtras,
+	}, " "))
 
-		if target.Os.Class == android.Device {
-			ctx.Strict(secondPrefix+"ADDRESS_SANITIZER_RUNTIME_LIBRARY", strings.TrimSuffix(config.AddressSanitizerRuntimeLibrary(toolchain), ".so"))
-			ctx.Strict(secondPrefix+"HWADDRESS_SANITIZER_RUNTIME_LIBRARY", strings.TrimSuffix(config.HWAddressSanitizerRuntimeLibrary(toolchain), ".so"))
-			ctx.Strict(secondPrefix+"HWADDRESS_SANITIZER_STATIC_LIBRARY", strings.TrimSuffix(config.HWAddressSanitizerStaticLibrary(toolchain), ".a"))
-			ctx.Strict(secondPrefix+"UBSAN_RUNTIME_LIBRARY", strings.TrimSuffix(config.UndefinedBehaviorSanitizerRuntimeLibrary(toolchain), ".so"))
-			ctx.Strict(secondPrefix+"UBSAN_MINIMAL_RUNTIME_LIBRARY", strings.TrimSuffix(config.UndefinedBehaviorSanitizerMinimalRuntimeLibrary(toolchain), ".a"))
-			ctx.Strict(secondPrefix+"TSAN_RUNTIME_LIBRARY", strings.TrimSuffix(config.ThreadSanitizerRuntimeLibrary(toolchain), ".so"))
-			ctx.Strict(secondPrefix+"SCUDO_RUNTIME_LIBRARY", strings.TrimSuffix(config.ScudoRuntimeLibrary(toolchain), ".so"))
-		}
-
-		// This is used by external/gentoo/...
-		ctx.Strict("CLANG_CONFIG_"+target.Arch.ArchType.Name+"_"+typePrefix+"TRIPLE",
-			toolchain.ClangTriple())
-
-		ctx.Strict(makePrefix+"CLANG_SUPPORTED", "true")
-	} else {
-		ctx.Strict(makePrefix+"CLANG_SUPPORTED", "")
+	if target.Os.Class == android.Device {
+		ctx.Strict(secondPrefix+"ADDRESS_SANITIZER_RUNTIME_LIBRARY", strings.TrimSuffix(config.AddressSanitizerRuntimeLibrary(toolchain), ".so"))
+		ctx.Strict(secondPrefix+"HWADDRESS_SANITIZER_RUNTIME_LIBRARY", strings.TrimSuffix(config.HWAddressSanitizerRuntimeLibrary(toolchain), ".so"))
+		ctx.Strict(secondPrefix+"HWADDRESS_SANITIZER_STATIC_LIBRARY", strings.TrimSuffix(config.HWAddressSanitizerStaticLibrary(toolchain), ".a"))
+		ctx.Strict(secondPrefix+"UBSAN_RUNTIME_LIBRARY", strings.TrimSuffix(config.UndefinedBehaviorSanitizerRuntimeLibrary(toolchain), ".so"))
+		ctx.Strict(secondPrefix+"UBSAN_MINIMAL_RUNTIME_LIBRARY", strings.TrimSuffix(config.UndefinedBehaviorSanitizerMinimalRuntimeLibrary(toolchain), ".a"))
+		ctx.Strict(secondPrefix+"TSAN_RUNTIME_LIBRARY", strings.TrimSuffix(config.ThreadSanitizerRuntimeLibrary(toolchain), ".so"))
+		ctx.Strict(secondPrefix+"SCUDO_RUNTIME_LIBRARY", strings.TrimSuffix(config.ScudoRuntimeLibrary(toolchain), ".so"))
 	}
 
-	ctx.Strict(makePrefix+"CC", gccCmd(toolchain, "gcc"))
-	ctx.Strict(makePrefix+"CXX", gccCmd(toolchain, "g++"))
+	// This is used by external/gentoo/...
+	ctx.Strict("CLANG_CONFIG_"+target.Arch.ArchType.Name+"_"+typePrefix+"TRIPLE",
+		toolchain.ClangTriple())
 
 	if target.Os == android.Darwin {
 		ctx.Strict(makePrefix+"AR", "${config.MacArPath}")
diff --git a/cc/prebuilt.go b/cc/prebuilt.go
index 3f277aa..47994a8 100644
--- a/cc/prebuilt.go
+++ b/cc/prebuilt.go
@@ -51,6 +51,24 @@
 
 var _ prebuiltLinkerInterface = (*prebuiltLibraryLinker)(nil)
 
+func (p *prebuiltLibraryLinker) linkerInit(ctx BaseModuleContext) {}
+
+func (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
+	// export_header_lib_headers needs to be passed along
+	return Deps{
+		HeaderLibs:               p.baseLinker.Properties.Header_libs,
+		ReexportHeaderLibHeaders: p.baseLinker.Properties.Export_header_lib_headers,
+	}
+}
+
+func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
+	return flags
+}
+
+func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
+	return p.libraryDecorator.linkerProps()
+}
+
 func (p *prebuiltLibraryLinker) link(ctx ModuleContext,
 	flags Flags, deps PathDeps, objs Objects) android.Path {
 	// TODO(ccross): verify shared library dependencies
@@ -58,8 +76,28 @@
 		p.libraryDecorator.exportIncludes(ctx, "-I")
 		p.libraryDecorator.reexportFlags(deps.ReexportedFlags)
 		p.libraryDecorator.reexportDeps(deps.ReexportedFlagsDeps)
-		// TODO(ccross): .toc optimization, stripping, packing
-		return p.Prebuilt.SingleSourcePath(ctx)
+
+		builderFlags := flagsToBuilderFlags(flags)
+
+		in := p.Prebuilt.SingleSourcePath(ctx)
+
+		if p.shared() {
+			p.unstrippedOutputFile = in
+			libName := ctx.baseModuleName() + flags.Toolchain.ShlibSuffix()
+			if p.needsStrip(ctx) {
+				stripped := android.PathForModuleOut(ctx, "stripped", libName)
+				p.strip(ctx, in, stripped, builderFlags)
+				in = stripped
+			}
+
+			// Optimize out relinking against shared libraries whose interface hasn't changed by
+			// depending on a table of contents file instead of the library itself.
+			tocFile := android.PathForModuleOut(ctx, libName+".toc")
+			p.tocFile = android.OptionalPathForPath(tocFile)
+			TransformSharedObjectToToc(ctx, in, tocFile, builderFlags)
+		}
+
+		return in
 	}
 
 	return nil
@@ -118,17 +156,26 @@
 	flags Flags, deps PathDeps, objs Objects) android.Path {
 	// TODO(ccross): verify shared library dependencies
 	if len(p.properties.Srcs) > 0 {
-		// TODO(ccross): .toc optimization, stripping, packing
+		builderFlags := flagsToBuilderFlags(flags)
+
+		fileName := p.getStem(ctx) + flags.Toolchain.ExecutableSuffix()
+		in := p.Prebuilt.SingleSourcePath(ctx)
+
+		p.unstrippedOutputFile = in
+
+		if p.needsStrip(ctx) {
+			stripped := android.PathForModuleOut(ctx, "stripped", fileName)
+			p.strip(ctx, in, stripped, builderFlags)
+			in = stripped
+		}
 
 		// Copy binaries to a name matching the final installed name
-		fileName := p.getStem(ctx) + flags.Toolchain.ExecutableSuffix()
 		outputFile := android.PathForModuleOut(ctx, fileName)
-
 		ctx.Build(pctx, android.BuildParams{
 			Rule:        android.CpExecutable,
 			Description: "prebuilt",
 			Output:      outputFile,
-			Input:       p.Prebuilt.SingleSourcePath(ctx),
+			Input:       in,
 		})
 
 		return outputFile
diff --git a/cc/relocation_packer.go b/cc/relocation_packer.go
deleted file mode 100644
index 8989b29..0000000
--- a/cc/relocation_packer.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright 2016 Google Inc. All rights reserved.
-//
-// 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 cc
-
-import (
-	"runtime"
-
-	"github.com/google/blueprint"
-
-	"android/soong/android"
-)
-
-func init() {
-	pctx.SourcePathVariable("relocationPackerCmd", "prebuilts/misc/${config.HostPrebuiltTag}/relocation_packer/relocation_packer")
-}
-
-var relocationPackerRule = pctx.AndroidStaticRule("packRelocations",
-	blueprint.RuleParams{
-		Command:     "rm -f $out && cp $in $out && $relocationPackerCmd $out",
-		CommandDeps: []string{"$relocationPackerCmd"},
-	})
-
-type RelocationPackerProperties struct {
-	// Generate compact dynamic relocation table, default true.
-	Pack_relocations *bool `android:"arch_variant"`
-
-	// This will be true even if we're embedded in Make, in which case
-	// we'll defer to make to actually do the packing.
-	PackingRelocations bool `blueprint:"mutated"`
-
-	// Use clang lld instead of gnu ld.
-	Use_clang_lld *bool
-}
-
-type relocationPacker struct {
-	Properties RelocationPackerProperties
-}
-
-func (p *relocationPacker) useClangLld(ctx BaseModuleContext) bool {
-	if p.Properties.Use_clang_lld != nil {
-		return Bool(p.Properties.Use_clang_lld)
-	}
-	return ctx.Config().UseClangLld()
-}
-
-func (p *relocationPacker) packingInit(ctx BaseModuleContext) {
-	enabled := true
-	// Relocation packer isn't available on Darwin yet
-	if runtime.GOOS == "darwin" {
-		enabled = false
-	}
-	if ctx.Target().Os != android.Android {
-		enabled = false
-	}
-	if ctx.Config().Getenv("DISABLE_RELOCATION_PACKER") == "true" {
-		enabled = false
-	}
-	// Relocation packer does not work with lld output files.
-	// Packed files won't load.
-	if p.useClangLld(ctx) {
-		enabled = false
-	}
-	if ctx.useSdk() {
-		enabled = false
-	}
-	if p.Properties.Pack_relocations != nil &&
-		*p.Properties.Pack_relocations == false {
-		enabled = false
-	}
-
-	p.Properties.PackingRelocations = enabled
-}
-
-func (p *relocationPacker) needsPacking(ctx ModuleContext) bool {
-	if ctx.Config().EmbeddedInMake() {
-		return false
-	}
-	return p.Properties.PackingRelocations
-}
-
-func (p *relocationPacker) pack(ctx ModuleContext, in, out android.ModuleOutPath, flags builderFlags) {
-	ctx.Build(pctx, android.BuildParams{
-		Rule:        relocationPackerRule,
-		Description: "pack relocations",
-		Output:      out,
-		Input:       in,
-	})
-}
diff --git a/cc/sanitize.go b/cc/sanitize.go
index a522a60..b2fc63f 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -40,6 +40,9 @@
 
 	cfiCflags = []string{"-flto", "-fsanitize-cfi-cross-dso",
 		"-fsanitize-blacklist=external/compiler-rt/lib/cfi/cfi_blacklist.txt"}
+	// -flto and -fvisibility are required by clang when -fsanitize=cfi is
+	// used, but have no effect on assembly files
+	cfiAsflags = []string{"-flto", "-fvisibility=default"}
 	cfiLdflags = []string{"-flto", "-fsanitize-cfi-cross-dso", "-fsanitize=cfi",
 		"-Wl,-plugin-opt,O1"}
 	cfiExportsMapPath     = "build/soong/cc/config/cfi_exports.map"
@@ -460,6 +463,7 @@
 		sanitizers = append(sanitizers, "cfi")
 
 		flags.CFlags = append(flags.CFlags, cfiCflags...)
+		flags.AsFlags = append(flags.AsFlags, cfiAsflags...)
 		// Only append the default visibility flag if -fvisibility has not already been set
 		// to hidden.
 		if !inList("-fvisibility=hidden", flags.CFlags) {
@@ -495,6 +499,7 @@
 		sanitizeArg := "-fsanitize=" + strings.Join(sanitizers, ",")
 
 		flags.CFlags = append(flags.CFlags, sanitizeArg)
+		flags.AsFlags = append(flags.AsFlags, sanitizeArg)
 		if ctx.Host() {
 			flags.CFlags = append(flags.CFlags, "-fno-sanitize-recover=all")
 			flags.LdFlags = append(flags.LdFlags, sanitizeArg)
diff --git a/cc/stl.go b/cc/stl.go
index 6f63835..f44902e 100644
--- a/cc/stl.go
+++ b/cc/stl.go
@@ -19,18 +19,24 @@
 	"fmt"
 )
 
-func getNdkStlFamily(ctx android.ModuleContext, m *Module) string {
+func getNdkStlFamily(m *Module) string {
+	family, _ := getNdkStlFamilyAndLinkType(m)
+	return family
+}
+
+func getNdkStlFamilyAndLinkType(m *Module) (string, string) {
 	stl := m.stl.Properties.SelectedStl
 	switch stl {
-	case "ndk_libc++_shared", "ndk_libc++_static":
-		return "libc++"
+	case "ndk_libc++_shared":
+		return "libc++", "shared"
+	case "ndk_libc++_static":
+		return "libc++", "static"
 	case "ndk_system":
-		return "system"
+		return "system", "shared"
 	case "":
-		return "none"
+		return "none", "none"
 	default:
-		ctx.ModuleErrorf("stl: %q is not a valid STL", stl)
-		return ""
+		panic(fmt.Errorf("stl: %q is not a valid STL", stl))
 	}
 }
 
@@ -207,10 +213,9 @@
 	hostDynamicGccLibs = map[android.OsType][]string{
 		android.Linux:  []string{"-lgcc_s", "-lgcc", "-lc", "-lgcc_s", "-lgcc"},
 		android.Darwin: []string{"-lc", "-lSystem"},
-		android.Windows: []string{"-lmsvcr110", "-lmingw32", "-lgcc", "-lmoldname",
-			"-lmingwex", "-lmsvcrt", "-ladvapi32", "-lshell32", "-luser32",
-			"-lkernel32", "-lmingw32", "-lgcc", "-lmoldname", "-lmingwex",
-			"-lmsvcrt"},
+		android.Windows: []string{"-lmingw32", "-lgcc", "-lmoldname", "-lmingwex", "-lmsvcr110",
+			"-lmsvcrt", "-ladvapi32", "-lshell32", "-luser32", "-lkernel32", "-lmingw32",
+			"-lgcc", "-lmoldname", "-lmingwex", "-lmsvcrt"},
 	}
 	hostStaticGccLibs = map[android.OsType][]string{
 		android.Linux:   []string{"-Wl,--start-group", "-lgcc", "-lgcc_eh", "-lc", "-Wl,--end-group"},
diff --git a/cc/strip.go b/cc/strip.go
index a7c2d4e..02397f4 100644
--- a/cc/strip.go
+++ b/cc/strip.go
@@ -21,6 +21,7 @@
 type StripProperties struct {
 	Strip struct {
 		None         *bool
+		All          *bool
 		Keep_symbols *bool
 	}
 }
@@ -30,17 +31,23 @@
 }
 
 func (stripper *stripper) needsStrip(ctx ModuleContext) bool {
-	return !ctx.Config().EmbeddedInMake() && !Bool(stripper.StripProperties.Strip.None)
+	// TODO(ccross): enable host stripping when embedded in make?  Make never had support for stripping host binaries.
+	return (!ctx.Config().EmbeddedInMake() || ctx.Device()) && !Bool(stripper.StripProperties.Strip.None)
 }
 
-func (stripper *stripper) strip(ctx ModuleContext, in, out android.ModuleOutPath,
+func (stripper *stripper) strip(ctx ModuleContext, in android.Path, out android.ModuleOutPath,
 	flags builderFlags) {
 	if ctx.Darwin() {
 		TransformDarwinStrip(ctx, in, out)
 	} else {
-		flags.stripKeepSymbols = Bool(stripper.StripProperties.Strip.Keep_symbols)
-		// TODO(ccross): don't add gnu debuglink for user builds
-		flags.stripAddGnuDebuglink = true
+		if Bool(stripper.StripProperties.Strip.Keep_symbols) {
+			flags.stripKeepSymbols = true
+		} else if !Bool(stripper.StripProperties.Strip.All) {
+			flags.stripKeepMiniDebugInfo = true
+		}
+		if ctx.Config().Debuggable() && !flags.stripKeepMiniDebugInfo {
+			flags.stripAddGnuDebuglink = true
+		}
 		TransformStrip(ctx, in, out, flags)
 	}
 }
diff --git a/cc/vndk_prebuilt.go b/cc/vndk_prebuilt.go
index 849bb3f..2d7274d 100644
--- a/cc/vndk_prebuilt.go
+++ b/cc/vndk_prebuilt.go
@@ -149,6 +149,7 @@
 	module.stl = nil
 	module.sanitize = nil
 	library.StripProperties.Strip.None = BoolPtr(true)
+	module.Properties.UseVndk = true
 
 	prebuilt := &vndkPrebuiltLibraryDecorator{
 		libraryDecorator: library,
diff --git a/cmd/multiproduct_kati/main.go b/cmd/multiproduct_kati/main.go
index a6bc8d5..374868c 100644
--- a/cmd/multiproduct_kati/main.go
+++ b/cmd/multiproduct_kati/main.go
@@ -18,6 +18,7 @@
 	"context"
 	"flag"
 	"fmt"
+	"io"
 	"io/ioutil"
 	"os"
 	"path/filepath"
@@ -27,6 +28,7 @@
 	"syscall"
 	"time"
 
+	"android/soong/finder"
 	"android/soong/ui/build"
 	"android/soong/ui/logger"
 	"android/soong/ui/status"
@@ -49,6 +51,7 @@
 var numJobs = flag.Int("j", detectNumJobs(), "number of parallel kati jobs")
 
 var keepArtifacts = flag.Bool("keep", false, "keep archives of artifacts")
+var incremental = flag.Bool("incremental", false, "run in incremental mode (saving intermediates)")
 
 var outDir = flag.String("out", "", "path to store output directories (defaults to tmpdir under $OUT when empty)")
 var alternateResultDir = flag.Bool("dist", false, "write select results to $DIST_DIR (or <out>/dist when empty)")
@@ -64,13 +67,6 @@
 const errorLeadingLines = 20
 const errorTrailingLines = 20
 
-type Product struct {
-	ctx     build.Context
-	config  build.Config
-	logFile string
-	action  *status.Action
-}
-
 func errMsgFromLog(filename string) string {
 	if filename == "" {
 		return ""
@@ -131,6 +127,34 @@
 	return false
 }
 
+func copyFile(from, to string) error {
+	fromFile, err := os.Open(from)
+	if err != nil {
+		return err
+	}
+	defer fromFile.Close()
+
+	toFile, err := os.Create(to)
+	if err != nil {
+		return err
+	}
+	defer toFile.Close()
+
+	_, err = io.Copy(toFile, fromFile)
+	return err
+}
+
+type mpContext struct {
+	Context context.Context
+	Logger  logger.Logger
+	Status  status.ToolStatus
+	Tracer  tracer.Tracer
+	Finder  *finder.Finder
+	Config  build.Config
+
+	LogsDir string
+}
+
 func main() {
 	writer := terminal.NewWriter(terminal.StdioImpl{})
 	defer writer.Finish()
@@ -169,7 +193,10 @@
 
 	config := build.NewConfig(buildCtx)
 	if *outDir == "" {
-		name := "multiproduct-" + time.Now().Format("20060102150405")
+		name := "multiproduct"
+		if !*incremental {
+			name += "-" + time.Now().Format("20060102150405")
+		}
 
 		*outDir = filepath.Join(config.OutDir(), name)
 
@@ -231,7 +258,7 @@
 		productsList = allProducts
 	}
 
-	products := make([]string, 0, len(productsList))
+	finalProductsList := make([]string, 0, len(productsList))
 	skipList := strings.Split(*skipProducts, ",")
 	skipProduct := func(p string) bool {
 		for _, s := range skipList {
@@ -243,136 +270,54 @@
 	}
 	for _, product := range productsList {
 		if !skipProduct(product) {
-			products = append(products, product)
+			finalProductsList = append(finalProductsList, product)
 		} else {
 			log.Verbose("Skipping: ", product)
 		}
 	}
 
-	log.Verbose("Got product list: ", products)
+	log.Verbose("Got product list: ", finalProductsList)
 
 	s := buildCtx.Status.StartTool()
-	s.SetTotalActions(len(products))
+	s.SetTotalActions(len(finalProductsList))
 
-	var wg sync.WaitGroup
-	productConfigs := make(chan Product, len(products))
+	mpCtx := &mpContext{
+		Context: ctx,
+		Logger:  log,
+		Status:  s,
+		Tracer:  trace,
 
-	// Run the product config for every product in parallel
-	for _, product := range products {
-		wg.Add(1)
-		go func(product string) {
-			var stdLog string
+		Finder: finder,
+		Config: config,
 
-			defer wg.Done()
-
-			action := &status.Action{
-				Description: product,
-				Outputs:     []string{product},
-			}
-			s.StartAction(action)
-			defer logger.Recover(func(err error) {
-				s.FinishAction(status.ActionResult{
-					Action: action,
-					Error:  err,
-					Output: errMsgFromLog(stdLog),
-				})
-			})
-
-			productOutDir := filepath.Join(config.OutDir(), product)
-			productLogDir := filepath.Join(logsDir, product)
-
-			if err := os.MkdirAll(productOutDir, 0777); err != nil {
-				log.Fatalf("Error creating out directory: %v", err)
-			}
-			if err := os.MkdirAll(productLogDir, 0777); err != nil {
-				log.Fatalf("Error creating log directory: %v", err)
-			}
-
-			stdLog = filepath.Join(productLogDir, "std.log")
-			f, err := os.Create(stdLog)
-			if err != nil {
-				log.Fatalf("Error creating std.log: %v", err)
-			}
-
-			productLog := logger.New(f)
-			productLog.SetOutput(filepath.Join(productLogDir, "soong.log"))
-
-			productCtx := build.Context{ContextImpl: &build.ContextImpl{
-				Context: ctx,
-				Logger:  productLog,
-				Tracer:  trace,
-				Writer:  terminal.NewWriter(terminal.NewCustomStdio(nil, f, f)),
-				Thread:  trace.NewThread(product),
-				Status:  &status.Status{},
-			}}
-			productCtx.Status.AddOutput(terminal.NewStatusOutput(productCtx.Writer, ""))
-
-			productConfig := build.NewConfig(productCtx)
-			productConfig.Environment().Set("OUT_DIR", productOutDir)
-			build.FindSources(productCtx, productConfig, finder)
-			productConfig.Lunch(productCtx, product, *buildVariant)
-
-			build.Build(productCtx, productConfig, build.BuildProductConfig)
-			productConfigs <- Product{productCtx, productConfig, stdLog, action}
-		}(product)
+		LogsDir: logsDir,
 	}
+
+	products := make(chan string, len(productsList))
 	go func() {
-		defer close(productConfigs)
-		wg.Wait()
+		defer close(products)
+		for _, product := range finalProductsList {
+			products <- product
+		}
 	}()
 
-	var wg2 sync.WaitGroup
-	// Then run up to numJobs worth of Soong and Kati
+	var wg sync.WaitGroup
 	for i := 0; i < *numJobs; i++ {
-		wg2.Add(1)
+		wg.Add(1)
 		go func() {
-			defer wg2.Done()
-			for product := range productConfigs {
-				func() {
-					defer logger.Recover(func(err error) {
-						s.FinishAction(status.ActionResult{
-							Action: product.action,
-							Error:  err,
-							Output: errMsgFromLog(product.logFile),
-						})
-					})
-
-					defer func() {
-						if *keepArtifacts {
-							args := zip.ZipArgs{
-								FileArgs: []zip.FileArg{
-									{
-										GlobDir:             product.config.OutDir(),
-										SourcePrefixToStrip: product.config.OutDir(),
-									},
-								},
-								OutputFilePath:   filepath.Join(config.OutDir(), product.config.TargetProduct()+".zip"),
-								NumParallelJobs:  runtime.NumCPU(),
-								CompressionLevel: 5,
-							}
-							if err := zip.Run(args); err != nil {
-								log.Fatalf("Error zipping artifacts: %v", err)
-							}
-						}
-						os.RemoveAll(product.config.OutDir())
-					}()
-
-					buildWhat := 0
-					if !*onlyConfig {
-						buildWhat |= build.BuildSoong
-						if !*onlySoong {
-							buildWhat |= build.BuildKati
-						}
+			defer wg.Done()
+			for {
+				select {
+				case product := <-products:
+					if product == "" {
+						return
 					}
-					build.Build(product.ctx, product.config, buildWhat)
-					s.FinishAction(status.ActionResult{
-						Action: product.action,
-					})
-				}()
+					buildProduct(mpCtx, product)
+				}
 			}
 		}()
 	}
-	wg2.Wait()
+	wg.Wait()
 
 	if *alternateResultDir {
 		args := zip.ZipArgs{
@@ -399,6 +344,111 @@
 	}
 }
 
+func buildProduct(mpctx *mpContext, product string) {
+	var stdLog string
+
+	outDir := filepath.Join(mpctx.Config.OutDir(), product)
+	logsDir := filepath.Join(mpctx.LogsDir, product)
+
+	if err := os.MkdirAll(outDir, 0777); err != nil {
+		mpctx.Logger.Fatalf("Error creating out directory: %v", err)
+	}
+	if err := os.MkdirAll(logsDir, 0777); err != nil {
+		mpctx.Logger.Fatalf("Error creating log directory: %v", err)
+	}
+
+	stdLog = filepath.Join(logsDir, "std.log")
+	f, err := os.Create(stdLog)
+	if err != nil {
+		mpctx.Logger.Fatalf("Error creating std.log: %v", err)
+	}
+	defer f.Close()
+
+	log := logger.New(f)
+	defer log.Cleanup()
+	log.SetOutput(filepath.Join(logsDir, "soong.log"))
+
+	action := &status.Action{
+		Description: product,
+		Outputs:     []string{product},
+	}
+	mpctx.Status.StartAction(action)
+	defer logger.Recover(func(err error) {
+		mpctx.Status.FinishAction(status.ActionResult{
+			Action: action,
+			Error:  err,
+			Output: errMsgFromLog(stdLog),
+		})
+	})
+
+	ctx := build.Context{ContextImpl: &build.ContextImpl{
+		Context: mpctx.Context,
+		Logger:  log,
+		Tracer:  mpctx.Tracer,
+		Writer:  terminal.NewWriter(terminal.NewCustomStdio(nil, f, f)),
+		Thread:  mpctx.Tracer.NewThread(product),
+		Status:  &status.Status{},
+	}}
+	ctx.Status.AddOutput(terminal.NewStatusOutput(ctx.Writer, ""))
+
+	config := build.NewConfig(ctx, flag.Args()...)
+	config.Environment().Set("OUT_DIR", outDir)
+	build.FindSources(ctx, config, mpctx.Finder)
+	config.Lunch(ctx, product, *buildVariant)
+
+	defer func() {
+		if *keepArtifacts {
+			args := zip.ZipArgs{
+				FileArgs: []zip.FileArg{
+					{
+						GlobDir:             outDir,
+						SourcePrefixToStrip: outDir,
+					},
+				},
+				OutputFilePath:   filepath.Join(mpctx.Config.OutDir(), product+".zip"),
+				NumParallelJobs:  runtime.NumCPU(),
+				CompressionLevel: 5,
+			}
+			if err := zip.Run(args); err != nil {
+				log.Fatalf("Error zipping artifacts: %v", err)
+			}
+		}
+		if *incremental {
+			// Save space, Kati doesn't notice
+			if f := config.KatiNinjaFile(); f != "" {
+				os.Truncate(f, 0)
+			}
+		} else {
+			os.RemoveAll(outDir)
+		}
+	}()
+
+	buildWhat := build.BuildProductConfig
+	if !*onlyConfig {
+		buildWhat |= build.BuildSoong
+		if !*onlySoong {
+			buildWhat |= build.BuildKati
+		}
+	}
+
+	before := time.Now()
+	build.Build(ctx, config, buildWhat)
+
+	// Save std_full.log if Kati re-read the makefiles
+	if buildWhat&build.BuildKati != 0 {
+		if after, err := os.Stat(config.KatiNinjaFile()); err == nil && after.ModTime().After(before) {
+			err := copyFile(stdLog, filepath.Join(filepath.Dir(stdLog), "std_full.log"))
+			if err != nil {
+				log.Fatalf("Error copying log file: %s", err)
+			}
+		}
+	}
+
+	mpctx.Status.FinishAction(status.ActionResult{
+		Action: action,
+	})
+}
+
 type failureCount int
 
 func (f *failureCount) StartAction(action *status.Action, counts status.Counts) {}
diff --git a/cmd/pom2bp/pom2bp.go b/cmd/pom2bp/pom2bp.go
index a39642f..a79c84f 100644
--- a/cmd/pom2bp/pom2bp.go
+++ b/cmd/pom2bp/pom2bp.go
@@ -107,7 +107,7 @@
 type HostModuleNames map[string]bool
 
 func (n HostModuleNames) IsHostModule(groupId string, artifactId string) bool {
-	_, found := n[groupId + ":" + artifactId]
+	_, found := n[groupId+":"+artifactId]
 	return found
 }
 
@@ -186,6 +186,34 @@
 	return !p.IsHostModule()
 }
 
+func (p Pom) ModuleType() string {
+	if p.IsAar() {
+		return "android_library"
+	} else if p.IsHostModule() {
+		return "java_library_host"
+	} else {
+		return "java_library_static"
+	}
+}
+
+func (p Pom) ImportModuleType() string {
+	if p.IsAar() {
+		return "android_library_import"
+	} else if p.IsHostModule() {
+		return "java_import_host"
+	} else {
+		return "java_import"
+	}
+}
+
+func (p Pom) ImportProperty() string {
+	if p.IsAar() {
+		return "aars"
+	} else {
+		return "jars"
+	}
+}
+
 func (p Pom) BpName() string {
 	if p.BpTarget == "" {
 		p.BpTarget = rewriteNames.MavenToBp(p.GroupId, p.ArtifactId)
@@ -293,27 +321,43 @@
 }
 
 var bpTemplate = template.Must(template.New("bp").Parse(`
-{{if .IsAar}}android_library_import{{else}}java_import{{end}} {
+{{.ImportModuleType}} {
     name: "{{.BpName}}-nodeps",
-    {{if .IsAar}}aars{{else}}jars{{end}}: ["{{.ArtifactFile}}"],
-    sdk_version: "{{.SdkVersion}}",{{if .IsAar}}
+    {{.ImportProperty}}: ["{{.ArtifactFile}}"],
+    sdk_version: "{{.SdkVersion}}",
+    {{- if .IsAar}}
     min_sdk_version: "{{.MinSdkVersion}}",
-    static_libs: [{{range .BpAarDeps}}
-        "{{.}}",{{end}}{{range .BpExtraDeps}}
-        "{{.}}",{{end}}
-    ],{{end}}
+    static_libs: [
+        {{- range .BpAarDeps}}
+        "{{.}}",
+        {{- end}}
+        {{- range .BpExtraDeps}}
+        "{{.}}",
+        {{- end}}
+    ],
+    {{- end}}
 }
 
-{{if .IsAar}}android_library{{else}}{{if .IsDeviceModule}}java_library_static{{else}}java_library_host{{end}}{{end}} {
-    name: "{{.BpName}}",{{if .IsDeviceModule}}
-    sdk_version: "{{.SdkVersion}}",{{if .IsAar}}
+{{.ModuleType}} {
+    name: "{{.BpName}}",
+    {{- if .IsDeviceModule}}
+    sdk_version: "{{.SdkVersion}}",
+    {{- if .IsAar}}
     min_sdk_version: "{{.MinSdkVersion}}",
-    manifest: "manifests/{{.BpName}}/AndroidManifest.xml",{{end}}{{end}}
+    manifest: "manifests/{{.BpName}}/AndroidManifest.xml",
+    {{- end}}
+    {{- end}}
     static_libs: [
-        "{{.BpName}}-nodeps",{{range .BpJarDeps}}
-        "{{.}}",{{end}}{{range .BpAarDeps}}
-        "{{.}}",{{end}}{{range .BpExtraDeps}}
-        "{{.}}",{{end}}
+        "{{.BpName}}-nodeps",
+         {{- range .BpJarDeps}}
+        "{{.}}",
+        {{- end}}
+        {{- range .BpAarDeps}}
+        "{{.}}",
+        {{- end}}
+        {{- range .BpExtraDeps}}
+        "{{.}}",
+        {{- end}}
     ],
     java_version: "1.7",
 }
diff --git a/java/aar.go b/java/aar.go
index e6a412c..29f5597 100644
--- a/java/aar.go
+++ b/java/aar.go
@@ -156,7 +156,7 @@
 	if !ctx.Config().UnbundledBuild() {
 		sdkDep := decodeSdkDep(ctx, sdkContext)
 		if sdkDep.frameworkResModule != "" {
-			ctx.AddDependency(ctx.Module(), frameworkResTag, sdkDep.frameworkResModule)
+			ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
 		}
 	}
 }
@@ -375,6 +375,9 @@
 
 	Static_libs []string
 	Libs        []string
+
+	// if set to true, run Jetifier against .aar file. Defaults to false.
+	Jetifier_enabled *bool
 }
 
 type AARImport struct {
@@ -433,12 +436,12 @@
 	if !ctx.Config().UnbundledBuild() {
 		sdkDep := decodeSdkDep(ctx, sdkContext(a))
 		if sdkDep.useModule && sdkDep.frameworkResModule != "" {
-			ctx.AddDependency(ctx.Module(), frameworkResTag, sdkDep.frameworkResModule)
+			ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
 		}
 	}
 
-	ctx.AddDependency(ctx.Module(), libTag, a.properties.Libs...)
-	ctx.AddDependency(ctx.Module(), staticLibTag, a.properties.Static_libs...)
+	ctx.AddVariationDependencies(nil, libTag, a.properties.Libs...)
+	ctx.AddVariationDependencies(nil, staticLibTag, a.properties.Static_libs...)
 }
 
 // Unzip an AAR into its constituent files and directories.  Any files in Outputs that don't exist in the AAR will be
@@ -456,7 +459,14 @@
 		return
 	}
 
-	aar := android.PathForModuleSrc(ctx, a.properties.Aars[0])
+	aarName := ctx.ModuleName() + ".aar"
+	var aar android.Path
+	aar = android.PathForModuleSrc(ctx, a.properties.Aars[0])
+	if Bool(a.properties.Jetifier_enabled) {
+		inputFile := aar
+		aar = android.PathForModuleOut(ctx, "jetifier", aarName)
+		TransformJetifier(ctx, aar.(android.WritablePath), inputFile)
+	}
 
 	extractedAARDir := android.PathForModuleOut(ctx, "aar")
 	extractedResDir := extractedAARDir.Join(ctx, "res")
diff --git a/java/android_manifest.go b/java/android_manifest.go
index 77b6214..168a22d 100644
--- a/java/android_manifest.go
+++ b/java/android_manifest.go
@@ -25,10 +25,14 @@
 
 var manifestFixerRule = pctx.AndroidStaticRule("manifestFixer",
 	blueprint.RuleParams{
-		Command:     `${config.ManifestFixerCmd} --minSdkVersion ${minSdkVersion} $args $in $out`,
+		Command: `${config.ManifestFixerCmd} ` +
+			`--minSdkVersion ${minSdkVersion} ` +
+			`--targetSdkVersion ${targetSdkVersion} ` +
+			`--raise-min-sdk-version ` +
+			`$args $in $out`,
 		CommandDeps: []string{"${config.ManifestFixerCmd}"},
 	},
-	"minSdkVersion", "args")
+	"minSdkVersion", "targetSdkVersion", "args")
 
 var manifestMergerRule = pctx.AndroidStaticRule("manifestMerger",
 	blueprint.RuleParams{
@@ -53,8 +57,9 @@
 		Input:  manifest,
 		Output: fixedManifest,
 		Args: map[string]string{
-			"minSdkVersion": sdkVersionOrDefault(ctx, sdkContext.minSdkVersion()),
-			"args":          strings.Join(args, " "),
+			"minSdkVersion":    sdkVersionOrDefault(ctx, sdkContext.minSdkVersion()),
+			"targetSdkVersion": sdkVersionOrDefault(ctx, sdkContext.sdkVersion()),
+			"args":             strings.Join(args, " "),
 		},
 	})
 	manifest = fixedManifest
@@ -68,7 +73,7 @@
 			Implicits: staticLibManifests,
 			Output:    mergedManifest,
 			Args: map[string]string{
-				"libs": android.JoinWithPrefix(staticLibManifests.Strings(), "--uses-library "),
+				"libs": android.JoinWithPrefix(staticLibManifests.Strings(), "--libs "),
 			},
 		})
 		manifest = mergedManifest
diff --git a/java/androidmk.go b/java/androidmk.go
index 877d840..509ad94 100644
--- a/java/androidmk.go
+++ b/java/androidmk.go
@@ -70,7 +70,7 @@
 				// Temporary hack: export sources used to compile framework.jar to Make
 				// to be used for droiddoc
 				// TODO(ccross): remove this once droiddoc is in soong
-				if library.Name() == "framework" {
+				if (library.Name() == "framework") || (library.Name() == "framework-annotation-proc") {
 					fmt.Fprintln(w, "SOONG_FRAMEWORK_SRCS :=", strings.Join(library.compiledJavaSrcs.Strings(), " "))
 					fmt.Fprintln(w, "SOONG_FRAMEWORK_SRCJARS :=", strings.Join(library.compiledSrcJars.Strings(), " "))
 				}
@@ -319,15 +319,12 @@
 		Include:    "$(BUILD_SYSTEM)/soong_droiddoc_prebuilt.mk",
 		Extra: []android.AndroidMkExtraFunc{
 			func(w io.Writer, outputFile android.Path) {
-				if BoolDefault(ddoc.Javadoc.properties.Installable, true) {
+				if BoolDefault(ddoc.Javadoc.properties.Installable, true) && ddoc.Javadoc.docZip != nil {
 					fmt.Fprintln(w, "LOCAL_DROIDDOC_DOC_ZIP := ", ddoc.Javadoc.docZip.String())
 				}
 				if ddoc.Javadoc.stubsSrcJar != nil {
 					fmt.Fprintln(w, "LOCAL_DROIDDOC_STUBS_SRCJAR := ", ddoc.Javadoc.stubsSrcJar.String())
 				}
-				if ddoc.annotationsZip != nil {
-					fmt.Fprintln(w, "LOCAL_DROIDDOC_ANNOTATIONS_ZIP := ", ddoc.annotationsZip.String())
-				}
 				if ddoc.checkCurrentApiTimestamp != nil {
 					fmt.Fprintln(w, ".PHONY:", ddoc.Name()+"-check-current-api")
 					fmt.Fprintln(w, ddoc.Name()+"-check-current-api:",
@@ -387,6 +384,75 @@
 	}
 }
 
+func (dstubs *Droidstubs) AndroidMk() android.AndroidMkData {
+	return android.AndroidMkData{
+		Class:      "JAVA_LIBRARIES",
+		OutputFile: android.OptionalPathForPath(dstubs.stubsSrcJar),
+		Include:    "$(BUILD_SYSTEM)/soong_droiddoc_prebuilt.mk",
+		Extra: []android.AndroidMkExtraFunc{
+			func(w io.Writer, outputFile android.Path) {
+				if dstubs.Javadoc.stubsSrcJar != nil {
+					fmt.Fprintln(w, "LOCAL_DROIDDOC_STUBS_SRCJAR := ", dstubs.Javadoc.stubsSrcJar.String())
+				}
+				if dstubs.annotationsZip != nil {
+					fmt.Fprintln(w, "LOCAL_DROIDDOC_ANNOTATIONS_ZIP := ", dstubs.annotationsZip.String())
+				}
+				if dstubs.checkCurrentApiTimestamp != nil {
+					fmt.Fprintln(w, ".PHONY:", dstubs.Name()+"-check-current-api")
+					fmt.Fprintln(w, dstubs.Name()+"-check-current-api:",
+						dstubs.checkCurrentApiTimestamp.String())
+
+					fmt.Fprintln(w, ".PHONY: checkapi")
+					fmt.Fprintln(w, "checkapi:",
+						dstubs.checkCurrentApiTimestamp.String())
+
+					fmt.Fprintln(w, ".PHONY: droidcore")
+					fmt.Fprintln(w, "droidcore: checkapi")
+				}
+				if dstubs.updateCurrentApiTimestamp != nil {
+					fmt.Fprintln(w, ".PHONY:", dstubs.Name()+"-update-current-api")
+					fmt.Fprintln(w, dstubs.Name()+"-update-current-api:",
+						dstubs.updateCurrentApiTimestamp.String())
+
+					fmt.Fprintln(w, ".PHONY: update-api")
+					fmt.Fprintln(w, "update-api:",
+						dstubs.updateCurrentApiTimestamp.String())
+				}
+				if dstubs.checkLastReleasedApiTimestamp != nil {
+					fmt.Fprintln(w, ".PHONY:", dstubs.Name()+"-check-last-released-api")
+					fmt.Fprintln(w, dstubs.Name()+"-check-last-released-api:",
+						dstubs.checkLastReleasedApiTimestamp.String())
+				}
+				apiFilePrefix := "INTERNAL_PLATFORM_"
+				if String(dstubs.properties.Api_tag_name) != "" {
+					apiFilePrefix += String(dstubs.properties.Api_tag_name) + "_"
+				}
+				if dstubs.apiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"API_FILE := ", dstubs.apiFile.String())
+				}
+				if dstubs.dexApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"DEX_API_FILE := ", dstubs.dexApiFile.String())
+				}
+				if dstubs.privateApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"PRIVATE_API_FILE := ", dstubs.privateApiFile.String())
+				}
+				if dstubs.privateDexApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"PRIVATE_DEX_API_FILE := ", dstubs.privateDexApiFile.String())
+				}
+				if dstubs.removedApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"REMOVED_API_FILE := ", dstubs.removedApiFile.String())
+				}
+				if dstubs.removedDexApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"REMOVED_DEX_API_FILE := ", dstubs.removedDexApiFile.String())
+				}
+				if dstubs.exactApiFile != nil {
+					fmt.Fprintln(w, apiFilePrefix+"EXACT_API_FILE := ", dstubs.exactApiFile.String())
+				}
+			},
+		},
+	}
+}
+
 func androidMkWriteTestData(data android.Paths, ret *android.AndroidMkData) {
 	var testFiles []string
 	for _, d := range data {
diff --git a/java/builder.go b/java/builder.go
index ff5de09..48b5a7b 100644
--- a/java/builder.go
+++ b/java/builder.go
@@ -24,6 +24,7 @@
 	"strings"
 
 	"github.com/google/blueprint"
+	"github.com/google/blueprint/proptools"
 
 	"android/soong/android"
 )
@@ -61,13 +62,12 @@
 
 	kotlinc = pctx.AndroidGomaStaticRule("kotlinc",
 		blueprint.RuleParams{
-			Command: `rm -rf "$outDir" "$srcJarDir" && mkdir -p "$outDir" "$srcJarDir" && ` +
+			Command: `rm -rf "$classesDir" "$srcJarDir" "$kotlinBuildFile" && mkdir -p "$classesDir" "$srcJarDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
-				`${config.GenKotlinBuildFileCmd} $classpath $outDir $out.rsp $srcJarDir/list > $outDir/kotlinc-build.xml &&` +
+				`${config.GenKotlinBuildFileCmd} $classpath $classesDir $out.rsp $srcJarDir/list > $kotlinBuildFile &&` +
 				`${config.KotlincCmd} $kotlincFlags ` +
-				`-jvm-target $kotlinJvmTarget -Xbuild-file=$outDir/kotlinc-build.xml && ` +
-				`rm $outDir/kotlinc-build.xml && ` +
-				`${config.SoongZipCmd} -jar -o $out -C $outDir -D $outDir`,
+				`-jvm-target $kotlinJvmTarget -Xbuild-file=$kotlinBuildFile && ` +
+				`${config.SoongZipCmd} -jar -o $out -C $classesDir -D $classesDir`,
 			CommandDeps: []string{
 				"${config.KotlincCmd}",
 				"${config.KotlinCompilerJar}",
@@ -78,7 +78,7 @@
 			Rspfile:        "$out.rsp",
 			RspfileContent: `$in`,
 		},
-		"kotlincFlags", "classpath", "srcJars", "srcJarDir", "outDir", "kotlinJvmTarget")
+		"kotlincFlags", "classpath", "srcJars", "srcJarDir", "classesDir", "kotlinJvmTarget", "kotlinBuildFile")
 
 	turbine = pctx.AndroidStaticRule("turbine",
 		blueprint.RuleParams{
@@ -122,6 +122,13 @@
 			CommandDeps: []string{"${config.JavaCmd}", "${config.JarjarCmd}", "$rulesFile"},
 		},
 		"rulesFile")
+
+	jetifier = pctx.AndroidStaticRule("jetifier",
+		blueprint.RuleParams{
+			Command:     "${config.JavaCmd} -jar ${config.JetifierJar} -l error -o $out -i $in",
+			CommandDeps: []string{"${config.JavaCmd}", "${config.JetifierJar}"},
+		},
+	)
 )
 
 func init() {
@@ -167,11 +174,12 @@
 		Inputs:      inputs,
 		Implicits:   deps,
 		Args: map[string]string{
-			"classpath":    flags.kotlincClasspath.FormJavaClassPath("-classpath"),
-			"kotlincFlags": flags.kotlincFlags,
-			"srcJars":      strings.Join(srcJars.Strings(), " "),
-			"outDir":       android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
-			"srcJarDir":    android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
+			"classpath":       flags.kotlincClasspath.FormJavaClassPath("-classpath"),
+			"kotlincFlags":    flags.kotlincFlags,
+			"srcJars":         strings.Join(srcJars.Strings(), " "),
+			"classesDir":      android.PathForModuleOut(ctx, "kotlinc", "classes").String(),
+			"srcJarDir":       android.PathForModuleOut(ctx, "kotlinc", "srcJars").String(),
+			"kotlinBuildFile": android.PathForModuleOut(ctx, "kotlinc-build.xml").String(),
 			// http://b/69160377 kotlinc only supports -jvm-target 1.6 and 1.8
 			"kotlinJvmTarget": "1.8",
 		},
@@ -313,7 +321,7 @@
 		Output:      outputFile,
 		Implicits:   deps,
 		Args: map[string]string{
-			"jarArgs": strings.Join(jarArgs, " "),
+			"jarArgs": strings.Join(proptools.NinjaEscape(jarArgs), " "),
 		},
 	})
 }
@@ -372,6 +380,16 @@
 	})
 }
 
+func TransformJetifier(ctx android.ModuleContext, outputFile android.WritablePath,
+	inputFile android.Path) {
+	ctx.Build(pctx, android.BuildParams{
+		Rule:        jetifier,
+		Description: "jetifier",
+		Output:      outputFile,
+		Input:       inputFile,
+	})
+}
+
 type classpath []android.Path
 
 func (x *classpath) FormJavaClassPath(optName string) string {
diff --git a/java/config/config.go b/java/config/config.go
index fa8cb0f..3d27b70 100644
--- a/java/config/config.go
+++ b/java/config/config.go
@@ -27,7 +27,7 @@
 var (
 	pctx = android.NewPackageContext("android/soong/java/config")
 
-	DefaultBootclasspathLibraries = []string{"core-oj", "core-libart"}
+	DefaultBootclasspathLibraries = []string{"core-oj", "core-libart", "core-simple"}
 	DefaultSystemModules          = "core-system-modules"
 	DefaultLibraries              = []string{"ext", "framework", "okhttp"}
 	DefaultLambdaStubsLibrary     = "core-lambda-stubs"
@@ -43,6 +43,7 @@
 		"android.car7",
 		"core-oj",
 		"core-libart",
+		"core-simple",
 	}
 
 	ManifestMergerClasspath = []string{
@@ -122,6 +123,7 @@
 	pctx.HostJavaToolVariable("DoclavaJar", "doclava.jar")
 	pctx.HostJavaToolVariable("MetalavaJar", "metalava.jar")
 	pctx.HostJavaToolVariable("DokkaJar", "dokka.jar")
+	pctx.HostJavaToolVariable("JetifierJar", "jetifier.jar")
 
 	pctx.HostBinToolVariable("SoongJavacWrapper", "soong_javac_wrapper")
 
diff --git a/java/dex.go b/java/dex.go
index 054a176..6445940 100644
--- a/java/dex.go
+++ b/java/dex.go
@@ -42,6 +42,7 @@
 			`rm -f "$outDict" && ` +
 			`${config.R8Cmd} -injars $in --output $outDir ` +
 			`--force-proguard-compatibility ` +
+			`--no-data-resources ` +
 			`-printmapping $outDict ` +
 			`$dxFlags $r8Flags && ` +
 			`touch "$outDict" && ` +
diff --git a/java/droiddoc.go b/java/droiddoc.go
index 52db705..ad2a580 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -31,7 +31,7 @@
 			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
 				`${config.JavadocCmd} -encoding UTF-8 @$out.rsp @$srcJarDir/list ` +
-				`$opts $bootclasspathArgs $classpathArgs -sourcepath $sourcepath ` +
+				`$opts $bootclasspathArgs $classpathArgs $sourcepathArgs ` +
 				`-d $outDir -quiet  && ` +
 				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
 				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir $postDoclavaCmds`,
@@ -45,7 +45,7 @@
 			Restat:         true,
 		},
 		"outDir", "srcJarDir", "stubsDir", "srcJars", "opts",
-		"bootclasspathArgs", "classpathArgs", "sourcepath", "docZip", "postDoclavaCmds")
+		"bootclasspathArgs", "classpathArgs", "sourcepathArgs", "docZip", "postDoclavaCmds")
 
 	apiCheck = pctx.AndroidStaticRule("apiCheck",
 		blueprint.RuleParams{
@@ -60,41 +60,39 @@
 
 	updateApi = pctx.AndroidStaticRule("updateApi",
 		blueprint.RuleParams{
-			Command: `( ( cp -f $apiFileToCheck $apiFile && cp -f $removedApiFileToCheck $removedApiFile ) ` +
+			Command: `( ( cp -f $srcApiFile $destApiFile && cp -f $srcRemovedApiFile $destRemovedApiFile ) ` +
 				`&& touch $out ) || (echo failed to update public API ; exit 38)`,
 		},
-		"apiFile", "apiFileToCheck", "removedApiFile", "removedApiFileToCheck")
+		"srcApiFile", "destApiFile", "srcRemovedApiFile", "destRemovedApiFile")
 
 	metalava = pctx.AndroidStaticRule("metalava",
 		blueprint.RuleParams{
-			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" "$docStubsDir" && ` +
-				`mkdir -p "$outDir" "$srcJarDir" "$stubsDir" "$docStubsDir" && ` +
+			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && ` +
+				`mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
 				`${config.JavaCmd} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
-				`$bootclasspathArgs $classpathArgs -sourcepath $sourcepath --no-banner --color --quiet ` +
-				`--stubs $stubsDir $opts && ` +
-				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
+				`$bootclasspathArgs $classpathArgs $sourcepathArgs --no-banner --color --quiet ` +
+				`$opts && ` +
 				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir`,
 			CommandDeps: []string{
 				"${config.ZipSyncCmd}",
 				"${config.JavaCmd}",
 				"${config.MetalavaJar}",
-				"${config.JavadocCmd}",
 				"${config.SoongZipCmd}",
 			},
 			Rspfile:        "$out.rsp",
 			RspfileContent: "$in",
 			Restat:         true,
 		},
-		"outDir", "srcJarDir", "stubsDir", "docStubsDir", "srcJars", "javaVersion", "bootclasspathArgs",
-		"classpathArgs", "sourcepath", "opts", "docZip")
+		"outDir", "srcJarDir", "stubsDir", "srcJars", "javaVersion", "bootclasspathArgs",
+		"classpathArgs", "sourcepathArgs", "opts")
 
 	metalavaApiCheck = pctx.AndroidStaticRule("metalavaApiCheck",
 		blueprint.RuleParams{
 			Command: `( rm -rf "$srcJarDir" && mkdir -p "$srcJarDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
 				`${config.JavaCmd} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
-				`$bootclasspathArgs $classpathArgs -sourcepath $sourcepath --no-banner --color --quiet ` +
+				`$bootclasspathArgs $classpathArgs $sourcepathArgs --no-banner --color --quiet ` +
 				`$opts && touch $out ) || ` +
 				`( echo -e "$msg" ; exit 38 )`,
 			CommandDeps: []string{
@@ -105,17 +103,40 @@
 			Rspfile:        "$out.rsp",
 			RspfileContent: "$in",
 		},
-		"srcJarDir", "srcJars", "javaVersion", "bootclasspathArgs", "classpathArgs", "sourcepath", "opts", "msg")
+		"srcJarDir", "srcJars", "javaVersion", "bootclasspathArgs", "classpathArgs", "sourcepathArgs", "opts", "msg")
+
+	dokka = pctx.AndroidStaticRule("dokka",
+		blueprint.RuleParams{
+			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && ` +
+				`mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
+				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
+				`${config.JavaCmd} -jar ${config.DokkaJar} $srcJarDir ` +
+				`$classpathArgs -format dac -dacRoot /reference/kotlin -output $outDir $opts && ` +
+				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
+				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir`,
+			CommandDeps: []string{
+				"${config.ZipSyncCmd}",
+				"${config.DokkaJar}",
+				"${config.MetalavaJar}",
+				"${config.SoongZipCmd}",
+			},
+			Restat: true,
+		},
+		"outDir", "srcJarDir", "stubsDir", "srcJars", "classpathArgs", "opts", "docZip")
 )
 
 func init() {
 	android.RegisterModuleType("doc_defaults", DocDefaultsFactory)
+	android.RegisterModuleType("stubs_defaults", StubsDefaultsFactory)
 
 	android.RegisterModuleType("droiddoc", DroiddocFactory)
 	android.RegisterModuleType("droiddoc_host", DroiddocHostFactory)
 	android.RegisterModuleType("droiddoc_exported_dir", ExportedDroiddocDirFactory)
 	android.RegisterModuleType("javadoc", JavadocFactory)
 	android.RegisterModuleType("javadoc_host", JavadocHostFactory)
+
+	android.RegisterModuleType("droidstubs", DroidstubsFactory)
+	android.RegisterModuleType("droidstubs_host", DroidstubsHostFactory)
 }
 
 var (
@@ -168,6 +189,18 @@
 
 	// If not blank, set the java version passed to javadoc as -source
 	Java_version *string
+
+	// local files that are used within user customized droiddoc options.
+	Arg_files []string
+
+	// user customized droiddoc args.
+	// Available variables for substitution:
+	//
+	//  $(location <label>): the path to the arg_files with name <label>
+	Args *string
+
+	// names of the output files used in args that will be generated
+	Out []string
 }
 
 type ApiToCheck struct {
@@ -208,18 +241,6 @@
 	// resources output directory under out/soong/.intermediates.
 	Resourcesoutdir *string
 
-	// local files that are used within user customized droiddoc options.
-	Arg_files []string
-
-	// user customized droiddoc args.
-	// Available variables for substitution:
-	//
-	//  $(location <label>): the path to the arg_files with name <label>
-	Args *string
-
-	// names of the output files used in args that will be generated
-	Out []string
-
 	// if set to true, collect the values used by the Dev tools and
 	// write them in files packaged with the SDK. Defaults to false.
 	Write_sdk_values *bool
@@ -274,31 +295,75 @@
 		Current ApiToCheck
 	}
 
-	// if set to true, create stubs through Metalava instead of Doclava. Javadoc/Doclava is
-	// currently still used for documentation generation, and will be replaced by Dokka soon.
-	Metalava_enabled *bool
+	// if set to true, generate docs through Dokka instead of Doclava.
+	Dokka_enabled *bool
+}
+
+type DroidstubsProperties struct {
+	// the tag name used to distinguish if the API files belong to public/system/test.
+	Api_tag_name *string
+
+	// the generated public API filename by Doclava.
+	Api_filename *string
+
+	// the generated public Dex API filename by Doclava.
+	Dex_api_filename *string
+
+	// the generated private API filename by Doclava.
+	Private_api_filename *string
+
+	// the generated private Dex API filename by Doclava.
+	Private_dex_api_filename *string
+
+	// the generated removed API filename by Doclava.
+	Removed_api_filename *string
+
+	// the generated removed Dex API filename by Doclava.
+	Removed_dex_api_filename *string
+
+	// mapping of dex signatures to source file and line number. This is a temporary property and
+	// will be deleted; you probably shouldn't be using it.
+	Dex_mapping_filename *string
+
+	// the generated exact API filename by Doclava.
+	Exact_api_filename *string
+
+	Check_api struct {
+		Last_released ApiToCheck
+
+		Current ApiToCheck
+	}
 
 	// user can specify the version of previous released API file in order to do compatibility check.
-	Metalava_previous_api *string
+	Previous_api *string
 
 	// is set to true, Metalava will allow framework SDK to contain annotations.
-	Metalava_annotations_enabled *bool
+	Annotations_enabled *bool
 
 	// a list of top-level directories containing files to merge annotations from.
-	Metalava_merge_annotations_dirs []string
+	Merge_annotations_dirs []string
 
-	// if set to true, generate docs through Dokka instead of Doclava. Valid only when
-	// metalava_enabled is set to true.
-	Dokka_enabled *bool
+	// if set to true, allow Metalava to generate doc_stubs source files. Defaults to false.
+	Create_doc_stubs *bool
+
+	// is set to true, Metalava will allow framework SDK to contain API levels annotations.
+	Api_levels_annotations_enabled *bool
+
+	// the dirs which Metalava extracts API levels annotations from.
+	Api_levels_annotations_dirs []string
+
+	// if set to true, collect the values used by the Dev tools and
+	// write them in files packaged with the SDK. Defaults to false.
+	Write_sdk_values *bool
 }
 
 //
 // Common flags passed down to build rule
 //
 type droiddocBuilderFlags struct {
-	args               string
 	bootClasspathArgs  string
 	classpathArgs      string
+	sourcepathArgs     string
 	dokkaClasspathArgs string
 	aidlFlags          string
 
@@ -306,9 +371,9 @@
 	doclavaDocsFlags  string
 	postDoclavaCmds   string
 
-	metalavaStubsFlags       string
-	metalavaAnnotationsFlags string
-	metalavaJavadocFlags     string
+	metalavaStubsFlags                string
+	metalavaAnnotationsFlags          string
+	metalavaApiLevelsAnnotationsFlags string
 
 	metalavaDokkaFlags string
 }
@@ -318,6 +383,39 @@
 	android.InitDefaultableModule(module)
 }
 
+func apiCheckEnabled(apiToCheck ApiToCheck, apiVersionTag string) bool {
+	if String(apiToCheck.Api_file) != "" && String(apiToCheck.Removed_api_file) != "" {
+		return true
+	} else if String(apiToCheck.Api_file) != "" {
+		panic("for " + apiVersionTag + " removed_api_file has to be non-empty!")
+	} else if String(apiToCheck.Removed_api_file) != "" {
+		panic("for " + apiVersionTag + " api_file has to be non-empty!")
+	}
+
+	return false
+}
+
+type ApiFilePath interface {
+	ApiFilePath() android.Path
+}
+
+func transformUpdateApi(ctx android.ModuleContext, destApiFile, destRemovedApiFile,
+	srcApiFile, srcRemovedApiFile android.Path, output android.WritablePath) {
+	ctx.Build(pctx, android.BuildParams{
+		Rule:        updateApi,
+		Description: "Update API",
+		Output:      output,
+		Implicits: append(android.Paths{}, srcApiFile, srcRemovedApiFile,
+			destApiFile, destRemovedApiFile),
+		Args: map[string]string{
+			"destApiFile":        destApiFile.String(),
+			"srcApiFile":         srcApiFile.String(),
+			"destRemovedApiFile": destRemovedApiFile.String(),
+			"srcRemovedApiFile":  srcRemovedApiFile.String(),
+		},
+	})
+}
+
 //
 // Javadoc
 //
@@ -330,6 +428,9 @@
 	srcJars     android.Paths
 	srcFiles    android.Paths
 	sourcepaths android.Paths
+	argFiles    android.Paths
+
+	args string
 
 	docZip      android.WritablePath
 	stubsSrcJar android.WritablePath
@@ -371,30 +472,33 @@
 	if ctx.Device() {
 		sdkDep := decodeSdkDep(ctx, sdkContext(j))
 		if sdkDep.useDefaultLibs {
-			ctx.AddDependency(ctx.Module(), bootClasspathTag, config.DefaultBootclasspathLibraries...)
+			ctx.AddVariationDependencies(nil, bootClasspathTag, config.DefaultBootclasspathLibraries...)
 			if ctx.Config().TargetOpenJDK9() {
-				ctx.AddDependency(ctx.Module(), systemModulesTag, config.DefaultSystemModules)
+				ctx.AddVariationDependencies(nil, systemModulesTag, config.DefaultSystemModules)
 			}
 			if !Bool(j.properties.No_framework_libs) {
-				ctx.AddDependency(ctx.Module(), libTag, config.DefaultLibraries...)
+				ctx.AddVariationDependencies(nil, libTag, config.DefaultLibraries...)
 			}
 		} else if sdkDep.useModule {
 			if ctx.Config().TargetOpenJDK9() {
-				ctx.AddDependency(ctx.Module(), systemModulesTag, sdkDep.systemModules)
+				ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
 			}
-			ctx.AddDependency(ctx.Module(), bootClasspathTag, sdkDep.modules...)
+			ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.modules...)
 		}
 	}
 
-	ctx.AddDependency(ctx.Module(), libTag, j.properties.Libs...)
+	ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
 	if j.properties.Srcs_lib != nil {
-		ctx.AddDependency(ctx.Module(), srcsLibTag, *j.properties.Srcs_lib)
+		ctx.AddVariationDependencies(nil, srcsLibTag, *j.properties.Srcs_lib)
 	}
 
 	android.ExtractSourcesDeps(ctx, j.properties.Srcs)
 
 	// exclude_srcs may contain filegroup or genrule.
 	android.ExtractSourcesDeps(ctx, j.properties.Exclude_srcs)
+
+	// arg_files may contains filegroup or genrule.
+	android.ExtractSourcesDeps(ctx, j.properties.Arg_files)
 }
 
 func (j *Javadoc) genWhitelistPathPrefixes(whitelistPathPrefixes map[string]bool) {
@@ -514,7 +618,7 @@
 					if _, ok := src.(android.WritablePath); ok { // generated sources
 						deps.srcs = append(deps.srcs, src)
 					} else { // select source path for documentation based on whitelist path prefixs.
-						for k, _ := range whitelistPathPrefixes {
+						for k := range whitelistPathPrefixes {
 							if strings.HasPrefix(src.Rel(), k) {
 								deps.srcs = append(deps.srcs, src)
 								break
@@ -553,11 +657,42 @@
 	j.docZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"docs.zip")
 	j.stubsSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+"-"+"stubs.srcjar")
 
-	if j.properties.Local_sourcepaths == nil {
+	if j.properties.Local_sourcepaths == nil && len(j.srcFiles) > 0 {
 		j.properties.Local_sourcepaths = append(j.properties.Local_sourcepaths, ".")
 	}
 	j.sourcepaths = android.PathsForModuleSrc(ctx, j.properties.Local_sourcepaths)
 
+	j.argFiles = ctx.ExpandSources(j.properties.Arg_files, nil)
+	argFilesMap := map[string]android.Path{}
+
+	for _, f := range j.argFiles {
+		if _, exists := argFilesMap[f.Rel()]; !exists {
+			argFilesMap[f.Rel()] = f
+		} else {
+			ctx.ModuleErrorf("multiple arg_files for %q, %q and %q",
+				f, argFilesMap[f.Rel()], f.Rel())
+		}
+	}
+
+	var err error
+	j.args, err = android.Expand(String(j.properties.Args), func(name string) (string, error) {
+		if strings.HasPrefix(name, "location ") {
+			label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
+			if f, ok := argFilesMap[label]; ok {
+				return f.String(), nil
+			} else {
+				return "", fmt.Errorf("unknown location label %q", label)
+			}
+		} else if name == "genDir" {
+			return android.PathForModuleGen(ctx).String(), nil
+		}
+		return "", fmt.Errorf("unknown variable '$(%s)'", name)
+	})
+
+	if err != nil {
+		ctx.PropertyErrorf("args", "%s", err.Error())
+	}
+
 	return deps
 }
 
@@ -572,7 +707,7 @@
 	implicits = append(implicits, deps.bootClasspath...)
 	implicits = append(implicits, deps.classpath...)
 
-	var bootClasspathArgs, classpathArgs string
+	var bootClasspathArgs, classpathArgs, sourcepathArgs string
 
 	javaVersion := getJavaVersion(ctx, String(j.properties.Java_version), sdkContext(j))
 	if len(deps.bootClasspath) > 0 {
@@ -588,9 +723,12 @@
 	}
 
 	implicits = append(implicits, j.srcJars...)
+	implicits = append(implicits, j.argFiles...)
 
 	opts := "-source " + javaVersion + " -J-Xmx1024m -XDignore.symbol.file -Xdoclint:none"
 
+	sourcepathArgs = "-sourcepath " + strings.Join(j.sourcepaths.Strings(), ":")
+
 	ctx.Build(pctx, android.BuildParams{
 		Rule:           javadoc,
 		Description:    "Javadoc",
@@ -606,7 +744,7 @@
 			"opts":              opts,
 			"bootclasspathArgs": bootClasspathArgs,
 			"classpathArgs":     classpathArgs,
-			"sourcepath":        strings.Join(j.sourcepaths.Strings(), ":"),
+			"sourcepathArgs":    sourcepathArgs,
 			"docZip":            j.docZip.String(),
 		},
 	})
@@ -633,15 +771,9 @@
 	updateCurrentApiTimestamp     android.WritablePath
 	checkLastReleasedApiTimestamp android.WritablePath
 
-	annotationsZip android.WritablePath
-
 	apiFilePath android.Path
 }
 
-type ApiFilePath interface {
-	ApiFilePath() android.Path
-}
-
 func DroiddocFactory() android.Module {
 	module := &Droiddoc{}
 
@@ -666,32 +798,6 @@
 	return d.apiFilePath
 }
 
-func (d *Droiddoc) checkCurrentApi() bool {
-	if String(d.properties.Check_api.Current.Api_file) != "" &&
-		String(d.properties.Check_api.Current.Removed_api_file) != "" {
-		return true
-	} else if String(d.properties.Check_api.Current.Api_file) != "" {
-		panic("check_api.current.removed_api_file: has to be non empty!")
-	} else if String(d.properties.Check_api.Current.Removed_api_file) != "" {
-		panic("check_api.current.api_file: has to be non empty!")
-	}
-
-	return false
-}
-
-func (d *Droiddoc) checkLastReleasedApi() bool {
-	if String(d.properties.Check_api.Last_released.Api_file) != "" &&
-		String(d.properties.Check_api.Last_released.Removed_api_file) != "" {
-		return true
-	} else if String(d.properties.Check_api.Last_released.Api_file) != "" {
-		panic("check_api.last_released.removed_api_file: has to be non empty!")
-	} else if String(d.properties.Check_api.Last_released.Removed_api_file) != "" {
-		panic("check_api.last_released.api_file: has to be non empty!")
-	}
-
-	return false
-}
-
 func (d *Droiddoc) DepsMutator(ctx android.BottomUpMutatorContext) {
 	d.Javadoc.addDeps(ctx)
 
@@ -699,9 +805,6 @@
 		ctx.AddDependency(ctx.Module(), droiddocTemplateTag, String(d.properties.Custom_template))
 	}
 
-	// arg_files may contains filegroup or genrule.
-	android.ExtractSourcesDeps(ctx, d.properties.Arg_files)
-
 	// knowntags may contain filegroup or genrule.
 	android.ExtractSourcesDeps(ctx, d.properties.Knowntags)
 
@@ -713,25 +816,15 @@
 		android.ExtractSourceDeps(ctx, d.properties.Static_doc_properties)
 	}
 
-	if d.checkCurrentApi() {
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") {
 		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Api_file)
 		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Removed_api_file)
 	}
 
-	if d.checkLastReleasedApi() {
+	if apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") {
 		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Api_file)
 		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Removed_api_file)
 	}
-
-	if String(d.properties.Metalava_previous_api) != "" {
-		android.ExtractSourceDeps(ctx, d.properties.Metalava_previous_api)
-	}
-
-	if len(d.properties.Metalava_merge_annotations_dirs) != 0 {
-		for _, mergeAnnotationsDir := range d.properties.Metalava_merge_annotations_dirs {
-			ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
-		}
-	}
 }
 
 func (d *Droiddoc) initBuilderFlags(ctx android.ModuleContext, implicits *android.Paths,
@@ -741,51 +834,28 @@
 	*implicits = append(*implicits, deps.bootClasspath...)
 	*implicits = append(*implicits, deps.classpath...)
 
-	// continue to use -bootclasspath even if Metalava under -source 1.9 is enabled
-	// since it doesn't support system modules yet.
 	if len(deps.bootClasspath.Strings()) > 0 {
 		// For OpenJDK 8 we can use -bootclasspath to define the core libraries code.
 		flags.bootClasspathArgs = deps.bootClasspath.FormJavaClassPath("-bootclasspath")
 	}
 	flags.classpathArgs = deps.classpath.FormJavaClassPath("-classpath")
-	// Dokka doesn't support boocClasspath, so combine these two classpath vars for Dokka.
+	// Dokka doesn't support bootClasspath, so combine these two classpath vars for Dokka.
 	dokkaClasspath := classpath{}
 	dokkaClasspath = append(dokkaClasspath, deps.bootClasspath...)
 	dokkaClasspath = append(dokkaClasspath, deps.classpath...)
 	flags.dokkaClasspathArgs = dokkaClasspath.FormJavaClassPath("-classpath")
 
-	argFiles := ctx.ExpandSources(d.properties.Arg_files, nil)
-	argFilesMap := map[string]android.Path{}
-
-	for _, f := range argFiles {
-		*implicits = append(*implicits, f)
-		if _, exists := argFilesMap[f.Rel()]; !exists {
-			argFilesMap[f.Rel()] = f
-		} else {
-			ctx.ModuleErrorf("multiple arg_files for %q, %q and %q",
-				f, argFilesMap[f.Rel()], f.Rel())
-		}
+	// TODO(nanzhang): Remove this if- statement once we finish migration for all Doclava
+	// based stubs generation.
+	// In the future, all the docs generation depends on Metalava stubs (droidstubs) srcjar
+	// dir. We need add the srcjar dir to -sourcepath arg, so that Javadoc can figure out
+	// the correct package name base path.
+	if len(d.Javadoc.properties.Local_sourcepaths) > 0 {
+		flags.sourcepathArgs = "-sourcepath " + strings.Join(d.Javadoc.sourcepaths.Strings(), ":")
+	} else {
+		flags.sourcepathArgs = "-sourcepath " + android.PathForModuleOut(ctx, "srcjars").String()
 	}
 
-	var err error
-	flags.args, err = android.Expand(String(d.properties.Args), func(name string) (string, error) {
-		if strings.HasPrefix(name, "location ") {
-			label := strings.TrimSpace(strings.TrimPrefix(name, "location "))
-			if f, ok := argFilesMap[label]; ok {
-				return f.String(), nil
-			} else {
-				return "", fmt.Errorf("unknown location label %q", label)
-			}
-		} else if name == "genDir" {
-			return android.PathForModuleGen(ctx).String(), nil
-		}
-		return "", fmt.Errorf("unknown variable '$(%s)'", name)
-	})
-
-	if err != nil {
-		ctx.PropertyErrorf("args", "%s", err.Error())
-		return droiddocBuilderFlags{}, err
-	}
 	return flags, nil
 }
 
@@ -877,27 +947,29 @@
 	return args
 }
 
-func (d *Droiddoc) collectStubsFlags(ctx android.ModuleContext, implicitOutputs *android.WritablePaths) (string, string) {
-	var doclavaFlags, MetalavaFlags string
-	if d.checkCurrentApi() || d.checkLastReleasedApi() || String(d.properties.Api_filename) != "" {
+func (d *Droiddoc) collectStubsFlags(ctx android.ModuleContext,
+	implicitOutputs *android.WritablePaths) string {
+	var doclavaFlags string
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") ||
+		apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") ||
+		String(d.properties.Api_filename) != "" {
 		d.apiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_api.txt")
 		doclavaFlags += " -api " + d.apiFile.String()
-		MetalavaFlags = MetalavaFlags + " --api " + d.apiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.apiFile)
 		d.apiFilePath = d.apiFile
 	}
 
-	if d.checkCurrentApi() || d.checkLastReleasedApi() || String(d.properties.Removed_api_filename) != "" {
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") ||
+		apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") ||
+		String(d.properties.Removed_api_filename) != "" {
 		d.removedApiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_removed.txt")
 		doclavaFlags += " -removedApi " + d.removedApiFile.String()
-		MetalavaFlags = MetalavaFlags + " --removed-api " + d.removedApiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.removedApiFile)
 	}
 
 	if String(d.properties.Private_api_filename) != "" {
 		d.privateApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_api_filename))
 		doclavaFlags += " -privateApi " + d.privateApiFile.String()
-		MetalavaFlags = MetalavaFlags + " --private-api " + d.privateApiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.privateApiFile)
 	}
 
@@ -910,35 +982,30 @@
 	if String(d.properties.Private_dex_api_filename) != "" {
 		d.privateDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_dex_api_filename))
 		doclavaFlags += " -privateDexApi " + d.privateDexApiFile.String()
-		MetalavaFlags = MetalavaFlags + " --private-dex-api " + d.privateDexApiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.privateDexApiFile)
 	}
 
 	if String(d.properties.Removed_dex_api_filename) != "" {
 		d.removedDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Removed_dex_api_filename))
 		doclavaFlags += " -removedDexApi " + d.removedDexApiFile.String()
-		MetalavaFlags = MetalavaFlags + " --removed-dex-api " + d.removedDexApiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.removedDexApiFile)
 	}
 
 	if String(d.properties.Exact_api_filename) != "" {
 		d.exactApiFile = android.PathForModuleOut(ctx, String(d.properties.Exact_api_filename))
 		doclavaFlags += " -exactApi " + d.exactApiFile.String()
-		MetalavaFlags = MetalavaFlags + " --exact-api " + d.exactApiFile.String()
 		*implicitOutputs = append(*implicitOutputs, d.exactApiFile)
 	}
 
 	if String(d.properties.Dex_mapping_filename) != "" {
 		d.apiMappingFile = android.PathForModuleOut(ctx, String(d.properties.Dex_mapping_filename))
 		doclavaFlags += " -apiMapping " + d.apiMappingFile.String()
-		// Omitted: metalava support
 		*implicitOutputs = append(*implicitOutputs, d.apiMappingFile)
 	}
 
 	if String(d.properties.Proguard_filename) != "" {
 		d.proguardFile = android.PathForModuleOut(ctx, String(d.properties.Proguard_filename))
 		doclavaFlags += " -proguard " + d.proguardFile.String()
-		// Omitted: metalava support
 		*implicitOutputs = append(*implicitOutputs, d.proguardFile)
 	}
 
@@ -949,7 +1016,8 @@
 	if Bool(d.properties.Write_sdk_values) {
 		doclavaFlags += " -sdkvalues " + android.PathForModuleOut(ctx, "out").String()
 	}
-	return doclavaFlags, MetalavaFlags
+
+	return doclavaFlags
 }
 
 func (d *Droiddoc) getPostDoclavaCmds(ctx android.ModuleContext, implicits *android.Paths) string {
@@ -972,93 +1040,9 @@
 	return cmds
 }
 
-func (d *Droiddoc) collectMetalavaAnnotationsFlags(
-	ctx android.ModuleContext, implicits *android.Paths, implicitOutputs *android.WritablePaths) string {
-	var flags string
-	if Bool(d.properties.Metalava_annotations_enabled) {
-		if String(d.properties.Metalava_previous_api) == "" {
-			ctx.PropertyErrorf("metalava_previous_api",
-				"has to be non-empty if annotations was enabled!")
-		}
-		previousApi := ctx.ExpandSource(String(d.properties.Metalava_previous_api),
-			"metalava_previous_api")
-		*implicits = append(*implicits, previousApi)
-
-		flags += " --include-annotations --migrate-nullness " + previousApi.String()
-
-		d.annotationsZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"_annotations.zip")
-		*implicitOutputs = append(*implicitOutputs, d.annotationsZip)
-
-		flags += " --extract-annotations " + d.annotationsZip.String()
-
-		if len(d.properties.Metalava_merge_annotations_dirs) == 0 {
-			ctx.PropertyErrorf("metalava_merge_annotations_dirs",
-				"has to be non-empty if annotations was enabled!")
-		}
-		ctx.VisitDirectDepsWithTag(metalavaMergeAnnotationsDirTag, func(m android.Module) {
-			if t, ok := m.(*ExportedDroiddocDir); ok {
-				*implicits = append(*implicits, t.deps...)
-				flags += " --merge-annotations " + t.dir.String()
-			} else {
-				ctx.PropertyErrorf("metalava_merge_annotations_dirs",
-					"module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
-			}
-		})
-		// TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
-		flags += " --hide HiddenTypedefConstant --hide SuperfluousPrefix --hide AnnotationExtraction "
-	}
-
-	return flags
-}
-
-func (d *Droiddoc) collectMetalavaJavadocFlags(ctx android.ModuleContext,
-	bootClasspathArgs, classpathArgs, outDir, docStubsDir string) string {
-	return " --doc-stubs " + docStubsDir +
-		" --write-doc-stubs-source-list " + android.PathForModuleOut(ctx, "doc_stubs.srclist").String() +
-		" --generate-documentation ${config.JavadocCmd} -encoding UTF-8 DOC_STUBS_SOURCE_LIST " +
-		bootClasspathArgs + " " + classpathArgs + " " + " -sourcepath " +
-		docStubsDir + " -quiet -d " + outDir
-}
-
-func (d *Droiddoc) collectMetalavaDokkaFlags(ctx android.ModuleContext, implicits *android.Paths,
-	classpathArgs, outDir, docStubsDir string) string {
-	dokka := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "dokka.jar")
-	*implicits = append(*implicits, dokka)
-
-	return " --doc-stubs " + docStubsDir + " --write-doc-stubs-source-list " +
-		android.PathForModuleOut(ctx, "doc_stubs.srclist").String() +
-		" --generate-documentation ${config.JavaCmd} -jar " + dokka.String() + " " +
-		docStubsDir + " " + classpathArgs + " -format dac -dacRoot /reference/kotlin -output " + outDir
-}
-
-func (d *Droiddoc) transformMetalava(ctx android.ModuleContext, implicits android.Paths,
-	implicitOutputs android.WritablePaths, outDir, docStubsDir, javaVersion,
-	bootclasspathArgs, classpathArgs, opts string) {
-	ctx.Build(pctx, android.BuildParams{
-		Rule:            metalava,
-		Description:     "Metalava",
-		Output:          d.Javadoc.stubsSrcJar,
-		Inputs:          d.Javadoc.srcFiles,
-		Implicits:       implicits,
-		ImplicitOutputs: implicitOutputs,
-		Args: map[string]string{
-			"outDir":            outDir,
-			"srcJarDir":         android.PathForModuleOut(ctx, "srcjars").String(),
-			"stubsDir":          android.PathForModuleOut(ctx, "stubsDir").String(),
-			"docStubsDir":       docStubsDir,
-			"srcJars":           strings.Join(d.Javadoc.srcJars.Strings(), " "),
-			"javaVersion":       javaVersion,
-			"bootclasspathArgs": bootclasspathArgs,
-			"classpathArgs":     classpathArgs,
-			"sourcepath":        strings.Join(d.Javadoc.sourcepaths.Strings(), ":"),
-			"docZip":            d.Javadoc.docZip.String(),
-			"opts":              opts,
-		},
-	})
-}
-
 func (d *Droiddoc) transformDoclava(ctx android.ModuleContext, implicits android.Paths,
-	implicitOutputs android.WritablePaths, bootclasspathArgs, classpathArgs, opts, postDoclavaCmds string) {
+	implicitOutputs android.WritablePaths,
+	bootclasspathArgs, classpathArgs, sourcepathArgs, opts, postDoclavaCmds string) {
 	ctx.Build(pctx, android.BuildParams{
 		Rule:            javadoc,
 		Description:     "Doclava",
@@ -1074,7 +1058,7 @@
 			"opts":              opts,
 			"bootclasspathArgs": bootclasspathArgs,
 			"classpathArgs":     classpathArgs,
-			"sourcepath":        strings.Join(d.Javadoc.sourcepaths.Strings(), ":"),
+			"sourcepathArgs":    sourcepathArgs,
 			"docZip":            d.Javadoc.docZip.String(),
 			"postDoclavaCmds":   postDoclavaCmds,
 		},
@@ -1091,19 +1075,387 @@
 		Implicits: append(android.Paths{apiFile, removedApiFile, d.apiFile, d.removedApiFile},
 			checkApiClasspath...),
 		Args: map[string]string{
+			"msg":                   msg,
 			"classpath":             checkApiClasspath.FormJavaClassPath(""),
 			"opts":                  opts,
 			"apiFile":               apiFile.String(),
 			"apiFileToCheck":        d.apiFile.String(),
 			"removedApiFile":        removedApiFile.String(),
 			"removedApiFileToCheck": d.removedApiFile.String(),
-			"msg": msg,
 		},
 	})
 }
 
-func (d *Droiddoc) transformMetalavaCheckApi(ctx android.ModuleContext, apiFile, removedApiFile android.Path,
-	implicits android.Paths, javaVersion, bootclasspathArgs, classpathArgs, opts, msg string,
+func (d *Droiddoc) transformDokka(ctx android.ModuleContext, implicits android.Paths,
+	classpathArgs, opts string) {
+	ctx.Build(pctx, android.BuildParams{
+		Rule:        dokka,
+		Description: "Dokka",
+		Output:      d.Javadoc.stubsSrcJar,
+		Inputs:      d.Javadoc.srcFiles,
+		Implicits:   implicits,
+		Args: map[string]string{
+			"outDir":        android.PathForModuleOut(ctx, "out").String(),
+			"srcJarDir":     android.PathForModuleOut(ctx, "srcjars").String(),
+			"stubsDir":      android.PathForModuleOut(ctx, "stubsDir").String(),
+			"srcJars":       strings.Join(d.Javadoc.srcJars.Strings(), " "),
+			"classpathArgs": classpathArgs,
+			"opts":          opts,
+			"docZip":        d.Javadoc.docZip.String(),
+		},
+	})
+}
+
+func (d *Droiddoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	deps := d.Javadoc.collectDeps(ctx)
+
+	jsilver := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "jsilver.jar")
+	doclava := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "doclava.jar")
+	java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
+	checkApiClasspath := classpath{jsilver, doclava, android.PathForSource(ctx, java8Home, "lib/tools.jar")}
+
+	var implicits android.Paths
+	implicits = append(implicits, d.Javadoc.srcJars...)
+	implicits = append(implicits, d.Javadoc.argFiles...)
+
+	var implicitOutputs android.WritablePaths
+	implicitOutputs = append(implicitOutputs, d.Javadoc.docZip)
+	for _, o := range d.Javadoc.properties.Out {
+		implicitOutputs = append(implicitOutputs, android.PathForModuleGen(ctx, o))
+	}
+
+	flags, err := d.initBuilderFlags(ctx, &implicits, deps)
+	if err != nil {
+		return
+	}
+
+	flags.doclavaStubsFlags = d.collectStubsFlags(ctx, &implicitOutputs)
+	if Bool(d.properties.Dokka_enabled) {
+		d.transformDokka(ctx, implicits, flags.classpathArgs, d.Javadoc.args)
+	} else {
+		flags.doclavaDocsFlags = d.collectDoclavaDocsFlags(ctx, &implicits, jsilver, doclava)
+		flags.postDoclavaCmds = d.getPostDoclavaCmds(ctx, &implicits)
+		d.transformDoclava(ctx, implicits, implicitOutputs, flags.bootClasspathArgs, flags.classpathArgs,
+			flags.sourcepathArgs, flags.doclavaDocsFlags+flags.doclavaStubsFlags+" "+d.Javadoc.args,
+			flags.postDoclavaCmds)
+	}
+
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") &&
+		!ctx.Config().IsPdkBuild() {
+		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Api_file),
+			"check_api.current.api_file")
+		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Removed_api_file),
+			"check_api.current_removed_api_file")
+
+		d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "check_current_api.timestamp")
+		d.transformCheckApi(ctx, apiFile, removedApiFile, checkApiClasspath,
+			fmt.Sprintf(`\n******************************\n`+
+				`You have tried to change the API from what has been previously approved.\n\n`+
+				`To make these errors go away, you have two choices:\n`+
+				`   1. You can add '@hide' javadoc comments to the methods, etc. listed in the\n`+
+				`      errors above.\n\n`+
+				`   2. You can update current.txt by executing the following command:\n`+
+				`         make %s-update-current-api\n\n`+
+				`      To submit the revised current.txt to the main Android repository,\n`+
+				`      you will need approval.\n`+
+				`******************************\n`, ctx.ModuleName()), String(d.properties.Check_api.Current.Args),
+			d.checkCurrentApiTimestamp)
+
+		d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "update_current_api.timestamp")
+		transformUpdateApi(ctx, apiFile, removedApiFile, d.apiFile, d.removedApiFile,
+			d.updateCurrentApiTimestamp)
+	}
+
+	if apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") &&
+		!ctx.Config().IsPdkBuild() {
+		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Api_file),
+			"check_api.last_released.api_file")
+		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Removed_api_file),
+			"check_api.last_released.removed_api_file")
+
+		d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "check_last_released_api.timestamp")
+		d.transformCheckApi(ctx, apiFile, removedApiFile, checkApiClasspath,
+			`\n******************************\n`+
+				`You have tried to change the API from what has been previously released in\n`+
+				`an SDK.  Please fix the errors listed above.\n`+
+				`******************************\n`, String(d.properties.Check_api.Last_released.Args),
+			d.checkLastReleasedApiTimestamp)
+	}
+}
+
+//
+// Droidstubs
+//
+type Droidstubs struct {
+	Javadoc
+
+	properties        DroidstubsProperties
+	apiFile           android.WritablePath
+	dexApiFile        android.WritablePath
+	privateApiFile    android.WritablePath
+	privateDexApiFile android.WritablePath
+	removedApiFile    android.WritablePath
+	removedDexApiFile android.WritablePath
+	apiMappingFile    android.WritablePath
+	exactApiFile      android.WritablePath
+
+	checkCurrentApiTimestamp      android.WritablePath
+	updateCurrentApiTimestamp     android.WritablePath
+	checkLastReleasedApiTimestamp android.WritablePath
+
+	annotationsZip android.WritablePath
+	apiVersionsXml android.WritablePath
+
+	apiFilePath android.Path
+}
+
+func DroidstubsFactory() android.Module {
+	module := &Droidstubs{}
+
+	module.AddProperties(&module.properties,
+		&module.Javadoc.properties)
+
+	InitDroiddocModule(module, android.HostAndDeviceSupported)
+	return module
+}
+
+func DroidstubsHostFactory() android.Module {
+	module := &Droidstubs{}
+
+	module.AddProperties(&module.properties,
+		&module.Javadoc.properties)
+
+	InitDroiddocModule(module, android.HostSupported)
+	return module
+}
+
+func (d *Droidstubs) ApiFilePath() android.Path {
+	return d.apiFilePath
+}
+
+func (d *Droidstubs) DepsMutator(ctx android.BottomUpMutatorContext) {
+	d.Javadoc.addDeps(ctx)
+
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") {
+		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Api_file)
+		android.ExtractSourceDeps(ctx, d.properties.Check_api.Current.Removed_api_file)
+	}
+
+	if apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") {
+		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Api_file)
+		android.ExtractSourceDeps(ctx, d.properties.Check_api.Last_released.Removed_api_file)
+	}
+
+	if String(d.properties.Previous_api) != "" {
+		android.ExtractSourceDeps(ctx, d.properties.Previous_api)
+	}
+
+	if len(d.properties.Merge_annotations_dirs) != 0 {
+		for _, mergeAnnotationsDir := range d.properties.Merge_annotations_dirs {
+			ctx.AddDependency(ctx.Module(), metalavaMergeAnnotationsDirTag, mergeAnnotationsDir)
+		}
+	}
+
+	if len(d.properties.Api_levels_annotations_dirs) != 0 {
+		for _, apiLevelsAnnotationsDir := range d.properties.Api_levels_annotations_dirs {
+			ctx.AddDependency(ctx.Module(), metalavaAPILevelsAnnotationsDirTag, apiLevelsAnnotationsDir)
+		}
+	}
+}
+
+func (d *Droidstubs) initBuilderFlags(ctx android.ModuleContext, implicits *android.Paths,
+	deps deps) (droiddocBuilderFlags, error) {
+	var flags droiddocBuilderFlags
+
+	*implicits = append(*implicits, deps.bootClasspath...)
+	*implicits = append(*implicits, deps.classpath...)
+
+	// continue to use -bootclasspath even if Metalava under -source 1.9 is enabled
+	// since it doesn't support system modules yet.
+	if len(deps.bootClasspath.Strings()) > 0 {
+		// For OpenJDK 8 we can use -bootclasspath to define the core libraries code.
+		flags.bootClasspathArgs = deps.bootClasspath.FormJavaClassPath("-bootclasspath")
+	}
+	flags.classpathArgs = deps.classpath.FormJavaClassPath("-classpath")
+
+	flags.sourcepathArgs = "-sourcepath " + strings.Join(d.Javadoc.sourcepaths.Strings(), ":")
+
+	return flags, nil
+}
+
+func (d *Droidstubs) collectStubsFlags(ctx android.ModuleContext,
+	implicitOutputs *android.WritablePaths) string {
+	var metalavaFlags string
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") ||
+		apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") ||
+		String(d.properties.Api_filename) != "" {
+		d.apiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_api.txt")
+		metalavaFlags = metalavaFlags + " --api " + d.apiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.apiFile)
+		d.apiFilePath = d.apiFile
+	}
+
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") ||
+		apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") ||
+		String(d.properties.Removed_api_filename) != "" {
+		d.removedApiFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"_removed.txt")
+		metalavaFlags = metalavaFlags + " --removed-api " + d.removedApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.removedApiFile)
+	}
+
+	if String(d.properties.Private_api_filename) != "" {
+		d.privateApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_api_filename))
+		metalavaFlags = metalavaFlags + " --private-api " + d.privateApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.privateApiFile)
+	}
+
+	if String(d.properties.Dex_api_filename) != "" {
+		d.dexApiFile = android.PathForModuleOut(ctx, String(d.properties.Dex_api_filename))
+		metalavaFlags += " --dex-api " + d.dexApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.dexApiFile)
+	}
+
+	if String(d.properties.Private_dex_api_filename) != "" {
+		d.privateDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Private_dex_api_filename))
+		metalavaFlags = metalavaFlags + " --private-dex-api " + d.privateDexApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.privateDexApiFile)
+	}
+
+	if String(d.properties.Removed_dex_api_filename) != "" {
+		d.removedDexApiFile = android.PathForModuleOut(ctx, String(d.properties.Removed_dex_api_filename))
+		metalavaFlags = metalavaFlags + " --removed-dex-api " + d.removedDexApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.removedDexApiFile)
+	}
+
+	if String(d.properties.Exact_api_filename) != "" {
+		d.exactApiFile = android.PathForModuleOut(ctx, String(d.properties.Exact_api_filename))
+		metalavaFlags = metalavaFlags + " --exact-api " + d.exactApiFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.exactApiFile)
+	}
+
+	if String(d.properties.Dex_mapping_filename) != "" {
+		d.apiMappingFile = android.PathForModuleOut(ctx, String(d.properties.Dex_mapping_filename))
+		metalavaFlags = metalavaFlags + " --dex-api-mapping " + d.apiMappingFile.String()
+		*implicitOutputs = append(*implicitOutputs, d.apiMappingFile)
+	}
+
+	if Bool(d.properties.Write_sdk_values) {
+		metalavaFlags = metalavaFlags + " --sdk-values " + android.PathForModuleOut(ctx, "out").String()
+	}
+
+	if Bool(d.properties.Create_doc_stubs) {
+		metalavaFlags += " --doc-stubs " + android.PathForModuleOut(ctx, "stubsDir").String()
+	} else {
+		metalavaFlags += " --stubs " + android.PathForModuleOut(ctx, "stubsDir").String()
+	}
+
+	return metalavaFlags
+}
+
+func (d *Droidstubs) collectAnnotationsFlags(ctx android.ModuleContext,
+	implicits *android.Paths, implicitOutputs *android.WritablePaths) string {
+	var flags string
+	if Bool(d.properties.Annotations_enabled) {
+		if String(d.properties.Previous_api) == "" {
+			ctx.PropertyErrorf("metalava_previous_api",
+				"has to be non-empty if annotations was enabled!")
+		}
+		previousApi := ctx.ExpandSource(String(d.properties.Previous_api),
+			"metalava_previous_api")
+		*implicits = append(*implicits, previousApi)
+
+		flags += " --include-annotations --migrate-nullness " + previousApi.String()
+
+		d.annotationsZip = android.PathForModuleOut(ctx, ctx.ModuleName()+"_annotations.zip")
+		*implicitOutputs = append(*implicitOutputs, d.annotationsZip)
+
+		flags += " --extract-annotations " + d.annotationsZip.String()
+
+		if len(d.properties.Merge_annotations_dirs) == 0 {
+			ctx.PropertyErrorf("merge_annotations_dirs",
+				"has to be non-empty if annotations was enabled!")
+		}
+		ctx.VisitDirectDepsWithTag(metalavaMergeAnnotationsDirTag, func(m android.Module) {
+			if t, ok := m.(*ExportedDroiddocDir); ok {
+				*implicits = append(*implicits, t.deps...)
+				flags += " --merge-annotations " + t.dir.String()
+			} else {
+				ctx.PropertyErrorf("merge_annotations_dirs",
+					"module %q is not a metalava merge-annotations dir", ctx.OtherModuleName(m))
+			}
+		})
+		// TODO(tnorbye): find owners to fix these warnings when annotation was enabled.
+		flags += " --hide HiddenTypedefConstant --hide SuperfluousPrefix --hide AnnotationExtraction "
+	}
+
+	return flags
+}
+
+func (d *Droidstubs) collectAPILevelsAnnotationsFlags(ctx android.ModuleContext,
+	implicits *android.Paths, implicitOutputs *android.WritablePaths) string {
+	var flags string
+	if Bool(d.properties.Api_levels_annotations_enabled) {
+		d.apiVersionsXml = android.PathForModuleOut(ctx, "api-versions.xml")
+		*implicitOutputs = append(*implicitOutputs, d.apiVersionsXml)
+
+		if len(d.properties.Api_levels_annotations_dirs) == 0 {
+			ctx.PropertyErrorf("api_levels_annotations_dirs",
+				"has to be non-empty if api levels annotations was enabled!")
+		}
+
+		flags = " --generate-api-levels " + d.apiVersionsXml.String() + " --apply-api-levels " +
+			d.apiVersionsXml.String() + " --current-version " + ctx.Config().PlatformSdkVersion() +
+			" --current-codename " + ctx.Config().PlatformSdkCodename() + " "
+
+		ctx.VisitDirectDepsWithTag(metalavaAPILevelsAnnotationsDirTag, func(m android.Module) {
+			if t, ok := m.(*ExportedDroiddocDir); ok {
+				var androidJars android.Paths
+				for _, dep := range t.deps {
+					if strings.HasSuffix(dep.String(), "android.jar") {
+						androidJars = append(androidJars, dep)
+					}
+				}
+				*implicits = append(*implicits, androidJars...)
+				flags += " --android-jar-pattern " + t.dir.String() + "/%/android.jar "
+			} else {
+				ctx.PropertyErrorf("api_levels_annotations_dirs",
+					"module %q is not a metalava api-levels-annotations dir", ctx.OtherModuleName(m))
+			}
+		})
+
+	}
+
+	return flags
+}
+
+func (d *Droidstubs) transformMetalava(ctx android.ModuleContext, implicits android.Paths,
+	implicitOutputs android.WritablePaths, javaVersion,
+	bootclasspathArgs, classpathArgs, sourcepathArgs, opts string) {
+
+	ctx.Build(pctx, android.BuildParams{
+		Rule:            metalava,
+		Description:     "Metalava",
+		Output:          d.Javadoc.stubsSrcJar,
+		Inputs:          d.Javadoc.srcFiles,
+		Implicits:       implicits,
+		ImplicitOutputs: implicitOutputs,
+		Args: map[string]string{
+			"outDir":            android.PathForModuleOut(ctx, "out").String(),
+			"srcJarDir":         android.PathForModuleOut(ctx, "srcjars").String(),
+			"stubsDir":          android.PathForModuleOut(ctx, "stubsDir").String(),
+			"srcJars":           strings.Join(d.Javadoc.srcJars.Strings(), " "),
+			"javaVersion":       javaVersion,
+			"bootclasspathArgs": bootclasspathArgs,
+			"classpathArgs":     classpathArgs,
+			"sourcepathArgs":    sourcepathArgs,
+			"opts":              opts,
+		},
+	})
+}
+
+func (d *Droidstubs) transformCheckApi(ctx android.ModuleContext,
+	apiFile, removedApiFile android.Path, implicits android.Paths,
+	javaVersion, bootclasspathArgs, classpathArgs, sourcepathArgs, opts, msg string,
 	output android.WritablePath) {
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        metalavaApiCheck,
@@ -1118,44 +1470,24 @@
 			"javaVersion":       javaVersion,
 			"bootclasspathArgs": bootclasspathArgs,
 			"classpathArgs":     classpathArgs,
-			"sourcepath":        strings.Join(d.Javadoc.sourcepaths.Strings(), ":"),
+			"sourcepathArgs":    sourcepathArgs,
 			"opts":              opts,
 			"msg":               msg,
 		},
 	})
 }
 
-func (d *Droiddoc) transformUpdateApi(ctx android.ModuleContext, apiFile, removedApiFile android.Path,
-	output android.WritablePath) {
-	ctx.Build(pctx, android.BuildParams{
-		Rule:        updateApi,
-		Description: "Update API",
-		Output:      output,
-		Implicits:   append(android.Paths{}, apiFile, removedApiFile, d.apiFile, d.removedApiFile),
-		Args: map[string]string{
-			"apiFile":               apiFile.String(),
-			"apiFileToCheck":        d.apiFile.String(),
-			"removedApiFile":        removedApiFile.String(),
-			"removedApiFileToCheck": d.removedApiFile.String(),
-		},
-	})
-}
-
-func (d *Droiddoc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+func (d *Droidstubs) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	deps := d.Javadoc.collectDeps(ctx)
 
 	javaVersion := getJavaVersion(ctx, String(d.Javadoc.properties.Java_version), sdkContext(d))
-	jsilver := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "jsilver.jar")
-	doclava := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "doclava.jar")
-	java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
-	checkApiClasspath := classpath{jsilver, doclava, android.PathForSource(ctx, java8Home, "lib/tools.jar")}
 
 	var implicits android.Paths
 	implicits = append(implicits, d.Javadoc.srcJars...)
+	implicits = append(implicits, d.Javadoc.argFiles...)
 
 	var implicitOutputs android.WritablePaths
-	implicitOutputs = append(implicitOutputs, d.Javadoc.docZip)
-	for _, o := range d.properties.Out {
+	for _, o := range d.Javadoc.properties.Out {
 		implicitOutputs = append(implicitOutputs, android.PathForModuleGen(ctx, o))
 	}
 
@@ -1165,114 +1497,68 @@
 		return
 	}
 
-	flags.doclavaStubsFlags, flags.metalavaStubsFlags = d.collectStubsFlags(ctx, &implicitOutputs)
-	if Bool(d.properties.Metalava_enabled) {
-		flags.metalavaAnnotationsFlags = d.collectMetalavaAnnotationsFlags(ctx, &implicits, &implicitOutputs)
-		outDir := android.PathForModuleOut(ctx, "out").String()
-		docStubsDir := android.PathForModuleOut(ctx, "docStubsDir").String()
-		// TODO(nanzhang): Add a Soong property to handle documentation args.
-		if strings.Contains(flags.args, "--generate-documentation") { // enable docs generation
-			if Bool(d.properties.Dokka_enabled) {
-				flags.metalavaDokkaFlags = d.collectMetalavaDokkaFlags(ctx, &implicits,
-					flags.dokkaClasspathArgs, outDir, docStubsDir)
-				d.transformMetalava(ctx, implicits, implicitOutputs, outDir, docStubsDir, javaVersion,
-					flags.bootClasspathArgs, flags.classpathArgs, flags.metalavaStubsFlags+
-						flags.metalavaAnnotationsFlags+" "+
-						strings.Split(flags.args, "--generate-documentation")[0]+
-						flags.metalavaDokkaFlags+" "+strings.Split(flags.args, "--generate-documentation")[1])
-			} else {
-				flags.metalavaJavadocFlags = d.collectMetalavaJavadocFlags(
-					ctx, flags.bootClasspathArgs, flags.classpathArgs, outDir, docStubsDir)
-				flags.doclavaDocsFlags = d.collectDoclavaDocsFlags(ctx, &implicits, jsilver, doclava)
-				d.transformMetalava(ctx, implicits, implicitOutputs, outDir, docStubsDir, javaVersion,
-					flags.bootClasspathArgs, flags.classpathArgs, flags.metalavaStubsFlags+
-						flags.metalavaAnnotationsFlags+" "+
-						strings.Split(flags.args, "--generate-documentation")[0]+
-						flags.metalavaJavadocFlags+flags.doclavaDocsFlags+
-						" "+strings.Split(flags.args, "--generate-documentation")[1])
-			}
-		} else {
-			d.transformMetalava(ctx, implicits, implicitOutputs, outDir, docStubsDir, javaVersion,
-				flags.bootClasspathArgs, flags.classpathArgs,
-				flags.metalavaStubsFlags+flags.metalavaAnnotationsFlags+" "+flags.args)
-		}
-	} else {
-		flags.doclavaDocsFlags = d.collectDoclavaDocsFlags(ctx, &implicits, jsilver, doclava)
-		flags.postDoclavaCmds = d.getPostDoclavaCmds(ctx, &implicits)
-		d.transformDoclava(ctx, implicits, implicitOutputs, flags.bootClasspathArgs, flags.classpathArgs,
-			flags.doclavaDocsFlags+flags.doclavaStubsFlags+" "+flags.args,
-			flags.postDoclavaCmds)
+	flags.metalavaStubsFlags = d.collectStubsFlags(ctx, &implicitOutputs)
+	flags.metalavaAnnotationsFlags = d.collectAnnotationsFlags(ctx, &implicits, &implicitOutputs)
+	flags.metalavaApiLevelsAnnotationsFlags = d.collectAPILevelsAnnotationsFlags(ctx, &implicits, &implicitOutputs)
+	if strings.Contains(d.Javadoc.args, "--generate-documentation") {
+		// Currently Metalava have the ability to invoke Javadoc in a seperate process.
+		// Pass "-nodocs" to suppress the Javadoc invocation when Metalava receives
+		// "--generate-documentation" arg. This is not needed when Metalava removes this feature.
+		d.Javadoc.args = d.Javadoc.args + " -nodocs "
 	}
+	d.transformMetalava(ctx, implicits, implicitOutputs, javaVersion,
+		flags.bootClasspathArgs, flags.classpathArgs, flags.sourcepathArgs,
+		flags.metalavaStubsFlags+flags.metalavaAnnotationsFlags+
+			flags.metalavaApiLevelsAnnotationsFlags+" "+d.Javadoc.args)
 
-	if d.checkCurrentApi() && !ctx.Config().IsPdkBuild() {
+	if apiCheckEnabled(d.properties.Check_api.Current, "current") &&
+		!ctx.Config().IsPdkBuild() {
 		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Api_file),
 			"check_api.current.api_file")
 		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Current.Removed_api_file),
 			"check_api.current_removed_api_file")
 
 		d.checkCurrentApiTimestamp = android.PathForModuleOut(ctx, "check_current_api.timestamp")
-		if !Bool(d.properties.Metalava_enabled) {
-			d.transformCheckApi(ctx, apiFile, removedApiFile, checkApiClasspath,
-				fmt.Sprintf(`\n******************************\n`+
-					`You have tried to change the API from what has been previously approved.\n\n`+
-					`To make these errors go away, you have two choices:\n`+
-					`   1. You can add '@hide' javadoc comments to the methods, etc. listed in the\n`+
-					`      errors above.\n\n`+
-					`   2. You can update current.txt by executing the following command:\n`+
-					`         make %s-update-current-api\n\n`+
-					`      To submit the revised current.txt to the main Android repository,\n`+
-					`      you will need approval.\n`+
-					`******************************\n`, ctx.ModuleName()), String(d.properties.Check_api.Current.Args),
-				d.checkCurrentApiTimestamp)
-		} else {
-			opts := flags.args + " --check-compatibility:api:current " + apiFile.String() +
-				" --check-compatibility:removed:current " + removedApiFile.String() + " "
+		opts := d.Javadoc.args + " --check-compatibility:api:current " + apiFile.String() +
+			" --check-compatibility:removed:current " + removedApiFile.String() + " "
 
-			d.transformMetalavaCheckApi(ctx, apiFile, removedApiFile, metalavaCheckApiImplicits,
-				javaVersion, flags.bootClasspathArgs, flags.classpathArgs, opts,
-				fmt.Sprintf(`\n******************************\n`+
-					`You have tried to change the API from what has been previously approved.\n\n`+
-					`To make these errors go away, you have two choices:\n`+
-					`   1. You can add '@hide' javadoc comments to the methods, etc. listed in the\n`+
-					`      errors above.\n\n`+
-					`   2. You can update current.txt by executing the following command:\n`+
-					`         make %s-update-current-api\n\n`+
-					`      To submit the revised current.txt to the main Android repository,\n`+
-					`      you will need approval.\n`+
-					`******************************\n`, ctx.ModuleName()),
-				d.checkCurrentApiTimestamp)
-		}
+		d.transformCheckApi(ctx, apiFile, removedApiFile, metalavaCheckApiImplicits,
+			javaVersion, flags.bootClasspathArgs, flags.classpathArgs, flags.sourcepathArgs, opts,
+			fmt.Sprintf(`\n******************************\n`+
+				`You have tried to change the API from what has been previously approved.\n\n`+
+				`To make these errors go away, you have two choices:\n`+
+				`   1. You can add '@hide' javadoc comments to the methods, etc. listed in the\n`+
+				`      errors above.\n\n`+
+				`   2. You can update current.txt by executing the following command:\n`+
+				`         make %s-update-current-api\n\n`+
+				`      To submit the revised current.txt to the main Android repository,\n`+
+				`      you will need approval.\n`+
+				`******************************\n`, ctx.ModuleName()),
+			d.checkCurrentApiTimestamp)
 
 		d.updateCurrentApiTimestamp = android.PathForModuleOut(ctx, "update_current_api.timestamp")
-		d.transformUpdateApi(ctx, apiFile, removedApiFile, d.updateCurrentApiTimestamp)
+		transformUpdateApi(ctx, apiFile, removedApiFile, d.apiFile, d.removedApiFile,
+			d.updateCurrentApiTimestamp)
 	}
 
-	if d.checkLastReleasedApi() && !ctx.Config().IsPdkBuild() {
+	if apiCheckEnabled(d.properties.Check_api.Last_released, "last_released") &&
+		!ctx.Config().IsPdkBuild() {
 		apiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Api_file),
 			"check_api.last_released.api_file")
 		removedApiFile := ctx.ExpandSource(String(d.properties.Check_api.Last_released.Removed_api_file),
 			"check_api.last_released.removed_api_file")
 
 		d.checkLastReleasedApiTimestamp = android.PathForModuleOut(ctx, "check_last_released_api.timestamp")
-		if !Bool(d.properties.Metalava_enabled) {
-			d.transformCheckApi(ctx, apiFile, removedApiFile, checkApiClasspath,
-				`\n******************************\n`+
-					`You have tried to change the API from what has been previously released in\n`+
-					`an SDK.  Please fix the errors listed above.\n`+
-					`******************************\n`, String(d.properties.Check_api.Last_released.Args),
-				d.checkLastReleasedApiTimestamp)
-		} else {
-			opts := flags.args + " --check-compatibility:api:released " + apiFile.String() +
-				" --check-compatibility:removed:released " + removedApiFile.String() + " "
+		opts := d.Javadoc.args + " --check-compatibility:api:released " + apiFile.String() +
+			" --check-compatibility:removed:released " + removedApiFile.String() + " "
 
-			d.transformMetalavaCheckApi(ctx, apiFile, removedApiFile, metalavaCheckApiImplicits,
-				javaVersion, flags.bootClasspathArgs, flags.classpathArgs, opts,
-				`\n******************************\n`+
-					`You have tried to change the API from what has been previously released in\n`+
-					`an SDK.  Please fix the errors listed above.\n`+
-					`******************************\n`,
-				d.checkLastReleasedApiTimestamp)
-		}
+		d.transformCheckApi(ctx, apiFile, removedApiFile, metalavaCheckApiImplicits,
+			javaVersion, flags.bootClasspathArgs, flags.classpathArgs, flags.sourcepathArgs, opts,
+			`\n******************************\n`+
+				`You have tried to change the API from what has been previously released in\n`+
+				`an SDK.  Please fix the errors listed above.\n`+
+				`******************************\n`,
+			d.checkLastReleasedApiTimestamp)
 	}
 }
 
@@ -1281,6 +1567,7 @@
 //
 var droiddocTemplateTag = dependencyTag{name: "droiddoc-template"}
 var metalavaMergeAnnotationsDirTag = dependencyTag{name: "metalava-merge-annotations-dir"}
+var metalavaAPILevelsAnnotationsDirTag = dependencyTag{name: "metalava-api-levels-annotations-dir"}
 
 type ExportedDroiddocDirProperties struct {
 	// path to the directory containing Droiddoc related files.
@@ -1337,3 +1624,16 @@
 
 	return module
 }
+
+func StubsDefaultsFactory() android.Module {
+	module := &DocDefaults{}
+
+	module.AddProperties(
+		&JavadocProperties{},
+		&DroidstubsProperties{},
+	)
+
+	android.InitDefaultsModule(module)
+
+	return module
+}
diff --git a/java/java.go b/java/java.go
index 7f82c77..4bf5880 100644
--- a/java/java.go
+++ b/java/java.go
@@ -75,7 +75,7 @@
 	// list of files to use as Java resources
 	Java_resources []string `android:"arch_variant"`
 
-	// list of files that should be excluded from java_resources
+	// list of files that should be excluded from java_resources and java_resource_dirs
 	Exclude_java_resources []string `android:"arch_variant"`
 
 	// don't build against the default libraries (bootclasspath, legacy-test, core-junit,
@@ -86,10 +86,6 @@
 	// ext, and framework for device targets)
 	No_framework_libs *bool
 
-	// Use renamed kotlin stdlib (com.android.kotlin.*). This allows kotlin usage without colliding
-	// with app-provided kotlin stdlib.
-	Renamed_kotlin_stdlib *bool
-
 	// list of module-specific flags that will be used for javac compiles
 	Javacflags []string `android:"arch_variant"`
 
@@ -416,7 +412,7 @@
 
 func sdkVersionOrDefault(ctx android.BaseContext, v string) string {
 	switch v {
-	case "", "current", "system_current", "test_current", "core_current":
+	case "", "current", "system_current", "test_current", "core_current", "core_platform_current":
 		return ctx.Config().DefaultAppTargetSdk()
 	default:
 		return v
@@ -427,7 +423,7 @@
 // it returns android.FutureApiLevel (10000).
 func sdkVersionToNumber(ctx android.BaseContext, v string) (int, error) {
 	switch v {
-	case "", "current", "test_current", "system_current", "core_current":
+	case "", "current", "test_current", "system_current", "core_current", "core_platform_current":
 		return ctx.Config().DefaultAppTargetSdkInt(), nil
 	default:
 		n := android.GetNumericSdkVersion(v)
@@ -524,6 +520,8 @@
 		}
 		if m == "core.current.stubs" {
 			ret.systemModules = "core-system-modules"
+		} else if m == "core.platform.api.stubs" {
+			ret.systemModules = "core-platform-api-stubs-system-modules"
 		}
 		return ret
 	}
@@ -546,6 +544,8 @@
 		return toModule("android_test_stubs_current", "framework-res")
 	case "core_current":
 		return toModule("core.current.stubs", "")
+	case "core_platform_current":
+		return toModule("core.platform.api.stubs", "")
 	default:
 		return toPrebuilt(v)
 	}
@@ -556,41 +556,37 @@
 		if !Bool(j.properties.No_standard_libs) {
 			sdkDep := decodeSdkDep(ctx, sdkContext(j))
 			if sdkDep.useDefaultLibs {
-				ctx.AddDependency(ctx.Module(), bootClasspathTag, config.DefaultBootclasspathLibraries...)
-				if ctx.Config().TargetOpenJDK9() {
-					ctx.AddDependency(ctx.Module(), systemModulesTag, config.DefaultSystemModules)
-				}
+				ctx.AddVariationDependencies(nil, bootClasspathTag, config.DefaultBootclasspathLibraries...)
+				ctx.AddVariationDependencies(nil, systemModulesTag, config.DefaultSystemModules)
 				if !Bool(j.properties.No_framework_libs) {
-					ctx.AddDependency(ctx.Module(), libTag, config.DefaultLibraries...)
+					ctx.AddVariationDependencies(nil, libTag, config.DefaultLibraries...)
 				}
 			} else if sdkDep.useModule {
-				if ctx.Config().TargetOpenJDK9() {
-					ctx.AddDependency(ctx.Module(), systemModulesTag, sdkDep.systemModules)
-				}
-				ctx.AddDependency(ctx.Module(), bootClasspathTag, sdkDep.modules...)
+				ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
+				ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.modules...)
 				if Bool(j.deviceProperties.Optimize.Enabled) {
-					ctx.AddDependency(ctx.Module(), proguardRaiseTag, config.DefaultBootclasspathLibraries...)
-					ctx.AddDependency(ctx.Module(), proguardRaiseTag, config.DefaultLibraries...)
+					ctx.AddVariationDependencies(nil, proguardRaiseTag, config.DefaultBootclasspathLibraries...)
+					ctx.AddVariationDependencies(nil, proguardRaiseTag, config.DefaultLibraries...)
 				}
 			}
 		} else if j.deviceProperties.System_modules == nil {
 			ctx.PropertyErrorf("no_standard_libs",
 				"system_modules is required to be set when no_standard_libs is true, did you mean no_framework_libs?")
-		} else if *j.deviceProperties.System_modules != "none" && ctx.Config().TargetOpenJDK9() {
-			ctx.AddDependency(ctx.Module(), systemModulesTag, *j.deviceProperties.System_modules)
+		} else if *j.deviceProperties.System_modules != "none" {
+			ctx.AddVariationDependencies(nil, systemModulesTag, *j.deviceProperties.System_modules)
 		}
-		if ctx.ModuleName() == "framework" {
-			ctx.AddDependency(ctx.Module(), frameworkResTag, "framework-res")
+		if (ctx.ModuleName() == "framework") || (ctx.ModuleName() == "framework-annotation-proc") {
+			ctx.AddVariationDependencies(nil, frameworkResTag, "framework-res")
 		}
 		if ctx.ModuleName() == "android_stubs_current" ||
 			ctx.ModuleName() == "android_system_stubs_current" ||
 			ctx.ModuleName() == "android_test_stubs_current" {
-			ctx.AddDependency(ctx.Module(), frameworkApkTag, "framework-res")
+			ctx.AddVariationDependencies(nil, frameworkApkTag, "framework-res")
 		}
 	}
 
-	ctx.AddDependency(ctx.Module(), libTag, j.properties.Libs...)
-	ctx.AddDependency(ctx.Module(), staticLibTag, j.properties.Static_libs...)
+	ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
+	ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
 	ctx.AddFarVariationDependencies([]blueprint.Variation{
 		{Mutator: "arch", Variation: ctx.Config().BuildOsCommonVariant},
 	}, annoTag, j.properties.Annotation_processors...)
@@ -606,11 +602,11 @@
 	if j.hasSrcExt(".kt") {
 		// TODO(ccross): move this to a mutator pass that can tell if generated sources contain
 		// Kotlin files
-		ctx.AddDependency(ctx.Module(), kotlinStdlibTag, "kotlin-stdlib")
+		ctx.AddVariationDependencies(nil, kotlinStdlibTag, "kotlin-stdlib")
 	}
 
 	if j.shouldInstrumentStatic(ctx) {
-		ctx.AddDependency(ctx.Module(), staticLibTag, "jacocoagent")
+		ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
 	}
 }
 
@@ -712,8 +708,9 @@
 	ver := m.sdkVersion()
 	noStdLibs := Bool(m.properties.No_standard_libs)
 	switch {
-	case name == "core.current.stubs" || ver == "core_current" || noStdLibs || name == "stub-annotations" ||
-		name == "private-stub-annotations-jar":
+	case name == "core.current.stubs" || ver == "core_current" ||
+		name == "core.platform.api.stubs" || ver == "core_platform_current" ||
+		noStdLibs || name == "stub-annotations" || name == "private-stub-annotations-jar":
 		return javaCore
 	case name == "android_system_stubs_current" || strings.HasPrefix(ver, "system_"):
 		return javaSystem
@@ -808,7 +805,7 @@
 			case annoTag:
 				deps.processorPath = append(deps.processorPath, dep.ImplementationAndResourcesJars()...)
 			case frameworkResTag:
-				if ctx.ModuleName() == "framework" {
+				if (ctx.ModuleName() == "framework") || (ctx.ModuleName() == "framework-annotation-proc") {
 					// framework.jar has a one-off dependency on the R.java and Manifest.java files
 					// generated by framework-res.apk
 					deps.srcJars = append(deps.srcJars, dep.(*AndroidApp).aaptSrcJar)
@@ -904,9 +901,12 @@
 
 	var flags javaBuilderFlags
 
+	// javaVersion flag.
+	flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), sdkContext(j))
+
 	// javac flags.
 	javacFlags := j.properties.Javacflags
-	if ctx.Config().TargetOpenJDK9() {
+	if flags.javaVersion == "1.9" {
 		javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
 	}
 	if ctx.Config().MinimizeJavaDebugInfo() {
@@ -931,15 +931,12 @@
 		flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
 	}
 
-	// javaVersion flag.
-	flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), sdkContext(j))
-
 	// classpath
 	flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
 	flags.classpath = append(flags.classpath, deps.classpath...)
 	flags.processorPath = append(flags.processorPath, deps.processorPath...)
 
-	if len(flags.bootClasspath) == 0 && ctx.Host() && !ctx.Config().TargetOpenJDK9() &&
+	if len(flags.bootClasspath) == 0 && ctx.Host() && flags.javaVersion != "1.9" &&
 		!Bool(j.properties.No_standard_libs) &&
 		inList(flags.javaVersion, []string{"1.6", "1.7", "1.8"}) {
 		// Give host-side tools a version of OpenJDK's standard libraries
@@ -965,7 +962,7 @@
 		}
 	}
 
-	if j.properties.Patch_module != nil && ctx.Config().TargetOpenJDK9() {
+	if j.properties.Patch_module != nil && flags.javaVersion == "1.9" {
 		patchClasspath := ".:" + flags.classpath.FormJavaClassPath("")
 		javacFlags = append(javacFlags, "--patch-module="+String(j.properties.Patch_module)+"="+patchClasspath)
 	}
@@ -999,7 +996,7 @@
 	deps := j.collectDeps(ctx)
 	flags := j.collectBuilderFlags(ctx, deps)
 
-	if ctx.Config().TargetOpenJDK9() {
+	if flags.javaVersion == "1.9" {
 		j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
 	}
 	srcFiles := ctx.ExpandSources(j.properties.Srcs, j.properties.Exclude_srcs)
@@ -1025,8 +1022,6 @@
 		}
 	}
 
-	var stripFiles []string
-
 	var kotlinJars android.Paths
 
 	if srcFiles.HasExt(".kt") {
@@ -1035,7 +1030,6 @@
 		// won't emit any classes for them.
 
 		flags.kotlincFlags = "-no-stdlib"
-
 		if ctx.Device() {
 			flags.kotlincFlags += " -no-jdk"
 		}
@@ -1060,18 +1054,7 @@
 
 		// Jar kotlin classes into the final jar after javac
 		kotlinJars = append(kotlinJars, kotlinJar)
-
-		if Bool(j.properties.Renamed_kotlin_stdlib) {
-			// Remove any kotlin-reflect related files
-			// TODO(pszczepaniak): Support kotlin-reflect
-			stripFiles = append(stripFiles,
-				"**/*.kotlin_module",
-				"**/*.kotlin_builtins")
-		} else {
-			// Only add kotlin-stdlib if not using (on-device) renamed stdlib
-			// (it's expected to be on device bootclasspath)
-			kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
-		}
+		kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
 	}
 
 	jars := append(android.Paths(nil), kotlinJars...)
@@ -1136,7 +1119,8 @@
 		}
 	}
 
-	dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs, j.properties.Exclude_java_resource_dirs)
+	dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
+		j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
 	fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
 
 	var resArgs []string
@@ -1207,21 +1191,10 @@
 	} else {
 		combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
 		TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
-			false, stripFiles, nil)
+			false, nil, nil)
 		outputFile = combinedJar
 	}
 
-	// Use renamed kotlin standard library?
-	if srcFiles.HasExt(".kt") && Bool(j.properties.Renamed_kotlin_stdlib) {
-		jarjarFile := android.PathForModuleOut(ctx, "kotlin-renamed", jarName)
-		TransformJarJar(ctx, jarjarFile, outputFile,
-			android.PathForSource(ctx, "external/kotlinc/jarjar-rules.txt"))
-		outputFile = jarjarFile
-		if ctx.Failed() {
-			return
-		}
-	}
-
 	// jarjar implementation jar if necessary
 	if j.properties.Jarjar_rules != nil {
 		jarjar_rules := android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
@@ -1611,6 +1584,9 @@
 
 	// List of directories to remove from the jar file(s)
 	Exclude_dirs []string
+
+	// if set to true, run Jetifier against .jar file. Defaults to false.
+	Jetifier_enabled *bool
 }
 
 type Import struct {
@@ -1645,15 +1621,21 @@
 
 func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
 	android.ExtractSourcesDeps(ctx, j.properties.Jars)
-	ctx.AddDependency(ctx.Module(), libTag, j.properties.Libs...)
+	ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
 }
 
 func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	jars := ctx.ExpandSources(j.properties.Jars, nil)
 
-	outputFile := android.PathForModuleOut(ctx, "classes.jar")
+	jarName := ctx.ModuleName() + ".jar"
+	outputFile := android.PathForModuleOut(ctx, "combined", jarName)
 	TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
 		false, j.properties.Exclude_files, j.properties.Exclude_dirs)
+	if Bool(j.properties.Jetifier_enabled) {
+		inputFile := outputFile
+		outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
+		TransformJetifier(ctx, outputFile, inputFile)
+	}
 	j.combinedClasspathFile = outputFile
 
 	ctx.VisitDirectDeps(func(module android.Module) {
diff --git a/java/java_resources.go b/java/java_resources.go
index e02709d..fdc1590 100644
--- a/java/java_resources.go
+++ b/java/java_resources.go
@@ -32,7 +32,7 @@
 }
 
 func ResourceDirsToJarArgs(ctx android.ModuleContext,
-	resourceDirs, excludeResourceDirs []string) (args []string, deps android.Paths) {
+	resourceDirs, excludeResourceDirs, excludeResourceFiles []string) (args []string, deps android.Paths) {
 	var excludeDirs []string
 	var excludeFiles []string
 
@@ -44,6 +44,8 @@
 		}
 	}
 
+	excludeFiles = append(excludeFiles, ctx.ExpandSources(excludeResourceFiles, nil).Strings()...)
+
 	excludeFiles = append(excludeFiles, resourceExcludes...)
 
 	for _, resourceDir := range resourceDirs {
diff --git a/java/java_test.go b/java/java_test.go
index 72341ee..82accd5 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -101,6 +101,7 @@
 		"core-oj",
 		"core-libart",
 		"core-lambda-stubs",
+		"core-simple",
 		"framework",
 		"ext",
 		"okhttp",
@@ -208,8 +209,6 @@
 		"bar-doc/IFoo.aidl":              nil,
 		"bar-doc/known_oj_tags.txt":      nil,
 		"external/doclava/templates-sdk": nil,
-
-		"external/kotlinc/jarjar-rules.txt": nil,
 	}
 
 	for k, v := range fs {
@@ -353,14 +352,14 @@
 }{
 	{
 		name:          "default",
-		bootclasspath: []string{"core-oj", "core-libart"},
+		bootclasspath: []string{"core-oj", "core-libart", "core-simple"},
 		system:        "core-system-modules",
 		classpath:     []string{"ext", "framework", "okhttp"},
 	},
 	{
 		name:          "blank sdk version",
 		properties:    `sdk_version: "",`,
-		bootclasspath: []string{"core-oj", "core-libart"},
+		bootclasspath: []string{"core-oj", "core-libart", "core-simple"},
 		system:        "core-system-modules",
 		classpath:     []string{"ext", "framework", "okhttp"},
 	},
@@ -703,6 +702,30 @@
 			prop: `java_resource_dirs: ["java-res/*"], exclude_java_resource_dirs: ["java-res/b"]`,
 			args: "-C java-res/a -f java-res/a/a",
 		},
+		{
+			// Test wildcards in java_resources
+			name: "wildcard files",
+			prop: `java_resources: ["java-res/**/*"]`,
+			args: "-C . -f java-res/a/a -f java-res/b/b",
+		},
+		{
+			// Test exclude_java_resources with java_resources
+			name: "wildcard files with exclude",
+			prop: `java_resources: ["java-res/**/*"], exclude_java_resources: ["java-res/b/*"]`,
+			args: "-C . -f java-res/a/a",
+		},
+		{
+			// Test exclude_java_resources with java_resource_dirs
+			name: "resource dirs with exclude files",
+			prop: `java_resource_dirs: ["java-res"], exclude_java_resources: ["java-res/b/b"]`,
+			args: "-C java-res -f java-res/a/a",
+		},
+		{
+			// Test exclude_java_resource_dirs with java_resource_dirs
+			name: "resource dirs with exclude files",
+			prop: `java_resource_dirs: ["java-res", "java-res2"], exclude_java_resource_dirs: ["java-res2"]`,
+			args: "-C java-res -f java-res/a/a -f java-res/b/b",
+		},
 	}
 
 	for _, test := range table {
@@ -735,42 +758,6 @@
 	}
 }
 
-func TestExcludeResources(t *testing.T) {
-	ctx := testJava(t, `
-		java_library {
-			name: "foo",
-			srcs: ["a.java"],
-			java_resource_dirs: ["java-res", "java-res2"],
-			exclude_java_resource_dirs: ["java-res2"],
-		}
-
-		java_library {
-			name: "bar",
-			srcs: ["a.java"],
-			java_resources: ["java-res/*/*"],
-			exclude_java_resources: ["java-res/b/*"],
-		}
-	`)
-
-	fooRes := ctx.ModuleForTests("foo", "android_common").Output("res/foo.jar")
-
-	expected := "-C java-res -f java-res/a/a -f java-res/b/b"
-	if fooRes.Args["jarArgs"] != expected {
-		t.Errorf("foo resource jar args %q is not %q",
-			fooRes.Args["jarArgs"], expected)
-
-	}
-
-	barRes := ctx.ModuleForTests("bar", "android_common").Output("res/bar.jar")
-
-	expected = "-C . -f java-res/a/a"
-	if barRes.Args["jarArgs"] != expected {
-		t.Errorf("bar resource jar args %q is not %q",
-			barRes.Args["jarArgs"], expected)
-
-	}
-}
-
 func TestGeneratedSources(t *testing.T) {
 	ctx := testJava(t, `
 		java_library {
@@ -822,12 +809,6 @@
 			name: "baz",
 			srcs: ["c.java"],
 		}
-
-		java_library {
-			name: "blorg",
-			renamed_kotlin_stdlib: true,
-			srcs: ["b.kt"],
-		}
 		`)
 
 	fooKotlinc := ctx.ModuleForTests("foo", "android_common").Rule("kotlinc")
@@ -870,12 +851,6 @@
 		t.Errorf(`expected %q in bar implicits %v`,
 			bazHeaderJar.Output.String(), barKotlinc.Implicits.Strings())
 	}
-
-	blorgRenamedJar := ctx.ModuleForTests("blorg", "android_common").Output("kotlin-renamed/blorg.jar")
-	if blorgRenamedJar.Implicit.String() != "external/kotlinc/jarjar-rules.txt" {
-		t.Errorf(`expected external/kotlinc/jarjar-rules.txt in blorg implicit %q`,
-			blorgRenamedJar.Implicit.String())
-	}
 }
 
 func TestTurbine(t *testing.T) {
diff --git a/java/proto.go b/java/proto.go
index 58b039e..8028039 100644
--- a/java/proto.go
+++ b/java/proto.go
@@ -73,14 +73,14 @@
 func protoDeps(ctx android.BottomUpMutatorContext, p *android.ProtoProperties) {
 	switch String(p.Proto.Type) {
 	case "micro":
-		ctx.AddDependency(ctx.Module(), staticLibTag, "libprotobuf-java-micro")
+		ctx.AddVariationDependencies(nil, staticLibTag, "libprotobuf-java-micro")
 	case "nano":
-		ctx.AddDependency(ctx.Module(), staticLibTag, "libprotobuf-java-nano")
+		ctx.AddVariationDependencies(nil, staticLibTag, "libprotobuf-java-nano")
 	case "lite", "":
-		ctx.AddDependency(ctx.Module(), staticLibTag, "libprotobuf-java-lite")
+		ctx.AddVariationDependencies(nil, staticLibTag, "libprotobuf-java-lite")
 	case "full":
 		if ctx.Host() {
-			ctx.AddDependency(ctx.Module(), staticLibTag, "libprotobuf-java-full")
+			ctx.AddVariationDependencies(nil, staticLibTag, "libprotobuf-java-full")
 		} else {
 			ctx.PropertyErrorf("proto.type", "full java protos only supported on the host")
 		}
diff --git a/java/sdk_library.go b/java/sdk_library.go
index 525652a..3e6908b 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -156,14 +156,14 @@
 
 func (module *sdkLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
 	// Add dependencies to the stubs library
-	ctx.AddDependency(ctx.Module(), publicApiStubsTag, module.stubsName(apiScopePublic))
-	ctx.AddDependency(ctx.Module(), systemApiStubsTag, module.stubsName(apiScopeSystem))
-	ctx.AddDependency(ctx.Module(), testApiStubsTag, module.stubsName(apiScopeTest))
-	ctx.AddDependency(ctx.Module(), implLibTag, module.implName())
+	ctx.AddVariationDependencies(nil, publicApiStubsTag, module.stubsName(apiScopePublic))
+	ctx.AddVariationDependencies(nil, systemApiStubsTag, module.stubsName(apiScopeSystem))
+	ctx.AddVariationDependencies(nil, testApiStubsTag, module.stubsName(apiScopeTest))
+	ctx.AddVariationDependencies(nil, implLibTag, module.implName())
 
-	ctx.AddDependency(ctx.Module(), publicApiFileTag, module.docsName(apiScopePublic))
-	ctx.AddDependency(ctx.Module(), systemApiFileTag, module.docsName(apiScopeSystem))
-	ctx.AddDependency(ctx.Module(), testApiFileTag, module.docsName(apiScopeTest))
+	ctx.AddVariationDependencies(nil, publicApiFileTag, module.docsName(apiScopePublic))
+	ctx.AddVariationDependencies(nil, systemApiFileTag, module.docsName(apiScopeSystem))
+	ctx.AddVariationDependencies(nil, testApiFileTag, module.docsName(apiScopeTest))
 }
 
 func (module *sdkLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
@@ -217,38 +217,45 @@
 			fmt.Fprintln(w, "LOCAL_MODULE :=", name)
 			fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES := "+module.implName())
 			fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
+			owner := module.ModuleBase.Owner()
+			if owner == "" {
+				owner = "android"
+			}
 			// Create dist rules to install the stubs libs to the dist dir
 			if len(module.publicApiStubsPath) == 1 {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.publicApiStubsPath.Strings()[0]+
-					":"+path.Join("apistubs", "public", module.BaseModuleName()+".jar")+")")
+					":"+path.Join("apistubs", owner, "public",
+					module.BaseModuleName()+".jar")+")")
 			}
 			if len(module.systemApiStubsPath) == 1 {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.systemApiStubsPath.Strings()[0]+
-					":"+path.Join("apistubs", "system", module.BaseModuleName()+".jar")+")")
+					":"+path.Join("apistubs", owner, "system",
+					module.BaseModuleName()+".jar")+")")
 			}
 			if len(module.testApiStubsPath) == 1 {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.testApiStubsPath.Strings()[0]+
-					":"+path.Join("apistubs", "test", module.BaseModuleName()+".jar")+")")
+					":"+path.Join("apistubs", owner, "test",
+					module.BaseModuleName()+".jar")+")")
 			}
 			if module.publicApiFilePath != nil {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.publicApiFilePath.String()+
-					":"+path.Join("apistubs", "public", "api",
+					":"+path.Join("apistubs", owner, "public", "api",
 					module.BaseModuleName()+".txt")+")")
 			}
 			if module.systemApiFilePath != nil {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.systemApiFilePath.String()+
-					":"+path.Join("apistubs", "system", "api",
+					":"+path.Join("apistubs", owner, "system", "api",
 					module.BaseModuleName()+".txt")+")")
 			}
 			if module.testApiFilePath != nil {
 				fmt.Fprintln(w, "$(call dist-for-goals,sdk win_sdk,"+
 					module.testApiFilePath.String()+
-					":"+path.Join("apistubs", "test", "api",
+					":"+path.Join("apistubs", owner, "test", "api",
 					module.BaseModuleName()+".txt")+")")
 			}
 		},
diff --git a/java/system_modules.go b/java/system_modules.go
index d98e0ab..9ee0307 100644
--- a/java/system_modules.go
+++ b/java/system_modules.go
@@ -123,7 +123,7 @@
 }
 
 func (system *SystemModules) DepsMutator(ctx android.BottomUpMutatorContext) {
-	ctx.AddDependency(ctx.Module(), libTag, system.properties.Libs...)
+	ctx.AddVariationDependencies(nil, libTag, system.properties.Libs...)
 }
 
 func (system *SystemModules) AndroidMk() android.AndroidMkData {
diff --git a/scripts/build-ndk-prebuilts.sh b/scripts/build-ndk-prebuilts.sh
index e3552a0..7f6e2c9 100755
--- a/scripts/build-ndk-prebuilts.sh
+++ b/scripts/build-ndk-prebuilts.sh
@@ -62,7 +62,6 @@
         "armeabi-v7a"
     ],
     "HostArch": "x86_64",
-    "HostSecondaryArch": "x86",
     "Malloc_not_svelte": false,
     "Safestack": false
 }
diff --git a/scripts/manifest_fixer.py b/scripts/manifest_fixer.py
index 25f96cd..b6fe34e 100755
--- a/scripts/manifest_fixer.py
+++ b/scripts/manifest_fixer.py
@@ -49,10 +49,16 @@
   parser = argparse.ArgumentParser()
   parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
                       help='specify minSdkVersion used by the build system')
+  parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
+                      help='specify targetSdkVersion used by the build system')
+  parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
+                      help='raise the minimum sdk version in the manifest if necessary')
   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')
+  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')
   parser.add_argument('output', help='output AndroidManifest.xml file')
   return parser.parse_args()
@@ -128,12 +134,13 @@
   return indent
 
 
-def raise_min_sdk_version(doc, requested, library):
+def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
   """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
 
   Args:
     doc: The XML document.  May be modified by this function.
-    requested: The requested minSdkVersion attribute.
+    min_sdk_version: The requested minSdkVersion attribute.
+    target_sdk_version: The requested targetSdkVersion attribute.
   Raises:
     RuntimeError: invalid manifest
   """
@@ -160,11 +167,11 @@
   min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
   if min_attr is None:
     min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
-    min_attr.value = requested
+    min_attr.value = min_sdk_version
     element.setAttributeNode(min_attr)
   else:
-    if compare_version_gt(requested, min_attr.value):
-      min_attr.value = requested
+    if compare_version_gt(min_sdk_version, min_attr.value):
+      min_attr.value = min_sdk_version
 
   # Insert the targetSdkVersion attribute if it is missing.  If it is already
   # present leave it as is.
@@ -174,7 +181,7 @@
     if library:
       target_attr.value = '1'
     else:
-      target_attr.value = requested
+      target_attr.value = target_sdk_version
     element.setAttributeNode(target_attr)
 
 
@@ -226,6 +233,33 @@
     indent = get_indent(application.previousSibling, 1)
     application.appendChild(doc.createTextNode(indent))
 
+def add_uses_non_sdk_api(doc):
+  """Add android:usesNonSdkApi=true attribute to <application>.
+
+  Args:
+    doc: The XML document. May be modified by this function.
+  Raises:
+    RuntimeError: Invalid manifest
+  """
+
+  manifest = parse_manifest(doc)
+  elems = get_children_with_tag(manifest, 'application')
+  application = elems[0] if len(elems) == 1 else None
+  if len(elems) > 1:
+    raise RuntimeError('found multiple <application> tags')
+  elif not elems:
+    application = doc.createElement('application')
+    indent = get_indent(manifest.firstChild, 1)
+    first = manifest.firstChild
+    manifest.insertBefore(doc.createTextNode(indent), first)
+    manifest.insertBefore(application, first)
+
+  attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
+  if attr is None:
+    attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
+    attr.value = 'true'
+    application.setAttributeNode(attr)
+
 
 def write_xml(f, doc):
   f.write('<?xml version="1.0" encoding="utf-8"?>\n')
@@ -242,12 +276,15 @@
 
     ensure_manifest_android_ns(doc)
 
-    if args.min_sdk_version:
-      raise_min_sdk_version(doc, args.min_sdk_version, args.library)
+    if args.raise_min_sdk_version:
+      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)
 
+    if args.uses_non_sdk_api:
+      add_uses_non_sdk_api(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 5908997..66a2317 100755
--- a/scripts/manifest_fixer_test.py
+++ b/scripts/manifest_fixer_test.py
@@ -54,9 +54,11 @@
 class RaiseMinSdkVersionTest(unittest.TestCase):
   """Unit tests for raise_min_sdk_version function."""
 
-  def raise_min_sdk_version_test(self, input_manifest, min_sdk_version, library):
+  def raise_min_sdk_version_test(self, input_manifest, min_sdk_version,
+                                 target_sdk_version, library):
     doc = minidom.parseString(input_manifest)
-    manifest_fixer.raise_min_sdk_version(doc, min_sdk_version, library)
+    manifest_fixer.raise_min_sdk_version(doc, min_sdk_version,
+                                         target_sdk_version, library)
     output = StringIO.StringIO()
     manifest_fixer.write_xml(output, doc)
     return output.getvalue()
@@ -69,13 +71,13 @@
 
   # pylint: disable=redefined-builtin
   def uses_sdk(self, min=None, target=None, extra=''):
-    attrs = ""
+    attrs = ''
     if min:
       attrs += ' android:minSdkVersion="%s"' % (min)
     if target:
       attrs += ' android:targetSdkVersion="%s"' % (target)
     if extra:
-        attrs += ' ' + extra
+      attrs += ' ' + extra
     return '    <uses-sdk%s/>\n' % (attrs)
 
   def test_no_uses_sdk(self):
@@ -83,7 +85,7 @@
 
     manifest_input = self.manifest_tmpl % ''
     expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '28', False)
     self.assertEqual(output, expected)
 
   def test_no_min(self):
@@ -92,47 +94,47 @@
     manifest_input = self.manifest_tmpl % '    <uses-sdk extra="foo"/>\n'
     expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28',
                                                   extra='extra="foo"')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '28', False)
     self.assertEqual(output, expected)
 
   def test_raise_min(self):
     """Tests inserting a minSdkVersion attribute into a uses-sdk element."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='27')
-    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '28', False)
     self.assertEqual(output, expected)
 
   def test_raise(self):
     """Tests raising a minSdkVersion attribute."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='27')
-    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '28', False)
     self.assertEqual(output, expected)
 
   def test_no_raise_min(self):
     """Tests a minSdkVersion that doesn't need raising."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='28')
-    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28')
-    output = self.raise_min_sdk_version_test(manifest_input, '27', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
+    output = self.raise_min_sdk_version_test(manifest_input, '27', '27', False)
     self.assertEqual(output, expected)
 
   def test_raise_codename(self):
     """Tests raising a minSdkVersion attribute to a codename."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='28')
-    expected = self.manifest_tmpl % self.uses_sdk(min='P', target='28')
-    output = self.raise_min_sdk_version_test(manifest_input, 'P', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='P', target='P')
+    output = self.raise_min_sdk_version_test(manifest_input, 'P', 'P', False)
     self.assertEqual(output, expected)
 
   def test_no_raise_codename(self):
     """Tests a minSdkVersion codename that doesn't need raising."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='P')
-    expected = self.manifest_tmpl % self.uses_sdk(min='P', target='P')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='P', target='28')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '28', False)
     self.assertEqual(output, expected)
 
   def test_target(self):
@@ -140,56 +142,56 @@
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='26', target='27')
     expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
     self.assertEqual(output, expected)
 
   def test_no_target(self):
     """Tests inserting targetSdkVersion when minSdkVersion exists."""
 
     manifest_input = self.manifest_tmpl % self.uses_sdk(min='27')
-    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='29')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
     self.assertEqual(output, expected)
 
   def test_target_no_min(self):
-      """Tests inserting targetSdkVersion when minSdkVersion exists."""
+    """"Tests inserting targetSdkVersion when minSdkVersion exists."""
 
-      manifest_input = self.manifest_tmpl % self.uses_sdk(target='27')
-      expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-      output = self.raise_min_sdk_version_test(manifest_input, '28', False)
-      self.assertEqual(output, expected)
+    manifest_input = self.manifest_tmpl % self.uses_sdk(target='27')
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
+    self.assertEqual(output, expected)
 
   def test_no_target_no_min(self):
     """Tests inserting targetSdkVersion when minSdkVersion does not exist."""
 
     manifest_input = self.manifest_tmpl % ''
-    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='28')
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='29')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
     self.assertEqual(output, expected)
 
   def test_library_no_target(self):
-      """Tests inserting targetSdkVersion when minSdkVersion exists."""
+    """Tests inserting targetSdkVersion when minSdkVersion exists."""
 
-      manifest_input = self.manifest_tmpl % self.uses_sdk(min='27')
-      expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-      output = self.raise_min_sdk_version_test(manifest_input, '28', True)
-      self.assertEqual(output, expected)
+    manifest_input = self.manifest_tmpl % self.uses_sdk(min='27')
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='1')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', True)
+    self.assertEqual(output, expected)
 
   def test_library_target_no_min(self):
-      """Tests inserting targetSdkVersion when minSdkVersion exists."""
+    """Tests inserting targetSdkVersion when minSdkVersion exists."""
 
-      manifest_input = self.manifest_tmpl % self.uses_sdk(target='27')
-      expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
-      output = self.raise_min_sdk_version_test(manifest_input, '28', True)
-      self.assertEqual(output, expected)
+    manifest_input = self.manifest_tmpl % self.uses_sdk(target='27')
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='27')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', True)
+    self.assertEqual(output, expected)
 
   def test_library_no_target_no_min(self):
-      """Tests inserting targetSdkVersion when minSdkVersion does not exist."""
+    """Tests inserting targetSdkVersion when minSdkVersion does not exist."""
 
-      manifest_input = self.manifest_tmpl % ''
-      expected = self.manifest_tmpl % self.uses_sdk(min='28', target='1')
-      output = self.raise_min_sdk_version_test(manifest_input, '28', True)
-      self.assertEqual(output, expected)
+    manifest_input = self.manifest_tmpl % ''
+    expected = self.manifest_tmpl % self.uses_sdk(min='28', target='1')
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', True)
+    self.assertEqual(output, expected)
 
   def test_extra(self):
     """Tests that extra attributes and elements are maintained."""
@@ -202,10 +204,10 @@
     # pylint: disable=line-too-long
     expected = self.manifest_tmpl % (
         '    <!-- comment -->\n'
-        '    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="27" extra="foo"/>\n'
+        '    <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="29" extra="foo"/>\n'
         '    <application/>\n')
 
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
 
     self.assertEqual(output, expected)
 
@@ -216,10 +218,10 @@
 
     # pylint: disable=line-too-long
     expected = self.manifest_tmpl % (
-        '  <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="28"/>\n'
+        '  <uses-sdk android:minSdkVersion="28" android:targetSdkVersion="29"/>\n'
         '  <!-- comment -->\n')
 
-    output = self.raise_min_sdk_version_test(manifest_input, '28', False)
+    output = self.raise_min_sdk_version_test(manifest_input, '28', '29', False)
 
     self.assertEqual(output, expected)
 
@@ -310,5 +312,39 @@
     self.assertEqual(output, expected)
 
 
+class AddUsesNonSdkApiTest(unittest.TestCase):
+  """Unit tests for add_uses_libraries function."""
+
+  def run_test(self, input_manifest):
+    doc = minidom.parseString(input_manifest)
+    manifest_fixer.add_uses_non_sdk_api(doc)
+    output = StringIO.StringIO()
+    manifest_fixer.write_xml(output, doc)
+    return output.getvalue()
+
+  manifest_tmpl = (
+      '<?xml version="1.0" encoding="utf-8"?>\n'
+      '<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n'
+      '    <application%s/>\n'
+      '</manifest>\n')
+
+  def uses_non_sdk_api(self, value):
+    return ' android:usesNonSdkApi="true"' if value else ''
+
+  def test_set_true(self):
+    """Empty new_uses_libraries must not touch the manifest."""
+    manifest_input = self.manifest_tmpl % self.uses_non_sdk_api(False)
+    expected = self.manifest_tmpl % self.uses_non_sdk_api(True)
+    output = self.run_test(manifest_input)
+    self.assertEqual(output, expected)
+
+  def test_already_set(self):
+    """new_uses_libraries must not overwrite existing tags."""
+    manifest_input = self.manifest_tmpl % self.uses_non_sdk_api(True)
+    expected = manifest_input
+    output = self.run_test(manifest_input)
+    self.assertEqual(output, expected)
+
+
 if __name__ == '__main__':
   unittest.main()
diff --git a/scripts/strip.sh b/scripts/strip.sh
index 432582f..cf8f631 100755
--- a/scripts/strip.sh
+++ b/scripts/strip.sh
@@ -63,27 +63,28 @@
     # we have not found a use case that is broken by objcopy yet.
     REMOVE_SECTIONS=`"${CROSS_COMPILE}readelf" -S "${infile}" | awk '/.debug_/ {print "--remove-section " $2}' | xargs`
     if [ ! -z "${use_llvm_strip}" ]; then
-        "${CROSS_COMPILE}objcopy" "${infile}" "${outfile}.tmp" ${REMOVE_SECTIONS}
-    else
         "${CLANG_BIN}/llvm-objcopy" "${infile}" "${outfile}.tmp" ${REMOVE_SECTIONS}
+    else
+        "${CROSS_COMPILE}objcopy" "${infile}" "${outfile}.tmp" ${REMOVE_SECTIONS}
     fi
 }
 
 do_strip_keep_mini_debug_info() {
     rm -f "${outfile}.dynsyms" "${outfile}.funcsyms" "${outfile}.keep_symbols" "${outfile}.debug" "${outfile}.mini_debuginfo" "${outfile}.mini_debuginfo.xz"
+    local fail=
     if [ ! -z "${use_llvm_strip}" ]; then
-        "${CLANG_BIN}/llvm-strip" --strip-all -keep=.ARM.attributes -remove-section=.comment "${infile}" "${outfile}.tmp"
+        "${CLANG_BIN}/llvm-strip" --strip-all -keep=.ARM.attributes -remove-section=.comment "${infile}" "${outfile}.tmp" || fail=true
     else
-        "${CROSS_COMPILE}strip" --strip-all -R .comment "${infile}" -o "${outfile}.tmp"
+        "${CROSS_COMPILE}strip" --strip-all -R .comment "${infile}" -o "${outfile}.tmp" || fail=true
     fi
-    if [ "$?" == "0" ]; then
+    if [ -z $fail ]; then
         # Current prebult llvm-objcopy does not support the following flags:
         #    --only-keep-debug --rename-section --keep-symbols
         # For the following use cases, ${CROSS_COMPILE}objcopy does fine with lld linked files,
         # except the --add-section flag.
         "${CROSS_COMPILE}objcopy" --only-keep-debug "${infile}" "${outfile}.debug"
-        "${CROSS_COMPILE}nm" -D "${infile}" --format=posix --defined-only | awk '{ print $$1 }' | sort >"${outfile}.dynsyms"
-        "${CROSS_COMPILE}nm" "${infile}" --format=posix --defined-only | awk '{ if ($$2 == "T" || $$2 == "t" || $$2 == "D") print $$1 }' | sort > "${outfile}.funcsyms"
+        "${CROSS_COMPILE}nm" -D "${infile}" --format=posix --defined-only | awk '{ print $1 }' | sort >"${outfile}.dynsyms"
+        "${CROSS_COMPILE}nm" "${infile}" --format=posix --defined-only | awk '{ if ($2 == "T" || $2 == "t" || $2 == "D") print $1 }' | sort > "${outfile}.funcsyms"
         comm -13 "${outfile}.dynsyms" "${outfile}.funcsyms" > "${outfile}.keep_symbols"
         echo >> "${outfile}.keep_symbols" # Ensure that the keep_symbols file is not empty.
         "${CROSS_COMPILE}objcopy" --rename-section .debug_frame=saved_debug_frame "${outfile}.debug" "${outfile}.mini_debuginfo"
diff --git a/scripts/toc.sh b/scripts/toc.sh
index bd6425b..8b1d25f 100755
--- a/scripts/toc.sh
+++ b/scripts/toc.sh
@@ -22,6 +22,7 @@
 #   -i ${file}: input file (required)
 #   -o ${file}: output file (required)
 #   -d ${file}: deps file (required)
+#   --elf | --macho | --pe: format (required)
 
 OPTSTRING=d:i:o:-:
 
@@ -36,13 +37,34 @@
 do_elf() {
     ("${CROSS_COMPILE}readelf" -d "${infile}" | grep SONAME || echo "No SONAME for ${infile}") > "${outfile}.tmp"
     "${CROSS_COMPILE}readelf" --dyn-syms "${infile}" | awk '{$2=""; $3=""; print}' >> "${outfile}.tmp"
+
+    cat <<EOF > "${depsfile}"
+${outfile}: \\
+  ${CROSS_COMPILE}readelf \\
+EOF
 }
 
 do_macho() {
     "${CROSS_COMPILE}/otool" -l "${infile}" | grep LC_ID_DYLIB -A 5 > "${outfile}.tmp"
-    "${CROSS_COMPILE}/nm" -gP "${infile}" | cut -f1-2 -d" " | grep -v 'U$' >> "${outfile}.tmp"
+    "${CROSS_COMPILE}/nm" -gP "${infile}" | cut -f1-2 -d" " | (grep -v 'U$' >> "${outfile}.tmp" || true)
+
+    cat <<EOF > "${depsfile}"
+${outfile}: \\
+  ${CROSS_COMPILE}/otool \\
+  ${CROSS_COMPILE}/nm \\
+EOF
 }
 
+do_pe() {
+    "${CROSS_COMPILE}objdump" -x "${infile}" | grep "^Name" | cut -f3 -d" " > "${outfile}.tmp"
+    "${CROSS_COMPILE}nm" -g -f p "${infile}" | cut -f1-2 -d" " >> "${outfile}.tmp"
+
+    cat <<EOF > "${depsfile}"
+${outfile}: \\
+  ${CROSS_COMPILE}objdump \\
+  ${CROSS_COMPILE}nm \\
+EOF
+}
 
 while getopts $OPTSTRING opt; do
     case "$opt" in
@@ -51,6 +73,9 @@
         o) outfile="${OPTARG}" ;;
         -)
             case "${OPTARG}" in
+                elf) elf=1 ;;
+                macho) macho=1 ;;
+                pe) pe=1 ;;
                 *) echo "Unknown option --${OPTARG}"; usage ;;
             esac;;
         ?) usage ;;
@@ -58,21 +83,26 @@
     esac
 done
 
-if [ -z "${infile}" ]; then
+if [ -z "${infile:-}" ]; then
     echo "-i argument is required"
     usage
 fi
 
-if [ -z "${outfile}" ]; then
+if [ -z "${outfile:-}" ]; then
     echo "-o argument is required"
     usage
 fi
 
-if [ -z "${depsfile}" ]; then
+if [ -z "${depsfile:-}" ]; then
     echo "-d argument is required"
     usage
 fi
 
+if [ -z "${CROSS_COMPILE:-}" ]; then
+    echo "CROSS_COMPILE environment variable must be set"
+    usage
+fi
+
 rm -f "${outfile}.tmp"
 
 cat <<EOF > "${depsfile}"
@@ -80,7 +110,15 @@
   ${CROSS_COMPILE}readelf \\
 EOF
 
-do_elf
+if [ -n "${elf:-}" ]; then
+    do_elf
+elif [ -n "${macho:-}" ]; then
+    do_macho
+elif [ -n "${pe:-}" ]; then
+    do_pe
+else
+    echo "--elf, --macho or --pe is required"; usage
+fi
 
 if cmp "${outfile}" "${outfile}.tmp" > /dev/null 2> /dev/null; then
     rm -f "${outfile}.tmp"
diff --git a/ui/build/cleanbuild.go b/ui/build/cleanbuild.go
index a076b66..4dee638 100644
--- a/ui/build/cleanbuild.go
+++ b/ui/build/cleanbuild.go
@@ -102,6 +102,7 @@
 		productOut("skin"),
 		productOut("obj/NOTICE_FILES"),
 		productOut("obj/PACKAGING"),
+		productOut("ramdisk"),
 		productOut("recovery"),
 		productOut("root"),
 		productOut("system"),
diff --git a/ui/build/config.go b/ui/build/config.go
index 2605f5b..fdeb8f2 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -369,14 +369,14 @@
 
 func (c *configImpl) OutDir() string {
 	if outDir, ok := c.environ.Get("OUT_DIR"); ok {
-		return outDir
+		return filepath.Clean(outDir)
 	}
 	return "out"
 }
 
 func (c *configImpl) DistDir() string {
 	if distDir, ok := c.environ.Get("DIST_DIR"); ok {
-		return distDir
+		return filepath.Clean(distDir)
 	}
 	return filepath.Join(c.OutDir(), "dist")
 }
diff --git a/ui/build/dumpvars.go b/ui/build/dumpvars.go
index fadf6c6..ffea841 100644
--- a/ui/build/dumpvars.go
+++ b/ui/build/dumpvars.go
@@ -198,5 +198,5 @@
 
 	config.SetPdkBuild(make_vars["TARGET_BUILD_PDK"] == "true")
 	config.SetBuildBrokenDupRules(make_vars["BUILD_BROKEN_DUP_RULES"] == "true")
-	config.SetBuildBrokenPhonyTargets(make_vars["BUILD_BROKEN_PHONY_TARGETS"] != "false")
+	config.SetBuildBrokenPhonyTargets(make_vars["BUILD_BROKEN_PHONY_TARGETS"] == "true")
 }
diff --git a/ui/build/kati.go b/ui/build/kati.go
index b54872c..b26d673 100644
--- a/ui/build/kati.go
+++ b/ui/build/kati.go
@@ -81,6 +81,8 @@
 		"--warn_real_to_phony",
 		"--warn_phony_looks_real",
 		"--kati_stats",
+		"--writable", config.OutDir() + "/",
+		"--writable", config.DistDir() + "/",
 		"-f", "build/make/core/main.mk",
 	}
 
@@ -94,7 +96,10 @@
 	}
 
 	if !config.BuildBrokenPhonyTargets() {
-		args = append(args, "--werror_real_to_phony", "--werror_phony_looks_real")
+		args = append(args,
+			"--werror_real_to_phony",
+			"--werror_phony_looks_real",
+			"--werror_writable")
 	}
 
 	if !config.Environment().IsFalse("KATI_EMULATE_FIND") {
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index aeefcf2..7886466 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -40,12 +40,13 @@
 }
 
 // The configuration used if the tool is not listed in the config below.
-// Currently this will create the symlink, but log a warning. In the future,
-// I expect this to move closer to Forbidden.
+// Currently this will create the symlink, but log and error when it's used. In
+// the future, I expect the symlink to be removed, and this will be equivalent
+// to Forbidden.
 var Missing = PathConfig{
 	Symlink: true,
 	Log:     true,
-	Error:   false,
+	Error:   true,
 }
 
 func GetConfig(name string) PathConfig {
@@ -77,6 +78,7 @@
 	"env":       Allowed,
 	"expr":      Allowed,
 	"find":      Allowed,
+	"fuser":     Allowed,
 	"getconf":   Allowed,
 	"getopt":    Allowed,
 	"git":       Allowed,
@@ -98,6 +100,7 @@
 	"mkdir":     Allowed,
 	"mktemp":    Allowed,
 	"mv":        Allowed,
+	"od":        Allowed,
 	"openssl":   Allowed,
 	"paste":     Allowed,
 	"patch":     Allowed,
@@ -128,11 +131,14 @@
 	"sum":       Allowed,
 	"tar":       Allowed,
 	"tail":      Allowed,
+	"tee":       Allowed,
+	"todos":     Allowed,
 	"touch":     Allowed,
 	"tr":        Allowed,
 	"true":      Allowed,
 	"uname":     Allowed,
 	"uniq":      Allowed,
+	"unix2dos":  Allowed,
 	"unzip":     Allowed,
 	"wc":        Allowed,
 	"which":     Allowed,
diff --git a/zip/zip.go b/zip/zip.go
index a89fa9f..a8df51e 100644
--- a/zip/zip.go
+++ b/zip/zip.go
@@ -220,14 +220,17 @@
 	}
 	pathMappings := []pathMapping{}
 
+	noCompression := args.CompressionLevel == 0
+
 	for _, fa := range args.FileArgs {
 		srcs := fa.SourceFiles
 		if fa.GlobDir != "" {
 			srcs = append(srcs, recursiveGlobFiles(fa.GlobDir)...)
 		}
 		for _, src := range srcs {
-			if err := fillPathPairs(fa.PathPrefixInZip,
-				fa.SourcePrefixToStrip, src, &pathMappings, args.NonDeflatedFiles); err != nil {
+			err := fillPathPairs(fa.PathPrefixInZip, fa.SourcePrefixToStrip, src,
+				&pathMappings, args.NonDeflatedFiles, noCompression)
+			if err != nil {
 				log.Fatal(err)
 			}
 		}
@@ -267,7 +270,9 @@
 	return nil
 }
 
-func fillPathPairs(prefix, rel, src string, pathMappings *[]pathMapping, nonDeflatedFiles map[string]bool) error {
+func fillPathPairs(prefix, rel, src string, pathMappings *[]pathMapping,
+	nonDeflatedFiles map[string]bool, noCompression bool) error {
+
 	src = strings.TrimSpace(src)
 	if src == "" {
 		return nil
@@ -280,7 +285,7 @@
 	dest = filepath.Join(prefix, dest)
 
 	zipMethod := zip.Deflate
-	if _, found := nonDeflatedFiles[dest]; found {
+	if _, found := nonDeflatedFiles[dest]; found || noCompression {
 		zipMethod = zip.Store
 	}
 	*pathMappings = append(*pathMappings,