Merge "Build transitive lint reports for apex modules"
diff --git a/android/Android.bp b/android/Android.bp
index 6ddcc14..96f0983 100644
--- a/android/Android.bp
+++ b/android/Android.bp
@@ -39,6 +39,7 @@
         "paths.go",
         "phony.go",
         "prebuilt.go",
+        "prebuilt_build_tool.go",
         "proto.go",
         "register.go",
         "rule_builder.go",
diff --git a/android/apex.go b/android/apex.go
index 47f07ca..a7570dc 100644
--- a/android/apex.go
+++ b/android/apex.go
@@ -65,9 +65,9 @@
 
 	apexModuleBase() *ApexModuleBase
 
-	// Marks that this module should be built for the specified APEXes.
+	// Marks that this module should be built for the specified APEX.
 	// Call this before apex.apexMutator is run.
-	BuildForApexes(apexes []ApexInfo)
+	BuildForApex(apex ApexInfo)
 
 	// Returns the APEXes that this module will be built for
 	ApexVariations() []ApexInfo
@@ -96,7 +96,7 @@
 	IsInstallableToApex() bool
 
 	// Mutate this module into one or more variants each of which is built
-	// for an APEX marked via BuildForApexes().
+	// for an APEX marked via BuildForApex().
 	CreateApexVariations(mctx BottomUpMutatorContext) []Module
 
 	// Tests if this module is available for the specified APEX or ":platform"
@@ -178,18 +178,15 @@
 	return nil
 }
 
-func (m *ApexModuleBase) BuildForApexes(apexes []ApexInfo) {
+func (m *ApexModuleBase) BuildForApex(apex ApexInfo) {
 	m.apexVariationsLock.Lock()
 	defer m.apexVariationsLock.Unlock()
-nextApex:
-	for _, apex := range apexes {
-		for _, v := range m.apexVariations {
-			if v.ApexName == apex.ApexName {
-				continue nextApex
-			}
+	for _, v := range m.apexVariations {
+		if v.ApexName == apex.ApexName {
+			return
 		}
-		m.apexVariations = append(m.apexVariations, apex)
 	}
+	m.apexVariations = append(m.apexVariations, apex)
 }
 
 func (m *ApexModuleBase) ApexVariations() []ApexInfo {
@@ -327,17 +324,15 @@
 // depended on by the specified APEXes. Directly depending means that a module
 // is explicitly listed in the build definition of the APEX via properties like
 // native_shared_libs, java_libs, etc.
-func UpdateApexDependency(apexes []ApexInfo, moduleName string, directDep bool) {
+func UpdateApexDependency(apex ApexInfo, moduleName string, directDep bool) {
 	apexNamesMapMutex.Lock()
 	defer apexNamesMapMutex.Unlock()
-	for _, apex := range apexes {
-		apexesForModule, ok := apexNamesMap()[moduleName]
-		if !ok {
-			apexesForModule = make(map[string]bool)
-			apexNamesMap()[moduleName] = apexesForModule
-		}
-		apexesForModule[apex.ApexName] = apexesForModule[apex.ApexName] || directDep
+	apexesForModule, ok := apexNamesMap()[moduleName]
+	if !ok {
+		apexesForModule = make(map[string]bool)
+		apexNamesMap()[moduleName] = apexesForModule
 	}
+	apexesForModule[apex.ApexName] = apexesForModule[apex.ApexName] || directDep
 }
 
 // TODO(b/146393795): remove this when b/146393795 is fixed
diff --git a/android/defs.go b/android/defs.go
index 4552224..83daa03 100644
--- a/android/defs.go
+++ b/android/defs.go
@@ -69,7 +69,7 @@
 	// A symlink rule.
 	Symlink = pctx.AndroidStaticRule("Symlink",
 		blueprint.RuleParams{
-			Command:     "ln -f -s $fromPath $out",
+			Command:     "rm -f $out && ln -f -s $fromPath $out",
 			Description: "symlink $out",
 		},
 		"fromPath")
diff --git a/android/prebuilt_build_tool.go b/android/prebuilt_build_tool.go
new file mode 100644
index 0000000..d457da4
--- /dev/null
+++ b/android/prebuilt_build_tool.go
@@ -0,0 +1,100 @@
+// Copyright 2020 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 android
+
+import (
+	"path"
+	"path/filepath"
+)
+
+func init() {
+	RegisterModuleType("prebuilt_build_tool", prebuiltBuildToolFactory)
+}
+
+type prebuiltBuildToolProperties struct {
+	// Source file to be executed for this build tool
+	Src *string `android:"path,arch_variant"`
+
+	// Extra files that should trigger rules using this tool to rebuild
+	Deps []string `android:"path,arch_variant"`
+}
+
+type prebuiltBuildTool struct {
+	ModuleBase
+	prebuilt Prebuilt
+
+	properties prebuiltBuildToolProperties
+
+	toolPath OptionalPath
+}
+
+func (t *prebuiltBuildTool) Name() string {
+	return t.prebuilt.Name(t.ModuleBase.Name())
+}
+
+func (t *prebuiltBuildTool) Prebuilt() *Prebuilt {
+	return &t.prebuilt
+}
+
+func (t *prebuiltBuildTool) DepsMutator(ctx BottomUpMutatorContext) {
+	if t.properties.Src == nil {
+		ctx.PropertyErrorf("src", "missing prebuilt source file")
+	}
+}
+
+func (t *prebuiltBuildTool) GenerateAndroidBuildActions(ctx ModuleContext) {
+	sourcePath := t.prebuilt.SingleSourcePath(ctx)
+	installedPath := PathForModuleOut(ctx, t.ModuleBase.Name())
+	deps := PathsForModuleSrc(ctx, t.properties.Deps)
+
+	var relPath string
+	if filepath.IsAbs(installedPath.String()) {
+		relPath = filepath.Join(absSrcDir, sourcePath.String())
+	} else {
+		var err error
+		relPath, err = filepath.Rel(path.Dir(installedPath.String()), sourcePath.String())
+		if err != nil {
+			ctx.ModuleErrorf("Unable to generate symlink between %q and %q: %s", installedPath.String(), sourcePath.String(), err)
+		}
+	}
+
+	ctx.Build(pctx, BuildParams{
+		Rule:      Symlink,
+		Output:    installedPath,
+		Input:     sourcePath,
+		Implicits: deps,
+		Args: map[string]string{
+			"fromPath": relPath,
+		},
+	})
+
+	t.toolPath = OptionalPathForPath(installedPath)
+}
+
+func (t *prebuiltBuildTool) HostToolPath() OptionalPath {
+	return t.toolPath
+}
+
+var _ HostToolProvider = &prebuiltBuildTool{}
+
+// prebuilt_build_tool is to declare prebuilts to be used during the build, particularly for use
+// in genrules with the "tools" property.
+func prebuiltBuildToolFactory() Module {
+	module := &prebuiltBuildTool{}
+	module.AddProperties(&module.properties)
+	InitSingleSourcePrebuiltModule(module, &module.properties, "Src")
+	InitAndroidArchModule(module, HostSupportedNoCross, MultilibFirst)
+	return module
+}
diff --git a/android/sdk.go b/android/sdk.go
index 2c38f56..28f5cd5 100644
--- a/android/sdk.go
+++ b/android/sdk.go
@@ -34,10 +34,8 @@
 	RequiredSdks() SdkRefs
 }
 
-// SdkAware is the interface that must be supported by any module to become a member of SDK or to be
-// built with SDK
-type SdkAware interface {
-	Module
+// Provided to improve code navigation with the IDE.
+type sdkAwareWithoutModule interface {
 	RequiredSdks
 
 	sdkBase() *SdkBase
@@ -48,6 +46,13 @@
 	BuildWithSdks(sdks SdkRefs)
 }
 
+// SdkAware is the interface that must be supported by any module to become a member of SDK or to be
+// built with SDK
+type SdkAware interface {
+	Module
+	sdkAwareWithoutModule
+}
+
 // SdkRef refers to a version of an SDK
 type SdkRef struct {
 	Name    string
diff --git a/apex/apex.go b/apex/apex.go
index 7f695b4..fa986cd 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -669,7 +669,7 @@
 }
 
 func RegisterPostDepsMutators(ctx android.RegisterMutatorsContext) {
-	ctx.TopDown("apex_deps", apexDepsMutator)
+	ctx.TopDown("apex_deps", apexDepsMutator).Parallel()
 	ctx.BottomUp("apex", apexMutator).Parallel()
 	ctx.BottomUp("apex_flattened", apexFlattenedMutator).Parallel()
 	ctx.BottomUp("apex_uses", apexUsesMutator).Parallel()
@@ -682,33 +682,30 @@
 	if !mctx.Module().Enabled() {
 		return
 	}
-	var apexBundles []android.ApexInfo
-	var directDep bool
-	if a, ok := mctx.Module().(*apexBundle); ok && !a.vndkApex {
-		apexBundles = []android.ApexInfo{{
-			ApexName:      mctx.ModuleName(),
-			MinSdkVersion: a.minSdkVersion(mctx),
-			Updatable:     a.Updatable(),
-		}}
-		directDep = true
-	} else if am, ok := mctx.Module().(android.ApexModule); ok {
-		apexBundles = am.ApexVariations()
-		directDep = false
-	}
-
-	if len(apexBundles) == 0 {
+	a, ok := mctx.Module().(*apexBundle)
+	if !ok || a.vndkApex {
 		return
 	}
-
-	cur := mctx.Module().(android.DepIsInSameApex)
-
-	mctx.VisitDirectDeps(func(child android.Module) {
-		depName := mctx.OtherModuleName(child)
-		if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() &&
-			(cur.DepIsInSameApex(mctx, child) || inAnySdk(child)) {
-			android.UpdateApexDependency(apexBundles, depName, directDep)
-			am.BuildForApexes(apexBundles)
+	apexInfo := android.ApexInfo{
+		ApexName:      mctx.ModuleName(),
+		MinSdkVersion: a.minSdkVersion(mctx),
+		Updatable:     a.Updatable(),
+	}
+	mctx.WalkDeps(func(child, parent android.Module) bool {
+		am, ok := child.(android.ApexModule)
+		if !ok || !am.CanHaveApexVariants() {
+			return false
 		}
+		if !parent.(android.DepIsInSameApex).DepIsInSameApex(mctx, child) && !inAnySdk(child) {
+			return false
+		}
+
+		depName := mctx.OtherModuleName(child)
+		// If the parent is apexBundle, this child is directly depended.
+		_, directDep := parent.(*apexBundle)
+		android.UpdateApexDependency(apexInfo, depName, directDep)
+		am.BuildForApex(apexInfo)
+		return true
 	})
 }
 
diff --git a/cc/cc.go b/cc/cc.go
index fdf2879..bea851f 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -116,6 +116,8 @@
 	// Used for host bionic
 	LinkerFlagsFile string
 	DynamicLinker   string
+
+	Tools []string
 }
 
 type PathDeps struct {
@@ -158,6 +160,8 @@
 
 	// Path to the dynamic linker binary
 	DynamicLinker android.OptionalPath
+
+	Tools map[string]android.Path
 }
 
 // LocalOrGlobalFlags contains flags that need to have values set globally by the build system or locally by the module
@@ -425,6 +429,12 @@
 	XrefCcFiles() android.Paths
 }
 
+type ToolDependencyTag struct {
+	blueprint.BaseDependencyTag
+
+	Name string
+}
+
 var (
 	dataLibDepTag         = DependencyTag{Name: "data_lib", Library: true, Shared: true}
 	sharedExportDepTag    = DependencyTag{Name: "shared", Library: true, Shared: true, ReexportFlags: true}
@@ -1694,6 +1704,7 @@
 	deps.LateSharedLibs = android.LastUniqueStrings(deps.LateSharedLibs)
 	deps.HeaderLibs = android.LastUniqueStrings(deps.HeaderLibs)
 	deps.RuntimeLibs = android.LastUniqueStrings(deps.RuntimeLibs)
+	deps.Tools = android.LastUniqueStrings(deps.Tools)
 
 	for _, lib := range deps.ReexportSharedLibHeaders {
 		if !inList(lib, deps.SharedLibs) {
@@ -2037,6 +2048,11 @@
 			}, vndkExtDepTag, vndkdep.getVndkExtendsModuleName())
 		}
 	}
+
+	for _, tool := range deps.Tools {
+		actx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(),
+			ToolDependencyTag{Name: tool}, tool)
+	}
 }
 
 func BeginMutator(ctx android.BottomUpMutatorContext) {
@@ -2215,10 +2231,38 @@
 		depPaths.ReexportedGeneratedHeaders = append(depPaths.ReexportedGeneratedHeaders, exporter.exportedGeneratedHeaders()...)
 	}
 
+	// For the dependency from platform to apex, use the latest stubs
+	c.apexSdkVersion = android.FutureApiLevel
+	if !c.IsForPlatform() {
+		c.apexSdkVersion = c.ApexProperties.Info.MinSdkVersion
+	}
+
+	if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
+		// In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
+		// so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
+		// (b/144430859)
+		c.apexSdkVersion = android.FutureApiLevel
+	}
+
 	ctx.VisitDirectDeps(func(dep android.Module) {
 		depName := ctx.OtherModuleName(dep)
 		depTag := ctx.OtherModuleDependencyTag(dep)
 
+		if toolDep, ok := depTag.(ToolDependencyTag); ok {
+			if toolMod, ok := dep.(android.HostToolProvider); ok {
+				if depPaths.Tools == nil {
+					depPaths.Tools = make(map[string]android.Path)
+				}
+				toolPath := toolMod.HostToolPath()
+				if !toolPath.Valid() {
+					ctx.ModuleErrorf("Failed to find path for host tool %q", toolDep.Name)
+				}
+				depPaths.Tools[toolDep.Name] = toolPath.Path()
+			} else {
+				ctx.ModuleErrorf("Found module, but not host tool for %q", toolDep.Name)
+			}
+		}
+
 		ccDep, ok := dep.(LinkableInterface)
 		if !ok {
 
@@ -2303,19 +2347,6 @@
 			}
 		}
 
-		// For the dependency from platform to apex, use the latest stubs
-		c.apexSdkVersion = android.FutureApiLevel
-		if !c.IsForPlatform() {
-			c.apexSdkVersion = c.ApexProperties.Info.MinSdkVersion
-		}
-
-		if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
-			// In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
-			// so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
-			// (b/144430859)
-			c.apexSdkVersion = android.FutureApiLevel
-		}
-
 		if depTag == staticUnwinderDepTag {
 			// Use static unwinder for legacy (min_sdk_version = 29) apexes (b/144430859)
 			if c.apexSdkVersion <= android.SdkVersion_Android10 {
diff --git a/cc/compiler.go b/cc/compiler.go
index d5ea2c3..ba14dd5 100644
--- a/cc/compiler.go
+++ b/cc/compiler.go
@@ -251,6 +251,14 @@
 		deps.StaticLibs = append(deps.StaticLibs, "libomp")
 	}
 
+	if compiler.hasSrcExt(".y") || compiler.hasSrcExt(".yy") {
+		deps.Tools = append(deps.Tools, "bison", "m4")
+	}
+
+	if compiler.hasSrcExt(".l") || compiler.hasSrcExt(".ll") {
+		deps.Tools = append(deps.Tools, "flex", "m4")
+	}
+
 	return deps
 }
 
@@ -581,7 +589,7 @@
 
 	srcs := append(android.Paths(nil), compiler.srcsBeforeGen...)
 
-	srcs, genDeps := genSources(ctx, srcs, buildFlags)
+	srcs, genDeps := genSources(ctx, srcs, buildFlags, deps.Tools)
 	pathDeps = append(pathDeps, genDeps...)
 
 	compiler.pathDeps = pathDeps
diff --git a/cc/gen.go b/cc/gen.go
index b0aadc6..6f9036b 100644
--- a/cc/gen.go
+++ b/cc/gen.go
@@ -24,7 +24,6 @@
 )
 
 func init() {
-	pctx.SourcePathVariable("lexCmd", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/flex")
 	pctx.SourcePathVariable("m4Cmd", "prebuilts/build-tools/${config.HostPrebuiltTag}/bin/m4")
 
 	pctx.HostBinToolVariable("aidlCmd", "aidl-cpp")
@@ -32,12 +31,6 @@
 }
 
 var (
-	lex = pctx.AndroidStaticRule("lex",
-		blueprint.RuleParams{
-			Command:     "M4=$m4Cmd $lexCmd -o$out $in",
-			CommandDeps: []string{"$lexCmd", "$m4Cmd"},
-		})
-
 	sysprop = pctx.AndroidStaticRule("sysprop",
 		blueprint.RuleParams{
 			Command: "$syspropCmd --header-dir=$headerOutDir --public-header-dir=$publicOutDir " +
@@ -66,7 +59,8 @@
 }
 
 func genYacc(ctx android.ModuleContext, rule *android.RuleBuilder, yaccFile android.Path,
-	outFile android.ModuleGenPath, props *YaccProperties) (headerFiles android.Paths) {
+	outFile android.ModuleGenPath, props *YaccProperties,
+	tools map[string]android.Path) (headerFiles android.Paths) {
 
 	outDir := android.PathForModuleGen(ctx, "yacc")
 	headerFile := android.GenPathWithExt(ctx, "yacc", yaccFile, "h")
@@ -97,9 +91,17 @@
 		}
 	}
 
-	cmd.Text("BISON_PKGDATADIR=prebuilts/build-tools/common/bison").
-		FlagWithInput("M4=", ctx.Config().PrebuiltBuildTool(ctx, "m4")).
-		PrebuiltBuildTool(ctx, "bison").
+	bison, ok := tools["bison"]
+	if !ok {
+		ctx.ModuleErrorf("Unable to find bison")
+	}
+	m4, ok := tools["m4"]
+	if !ok {
+		ctx.ModuleErrorf("Unable to find m4")
+	}
+
+	cmd.FlagWithInput("M4=", m4).
+		Tool(bison).
 		Flag("-d").
 		Flags(flags).
 		FlagWithOutput("--defines=", headerFile).
@@ -153,13 +155,23 @@
 	}
 }
 
-func genLex(ctx android.ModuleContext, lexFile android.Path, outFile android.ModuleGenPath) {
-	ctx.Build(pctx, android.BuildParams{
-		Rule:        lex,
-		Description: "lex " + lexFile.Rel(),
-		Output:      outFile,
-		Input:       lexFile,
-	})
+func genLex(ctx android.ModuleContext, rule *android.RuleBuilder, lexFile android.Path,
+	outFile android.ModuleGenPath, tools map[string]android.Path) {
+
+	flex, ok := tools["flex"]
+	if !ok {
+		ctx.ModuleErrorf("Unable to find flex")
+	}
+	m4, ok := tools["m4"]
+	if !ok {
+		ctx.ModuleErrorf("Unable to find m4")
+	}
+
+	rule.Command().
+		FlagWithInput("M4=", m4).
+		Tool(flex).
+		FlagWithOutput("-o", outFile).
+		Input(lexFile)
 }
 
 func genSysprop(ctx android.ModuleContext, syspropFile android.Path) (android.Path, android.Paths) {
@@ -206,14 +218,22 @@
 	return rcFile, headerFile
 }
 
-func genSources(ctx android.ModuleContext, srcFiles android.Paths,
-	buildFlags builderFlags) (android.Paths, android.Paths) {
+func genSources(ctx android.ModuleContext, srcFiles android.Paths, buildFlags builderFlags,
+	tools map[string]android.Path) (android.Paths, android.Paths) {
 
 	var deps android.Paths
 	var rsFiles android.Paths
 
 	var aidlRule *android.RuleBuilder
 
+	var lexRule_ *android.RuleBuilder
+	lexRule := func() *android.RuleBuilder {
+		if lexRule_ == nil {
+			lexRule_ = android.NewRuleBuilder().Sbox(android.PathForModuleGen(ctx, "lex"))
+		}
+		return lexRule_
+	}
+
 	var yaccRule_ *android.RuleBuilder
 	yaccRule := func() *android.RuleBuilder {
 		if yaccRule_ == nil {
@@ -227,19 +247,19 @@
 		case ".y":
 			cFile := android.GenPathWithExt(ctx, "yacc", srcFile, "c")
 			srcFiles[i] = cFile
-			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cFile, buildFlags.yacc)...)
+			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cFile, buildFlags.yacc, tools)...)
 		case ".yy":
 			cppFile := android.GenPathWithExt(ctx, "yacc", srcFile, "cpp")
 			srcFiles[i] = cppFile
-			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cppFile, buildFlags.yacc)...)
+			deps = append(deps, genYacc(ctx, yaccRule(), srcFile, cppFile, buildFlags.yacc, tools)...)
 		case ".l":
 			cFile := android.GenPathWithExt(ctx, "lex", srcFile, "c")
 			srcFiles[i] = cFile
-			genLex(ctx, srcFile, cFile)
+			genLex(ctx, lexRule(), srcFile, cFile, tools)
 		case ".ll":
 			cppFile := android.GenPathWithExt(ctx, "lex", srcFile, "cpp")
 			srcFiles[i] = cppFile
-			genLex(ctx, srcFile, cppFile)
+			genLex(ctx, lexRule(), srcFile, cppFile, tools)
 		case ".proto":
 			ccFile, headerFile := genProto(ctx, srcFile, buildFlags)
 			srcFiles[i] = ccFile
@@ -271,6 +291,10 @@
 		aidlRule.Build(pctx, ctx, "aidl", "gen aidl")
 	}
 
+	if lexRule_ != nil {
+		lexRule_.Build(pctx, ctx, "lex", "gen lex")
+	}
+
 	if yaccRule_ != nil {
 		yaccRule_.Build(pctx, ctx, "yacc", "gen yacc")
 	}
diff --git a/java/Android.bp b/java/Android.bp
index 1fda7f7..fd06c46 100644
--- a/java/Android.bp
+++ b/java/Android.bp
@@ -38,6 +38,7 @@
         "java_resources.go",
         "kotlin.go",
         "lint.go",
+        "legacy_core_platform_api_usage.go",
         "platform_compat_config.go",
         "plugin.go",
         "prebuilt_apis.go",
diff --git a/java/config/config.go b/java/config/config.go
index 0fe74c8..d2f4513 100644
--- a/java/config/config.go
+++ b/java/config/config.go
@@ -30,6 +30,8 @@
 
 	LegacyCorePlatformBootclasspathLibraries = []string{"legacy.core.platform.api.stubs", "core-lambda-stubs"}
 	LegacyCorePlatformSystemModules          = "legacy-core-platform-api-stubs-system-modules"
+	StableCorePlatformBootclasspathLibraries = []string{"stable.core.platform.api.stubs", "core-lambda-stubs"}
+	StableCorePlatformSystemModules          = "stable-core-platform-api-stubs-system-modules"
 	FrameworkLibraries                       = []string{"ext", "framework"}
 	DefaultLambdaStubsLibrary                = "core-lambda-stubs"
 	SdkLambdaStubsPath                       = "prebuilts/sdk/tools/core-lambda-stubs.jar"
diff --git a/java/legacy_core_platform_api_usage.go b/java/legacy_core_platform_api_usage.go
new file mode 100644
index 0000000..8af66d0
--- /dev/null
+++ b/java/legacy_core_platform_api_usage.go
@@ -0,0 +1,162 @@
+// Copyright 2020 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 java
+
+import (
+	"android/soong/android"
+	"android/soong/java/config"
+)
+
+var legacyCorePlatformApiModules = []string{
+	"ahat-test-dump",
+	"android.car",
+	"android.test.mock",
+	"android.test.mock.impl",
+	"AoapTestDeviceApp",
+	"AoapTestHostApp",
+	"api-stubs-docs",
+	"art_cts_jvmti_test_library",
+	"art-gtest-jars-MyClassNatives",
+	"BackupFrameworksServicesRoboTests",
+	"BandwidthEnforcementTest",
+	"BlockedNumberProvider",
+	"BluetoothInstrumentationTests",
+	"BluetoothMidiService",
+	"car-apps-common",
+	"CertInstaller",
+	"ConnectivityManagerTest",
+	"ContactsProvider",
+	"core-tests-support",
+	"CtsContentTestCases",
+	"CtsIkeTestCases",
+	"CtsLibcoreWycheproofBCTestCases",
+	"CtsMediaTestCases",
+	"CtsNetTestCases",
+	"CtsNetTestCasesLatestSdk",
+	"CtsSecurityTestCases",
+	"CtsUsageStatsTestCases",
+	"DisplayCutoutEmulationEmu01Overlay",
+	"DocumentsUIPerfTests",
+	"DocumentsUITests",
+	"DownloadProvider",
+	"DownloadProviderTests",
+	"DownloadProviderUi",
+	"DynamicSystemInstallationService",
+	"EmergencyInfo-lib",
+	"ethernet-service",
+	"EthernetServiceTests",
+	"ExternalStorageProvider",
+	"ExtServices",
+	"ExtServices-core",
+	"framework-all",
+	"framework-minus-apex",
+	"FrameworksCoreTests",
+	"FrameworksIkeTests",
+	"FrameworksNetCommonTests",
+	"FrameworksNetTests",
+	"FrameworksServicesRoboTests",
+	"FrameworksServicesTests",
+	"FrameworksUtilTests",
+	"hid",
+	"hidl_test_java_java",
+	"hwbinder",
+	"ims",
+	"KeyChain",
+	"ksoap2",
+	"LocalTransport",
+	"lockagent",
+	"mediaframeworktest",
+	"MediaProvider",
+	"MmsService",
+	"MtpDocumentsProvider",
+	"MultiDisplayProvider",
+	"NetworkStackIntegrationTestsLib",
+	"NetworkStackNextIntegrationTests",
+	"NetworkStackNextTests",
+	"NetworkStackTests",
+	"NetworkStackTestsLib",
+	"NfcNci",
+	"platform_library-docs",
+	"PrintSpooler",
+	"RollbackTest",
+	"services",
+	"services.accessibility",
+	"services.backup",
+	"services.core.unboosted",
+	"services.devicepolicy",
+	"services.print",
+	"services.usage",
+	"services.usb",
+	"Settings-core",
+	"SettingsLib",
+	"SettingsProvider",
+	"SettingsProviderTest",
+	"SettingsRoboTests",
+	"Shell",
+	"ShellTests",
+	"sl4a.Common",
+	"StatementService",
+	"SystemUI-core",
+	"SystemUISharedLib",
+	"SystemUI-tests",
+	"Telecom",
+	"TelecomUnitTests",
+	"telephony-common",
+	"TelephonyProvider",
+	"TelephonyProviderTests",
+	"TeleService",
+	"testables",
+	"TetheringTests",
+	"TetheringTestsLib",
+	"time_zone_distro_installer",
+	"time_zone_distro_installer-tests",
+	"time_zone_distro-tests",
+	"time_zone_updater",
+	"TvProvider",
+	"uiautomator-stubs-docs",
+	"UsbHostExternalManagementTestApp",
+	"UserDictionaryProvider",
+	"WallpaperBackup",
+	"wifi-service",
+}
+
+var legacyCorePlatformApiLookup = make(map[string]struct{})
+
+func init() {
+	for _, module := range legacyCorePlatformApiModules {
+		legacyCorePlatformApiLookup[module] = struct{}{}
+	}
+}
+
+func useLegacyCorePlatformApi(ctx android.EarlyModuleContext) bool {
+	_, found := legacyCorePlatformApiLookup[ctx.ModuleName()]
+	return found
+}
+
+func corePlatformSystemModules(ctx android.EarlyModuleContext) string {
+	if useLegacyCorePlatformApi(ctx) {
+		return config.LegacyCorePlatformSystemModules
+	} else {
+		return config.StableCorePlatformSystemModules
+	}
+}
+
+func corePlatformBootclasspathLibraries(ctx android.EarlyModuleContext) []string {
+	if useLegacyCorePlatformApi(ctx) {
+		return config.LegacyCorePlatformBootclasspathLibraries
+	} else {
+		return config.StableCorePlatformBootclasspathLibraries
+	}
+}
diff --git a/java/sdk.go b/java/sdk.go
index 6564f6d..6e67a13 100644
--- a/java/sdk.go
+++ b/java/sdk.go
@@ -413,8 +413,8 @@
 	case sdkPrivate:
 		return sdkDep{
 			useModule:          true,
-			systemModules:      config.LegacyCorePlatformSystemModules,
-			bootclasspath:      config.LegacyCorePlatformBootclasspathLibraries,
+			systemModules:      corePlatformSystemModules(ctx),
+			bootclasspath:      corePlatformBootclasspathLibraries(ctx),
 			classpath:          config.FrameworkLibraries,
 			frameworkResModule: "framework-res",
 		}
@@ -438,8 +438,8 @@
 	case sdkCorePlatform:
 		return sdkDep{
 			useModule:        true,
-			systemModules:    config.LegacyCorePlatformSystemModules,
-			bootclasspath:    config.LegacyCorePlatformBootclasspathLibraries,
+			systemModules:    corePlatformSystemModules(ctx),
+			bootclasspath:    corePlatformBootclasspathLibraries(ctx),
 			noFrameworksLibs: true,
 		}
 	case sdkPublic:
diff --git a/java/sdk_test.go b/java/sdk_test.go
index 1f23b14..395da79 100644
--- a/java/sdk_test.go
+++ b/java/sdk_test.go
@@ -49,8 +49,8 @@
 	}{
 		{
 			name:           "default",
-			bootclasspath:  config.LegacyCorePlatformBootclasspathLibraries,
-			system:         config.LegacyCorePlatformSystemModules,
+			bootclasspath:  config.StableCorePlatformBootclasspathLibraries,
+			system:         config.StableCorePlatformSystemModules,
 			java8classpath: config.FrameworkLibraries,
 			java9classpath: config.FrameworkLibraries,
 			aidl:           "-Iframework/aidl",
@@ -58,16 +58,16 @@
 		{
 			name:           `sdk_version:"core_platform"`,
 			properties:     `sdk_version:"core_platform"`,
-			bootclasspath:  config.LegacyCorePlatformBootclasspathLibraries,
-			system:         config.LegacyCorePlatformSystemModules,
+			bootclasspath:  config.StableCorePlatformBootclasspathLibraries,
+			system:         config.StableCorePlatformSystemModules,
 			java8classpath: []string{},
 			aidl:           "",
 		},
 		{
 			name:           "blank sdk version",
 			properties:     `sdk_version: "",`,
-			bootclasspath:  config.LegacyCorePlatformBootclasspathLibraries,
-			system:         config.LegacyCorePlatformSystemModules,
+			bootclasspath:  config.StableCorePlatformBootclasspathLibraries,
+			system:         config.StableCorePlatformSystemModules,
 			java8classpath: config.FrameworkLibraries,
 			java9classpath: config.FrameworkLibraries,
 			aidl:           "-Iframework/aidl",
@@ -155,9 +155,9 @@
 		{
 
 			name:           "nostdlib system_modules",
-			properties:     `sdk_version: "none", system_modules: "legacy-core-platform-api-stubs-system-modules"`,
-			system:         "legacy-core-platform-api-stubs-system-modules",
-			bootclasspath:  []string{"legacy-core-platform-api-stubs-system-modules-lib"},
+			properties:     `sdk_version: "none", system_modules: "stable-core-platform-api-stubs-system-modules"`,
+			system:         "stable-core-platform-api-stubs-system-modules",
+			bootclasspath:  []string{"stable-core-platform-api-stubs-system-modules-lib"},
 			java8classpath: []string{},
 		},
 		{
diff --git a/java/testing.go b/java/testing.go
index 94f054e..e761743 100644
--- a/java/testing.go
+++ b/java/testing.go
@@ -136,7 +136,7 @@
 				name: "%s",
 				srcs: ["a.java"],
 				sdk_version: "none",
-				system_modules: "legacy-core-platform-api-stubs-system-modules",
+				system_modules: "stable-core-platform-api-stubs-system-modules",
 			}
 		`, extra)
 	}
@@ -146,7 +146,7 @@
 			name: "framework",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			aidl: {
 				export_include_dirs: ["framework/aidl"],
 			},
@@ -161,7 +161,7 @@
 			name: "android.hidl.base-V1.0-java",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			installable: true,
 		}
 
@@ -169,7 +169,7 @@
 			name: "android.hidl.manager-V1.0-java",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			installable: true,
 		}
 
@@ -177,7 +177,7 @@
 			name: "org.apache.http.legacy",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			installable: true,
 		}
 
@@ -185,7 +185,7 @@
 			name: "android.test.base",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			installable: true,
 		}
   
@@ -193,7 +193,7 @@
 			name: "android.test.mock",
 			srcs: ["a.java"],
 			sdk_version: "none",
-			system_modules: "legacy-core-platform-api-stubs-system-modules",
+			system_modules: "stable-core-platform-api-stubs-system-modules",
 			installable: true,
 		}
 	`
diff --git a/rust/bindgen.go b/rust/bindgen.go
index 0f657ef..132b1fd 100644
--- a/rust/bindgen.go
+++ b/rust/bindgen.go
@@ -24,7 +24,7 @@
 )
 
 var (
-	defaultBindgenFlags = []string{"--no-rustfmt-bindings"}
+	defaultBindgenFlags = []string{""}
 
 	// bindgen should specify its own Clang revision so updating Clang isn't potentially blocked on bindgen failures.
 	bindgenClangVersion  = "clang-r383902c"
@@ -40,7 +40,8 @@
 	//TODO(ivanlozano) Switch this to RuleBuilder
 	bindgen = pctx.AndroidStaticRule("bindgen",
 		blueprint.RuleParams{
-			Command:     "CLANG_PATH=$bindgenClang LIBCLANG_PATH=$bindgenLibClang $bindgenCmd $flags $in -o $out -- $cflags",
+			Command: "CLANG_PATH=$bindgenClang LIBCLANG_PATH=$bindgenLibClang RUSTFMT=${config.RustBin}/rustfmt " +
+				"$bindgenCmd $flags $in -o $out -- $cflags",
 			CommandDeps: []string{"$bindgenCmd"},
 		},
 		"flags", "cflags")
diff --git a/sdk/java_sdk_test.go b/sdk/java_sdk_test.go
index 6fefc28..a2198e9 100644
--- a/sdk/java_sdk_test.go
+++ b/sdk/java_sdk_test.go
@@ -51,10 +51,10 @@
 	name: "core-current-stubs-system-modules",
 }
 java_system_modules_import {
-	name: "legacy-core-platform-api-stubs-system-modules",
+	name: "stable-core-platform-api-stubs-system-modules",
 }
 java_import {
-	name: "legacy.core.platform.api.stubs",
+	name: "stable.core.platform.api.stubs",
 }
 java_import {
 	name: "android_stubs_current",