Merge "ShouldKeepExistingBuldFileForDir look up by dir"
diff --git a/android/allowlists/allowlists.go b/android/allowlists/allowlists.go
index b82ea4f..bf39404 100644
--- a/android/allowlists/allowlists.go
+++ b/android/allowlists/allowlists.go
@@ -650,6 +650,10 @@
 		"libcodec2_soft_avcenc",
 		"libcodec2_soft_aacdec",
 		"libcodec2_soft_common",
+
+		// kotlin srcs in java libs
+		"CtsPkgInstallerConstants",
+		"kotlinx_atomicfu",
 	}
 
 	Bp2buildModuleTypeAlwaysConvertList = []string{
diff --git a/android/bazel_handler.go b/android/bazel_handler.go
index eec78d2..e2751d6 100644
--- a/android/bazel_handler.go
+++ b/android/bazel_handler.go
@@ -150,8 +150,9 @@
 	// ** end Cquery Results Retrieval Functions
 
 	// Issues commands to Bazel to receive results for all cquery requests
-	// queued in the BazelContext.
-	InvokeBazel(config Config) error
+	// queued in the BazelContext. The ctx argument is optional and is only
+	// used for performance data collection
+	InvokeBazel(config Config, ctx *Context) error
 
 	// Returns true if Bazel handling is enabled for the module with the given name.
 	// Note that this only implies "bazel mixed build" allowlisting. The caller
@@ -259,7 +260,7 @@
 	return result, nil
 }
 
-func (m MockBazelContext) InvokeBazel(_ Config) error {
+func (m MockBazelContext) InvokeBazel(_ Config, ctx *Context) error {
 	panic("unimplemented")
 }
 
@@ -355,7 +356,7 @@
 	panic("implement me")
 }
 
-func (n noopBazelContext) InvokeBazel(_ Config) error {
+func (n noopBazelContext) InvokeBazel(_ Config, ctx *Context) error {
 	panic("unimplemented")
 }
 
@@ -865,51 +866,78 @@
 	return filepath.Dir(p.soongOutDir)
 }
 
+const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
+
+var (
+	cqueryCmd = bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
+	aqueryCmd = bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
+	buildCmd  = bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
+)
+
 // Issues commands to Bazel to receive results for all cquery requests
 // queued in the BazelContext.
-func (context *bazelContext) InvokeBazel(config Config) error {
+func (context *bazelContext) InvokeBazel(config Config, ctx *Context) error {
+	if ctx != nil {
+		ctx.EventHandler.Begin("bazel")
+		defer ctx.EventHandler.End("bazel")
+	}
+
+	if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
+		if err := os.MkdirAll(metricsDir, 0777); err != nil {
+			return err
+		}
+	}
 	context.results = make(map[cqueryKey]string)
+	if err := context.runCquery(ctx); err != nil {
+		return err
+	}
+	if err := context.runAquery(config, ctx); err != nil {
+		return err
+	}
+	if err := context.generateBazelSymlinks(ctx); err != nil {
+		return err
+	}
 
-	var err error
+	// Clear requests.
+	context.requests = map[cqueryKey]bool{}
+	return nil
+}
 
+func (context *bazelContext) runCquery(ctx *Context) error {
+	if ctx != nil {
+		ctx.EventHandler.Begin("cquery")
+		defer ctx.EventHandler.End("cquery")
+	}
 	soongInjectionPath := absolutePath(context.paths.injectedFilesDir())
 	mixedBuildsPath := filepath.Join(soongInjectionPath, "mixed_builds")
 	if _, err := os.Stat(mixedBuildsPath); os.IsNotExist(err) {
 		err = os.MkdirAll(mixedBuildsPath, 0777)
-	}
-	if err != nil {
-		return err
-	}
-	if metricsDir := context.paths.BazelMetricsDir(); metricsDir != "" {
-		err = os.MkdirAll(metricsDir, 0777)
 		if err != nil {
 			return err
 		}
 	}
-	if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
+	if err := ioutil.WriteFile(filepath.Join(soongInjectionPath, "WORKSPACE.bazel"), []byte{}, 0666); err != nil {
 		return err
 	}
-	if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
+	if err := ioutil.WriteFile(filepath.Join(mixedBuildsPath, "main.bzl"), context.mainBzlFileContents(), 0666); err != nil {
 		return err
 	}
-	if err = ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
+	if err := ioutil.WriteFile(filepath.Join(mixedBuildsPath, "BUILD.bazel"), context.mainBuildFileContents(), 0666); err != nil {
 		return err
 	}
 	cqueryFileRelpath := filepath.Join(context.paths.injectedFilesDir(), "buildroot.cquery")
-	if err = ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
+	if err := ioutil.WriteFile(absolutePath(cqueryFileRelpath), context.cqueryStarlarkFileContents(), 0666); err != nil {
 		return err
 	}
 
-	const buildrootLabel = "@soong_injection//mixed_builds:buildroot"
-	cqueryCmd := bazelCommand{"cquery", fmt.Sprintf("deps(%s, 2)", buildrootLabel)}
 	cqueryCommandWithFlag := context.createBazelCommand(context.paths, bazel.CqueryBuildRootRunName, cqueryCmd,
 		"--output=starlark", "--starlark:file="+absolutePath(cqueryFileRelpath))
-	cqueryOutput, cqueryErr, err := context.issueBazelCommand(cqueryCommandWithFlag)
-	if err != nil {
-		return err
+	cqueryOutput, cqueryErrorMessage, cqueryErr := context.issueBazelCommand(cqueryCommandWithFlag)
+	if cqueryErr != nil {
+		return cqueryErr
 	}
 	cqueryCommandPrint := fmt.Sprintf("cquery command line:\n  %s \n\n\n", printableCqueryCommand(cqueryCommandWithFlag))
-	if err = ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
+	if err := ioutil.WriteFile(filepath.Join(soongInjectionPath, "cquery.out"), []byte(cqueryCommandPrint+cqueryOutput), 0666); err != nil {
 		return err
 	}
 	cqueryResults := map[string]string{}
@@ -924,10 +952,17 @@
 			context.results[val] = cqueryResult
 		} else {
 			return fmt.Errorf("missing result for bazel target %s. query output: [%s], cquery err: [%s]",
-				getCqueryId(val), cqueryOutput, cqueryErr)
+				getCqueryId(val), cqueryOutput, cqueryErrorMessage)
 		}
 	}
+	return nil
+}
 
+func (context *bazelContext) runAquery(config Config, ctx *Context) error {
+	if ctx != nil {
+		ctx.EventHandler.Begin("aquery")
+		defer ctx.EventHandler.End("aquery")
+	}
 	// Issue an aquery command to retrieve action information about the bazel build tree.
 	//
 	// Use jsonproto instead of proto; actual proto parsing would require a dependency on Bazel's
@@ -937,6 +972,12 @@
 		extraFlags = append(extraFlags, "--collect_code_coverage")
 		paths := make([]string, 0, 2)
 		if p := config.productVariables.NativeCoveragePaths; len(p) > 0 {
+			for i, _ := range p {
+				// TODO(b/259404593) convert path wildcard to regex values
+				if p[i] == "*" {
+					p[i] = ".*"
+				}
+			}
 			paths = append(paths, JoinWithPrefixAndSeparator(p, "+", ","))
 		}
 		if p := config.productVariables.NativeCoverageExcludePaths; len(p) > 0 {
@@ -946,26 +987,25 @@
 			extraFlags = append(extraFlags, "--instrumentation_filter="+strings.Join(paths, ","))
 		}
 	}
-	aqueryCmd := bazelCommand{"aquery", fmt.Sprintf("deps(%s)", buildrootLabel)}
-	if aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
-		extraFlags...)); err == nil {
-		context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
-	}
+	aqueryOutput, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.AqueryBuildRootRunName, aqueryCmd,
+		extraFlags...))
 	if err != nil {
 		return err
 	}
+	context.buildStatements, context.depsets, err = bazel.AqueryBuildStatements([]byte(aqueryOutput))
+	return err
+}
 
+func (context *bazelContext) generateBazelSymlinks(ctx *Context) error {
+	if ctx != nil {
+		ctx.EventHandler.Begin("symlinks")
+		defer ctx.EventHandler.End("symlinks")
+	}
 	// Issue a build command of the phony root to generate symlink forests for dependencies of the
 	// Bazel build. This is necessary because aquery invocations do not generate this symlink forest,
 	// but some of symlinks may be required to resolve source dependencies of the build.
-	buildCmd := bazelCommand{"build", "@soong_injection//mixed_builds:phonyroot"}
-	if _, _, err = context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd)); err != nil {
-		return err
-	}
-
-	// Clear requests.
-	context.requests = map[cqueryKey]bool{}
-	return nil
+	_, _, err := context.issueBazelCommand(context.createBazelCommand(context.paths, bazel.BazelBuildPhonyRootRunName, buildCmd))
+	return err
 }
 
 func (context *bazelContext) BuildStatementsToRegister() []bazel.BuildStatement {
diff --git a/android/bazel_handler_test.go b/android/bazel_handler_test.go
index 6e3acd5..bc16cb5 100644
--- a/android/bazel_handler_test.go
+++ b/android/bazel_handler_test.go
@@ -23,7 +23,7 @@
 		bazelCommand{command: "cquery", expression: "deps(@soong_injection//mixed_builds:buildroot, 2)"}: `@//foo:bar|arm64_armv8-a|android>>out/foo/bar.txt`,
 	})
 	bazelContext.QueueBazelRequest(label, cquery.GetOutputFiles, cfg)
-	err := bazelContext.InvokeBazel(testConfig)
+	err := bazelContext.InvokeBazel(testConfig, nil)
 	if err != nil {
 		t.Fatalf("Did not expect error invoking Bazel, but got %s", err)
 	}
@@ -37,7 +37,7 @@
 
 func TestInvokeBazelWritesBazelFiles(t *testing.T) {
 	bazelContext, baseDir := testBazelContext(t, map[bazelCommand]string{})
-	err := bazelContext.InvokeBazel(testConfig)
+	err := bazelContext.InvokeBazel(testConfig, nil)
 	if err != nil {
 		t.Fatalf("Did not expect error invoking Bazel, but got %s", err)
 	}
@@ -118,7 +118,7 @@
 		bazelContext, _ := testBazelContext(t, map[bazelCommand]string{
 			bazelCommand{command: "aquery", expression: "deps(@soong_injection//mixed_builds:buildroot)"}: string(data)})
 
-		err = bazelContext.InvokeBazel(testConfig)
+		err = bazelContext.InvokeBazel(testConfig, nil)
 		if err != nil {
 			t.Fatalf("testCase #%d: did not expect error invoking Bazel, but got %s", i+1, err)
 		}
@@ -155,6 +155,10 @@
 	testConfig.productVariables.NativeCoverageExcludePaths = []string{"bar1"}
 	verifyExtraFlags(t, testConfig, `--collect_code_coverage --instrumentation_filter=-bar1`)
 
+	testConfig.productVariables.NativeCoveragePaths = []string{"*"}
+	testConfig.productVariables.NativeCoverageExcludePaths = nil
+	verifyExtraFlags(t, testConfig, `--collect_code_coverage --instrumentation_filter=+.*`)
+
 	testConfig.productVariables.ClangCoverage = boolPtr(false)
 	actual := verifyExtraFlags(t, testConfig, ``)
 	if strings.Contains(actual, "--collect_code_coverage") ||
@@ -166,7 +170,7 @@
 func verifyExtraFlags(t *testing.T, config Config, expected string) string {
 	bazelContext, _ := testBazelContext(t, map[bazelCommand]string{})
 
-	err := bazelContext.InvokeBazel(config)
+	err := bazelContext.InvokeBazel(config, nil)
 	if err != nil {
 		t.Fatalf("Did not expect error invoking Bazel, but got %s", err)
 	}
@@ -193,7 +197,7 @@
 	}
 	aqueryCommand := bazelCommand{command: "aquery", expression: "deps(@soong_injection//mixed_builds:buildroot)"}
 	if _, exists := bazelCommandResults[aqueryCommand]; !exists {
-		bazelCommandResults[aqueryCommand] = "{}\n"
+		bazelCommandResults[aqueryCommand] = ""
 	}
 	runner := &mockBazelRunner{bazelCommandResults: bazelCommandResults}
 	return &bazelContext{
diff --git a/android/defs.go b/android/defs.go
index 2a28e98..9ae360e 100644
--- a/android/defs.go
+++ b/android/defs.go
@@ -25,7 +25,8 @@
 )
 
 var (
-	pctx = NewPackageContext("android/soong/android")
+	pctx         = NewPackageContext("android/soong/android")
+	exportedVars = NewExportedVariables(pctx)
 
 	cpPreserveSymlinks = pctx.VariableConfigMethod("cpPreserveSymlinks",
 		Config.CpPreserveSymlinksFlags)
@@ -128,6 +129,13 @@
 	pctx.VariableFunc("RBEWrapper", func(ctx PackageVarContext) string {
 		return ctx.Config().RBEWrapper()
 	})
+
+	exportedVars.ExportStringList("NeverAllowNotInIncludeDir", neverallowNotInIncludeDir)
+	exportedVars.ExportStringList("NeverAllowNoUseIncludeDir", neverallowNoUseIncludeDir)
+}
+
+func BazelCcToolchainVars(config Config) string {
+	return BazelToolchainVars(config, exportedVars)
 }
 
 var (
diff --git a/android/neverallow.go b/android/neverallow.go
index d288439..293bac8 100644
--- a/android/neverallow.go
+++ b/android/neverallow.go
@@ -74,8 +74,8 @@
 			"supported for custom conversion, use allowlists.go instead.")
 }
 
-func createIncludeDirsRules() []Rule {
-	notInIncludeDir := []string{
+var (
+	neverallowNotInIncludeDir = []string{
 		"art",
 		"art/libnativebridge",
 		"art/libnativeloader",
@@ -91,7 +91,7 @@
 		"external/vixl",
 		"external/wycheproof",
 	}
-	noUseIncludeDir := []string{
+	neverallowNoUseIncludeDir = []string{
 		"frameworks/av/apex",
 		"frameworks/av/tools",
 		"frameworks/native/cmds",
@@ -103,10 +103,12 @@
 		"system/libfmq",
 		"system/libvintf",
 	}
+)
 
-	rules := make([]Rule, 0, len(notInIncludeDir)+len(noUseIncludeDir))
+func createIncludeDirsRules() []Rule {
+	rules := make([]Rule, 0, len(neverallowNotInIncludeDir)+len(neverallowNoUseIncludeDir))
 
-	for _, path := range notInIncludeDir {
+	for _, path := range neverallowNotInIncludeDir {
 		rule :=
 			NeverAllow().
 				WithMatcher("include_dirs", StartsWith(path+"/")).
@@ -116,7 +118,7 @@
 		rules = append(rules, rule)
 	}
 
-	for _, path := range noUseIncludeDir {
+	for _, path := range neverallowNoUseIncludeDir {
 		rule := NeverAllow().In(path+"/").WithMatcher("include_dirs", isSetMatcherInstance).
 			Because("include_dirs is deprecated, all usages of them in '" + path + "' have been migrated" +
 				" to use alternate mechanisms and so can no longer be used.")
diff --git a/apex/apex.go b/apex/apex.go
index 09de2d4..04808c1 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -455,9 +455,6 @@
 	// Processed file_contexts files
 	fileContexts android.WritablePath
 
-	// Path to notice file in html.gz format.
-	htmlGzNotice android.WritablePath
-
 	// The built APEX file. This is the main product.
 	// Could be .apex or .capex
 	outputFile android.WritablePath
@@ -1903,9 +1900,6 @@
 	apexType := a.properties.ApexType
 	switch apexType {
 	case imageApex:
-
-		// TODO(b/190817312): Generate the notice file from the apex rule.
-		a.htmlGzNotice = android.PathForBazelOut(ctx, "NOTICE.html.gz")
 		a.bundleModuleFile = android.PathForBazelOut(ctx, outputs.BundleFile)
 		a.nativeApisUsedByModuleFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.SymbolsUsedByApex))
 		a.nativeApisBackedByModuleFile = android.ModuleOutPath(android.PathForBazelOut(ctx, outputs.BackingLibs))
@@ -2508,7 +2502,8 @@
 		filesToAdd = append(filesToAdd, *af)
 	}
 
-	if pathInApex := bootclasspathFragmentInfo.ProfileInstallPathInApex(); pathInApex != "" {
+	pathInApex := bootclasspathFragmentInfo.ProfileInstallPathInApex()
+	if pathInApex != "" && !java.SkipDexpreoptBootJars(ctx) {
 		pathOnHost := bootclasspathFragmentInfo.ProfilePathOnHost()
 		tempPath := android.PathForModuleOut(ctx, "boot_image_profile", pathInApex)
 
diff --git a/apex/builder.go b/apex/builder.go
index e4c1673..9e368b6 100644
--- a/apex/builder.go
+++ b/apex/builder.go
@@ -650,9 +650,9 @@
 		}
 
 		// Create a NOTICE file, and embed it as an asset file in the APEX.
-		a.htmlGzNotice = android.PathForModuleOut(ctx, "NOTICE.html.gz")
+		htmlGzNotice := android.PathForModuleOut(ctx, "NOTICE.html.gz")
 		android.BuildNoticeHtmlOutputFromLicenseMetadata(
-			ctx, a.htmlGzNotice, "", "",
+			ctx, htmlGzNotice, "", "",
 			[]string{
 				android.PathForModuleInstall(ctx).String() + "/",
 				android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
@@ -660,7 +660,7 @@
 		noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
 		builder := android.NewRuleBuilder(pctx, ctx)
 		builder.Command().Text("cp").
-			Input(a.htmlGzNotice).
+			Input(htmlGzNotice).
 			Output(noticeAssetPath)
 		builder.Build("notice_dir", "Building notice dir")
 		implicitInputs = append(implicitInputs, noticeAssetPath)
diff --git a/bp2build/conversion.go b/bp2build/conversion.go
index 8ca13b8..6eb93bc 100644
--- a/bp2build/conversion.go
+++ b/bp2build/conversion.go
@@ -23,6 +23,9 @@
 func CreateSoongInjectionFiles(cfg android.Config, metrics CodegenMetrics) []BazelFile {
 	var files []BazelFile
 
+	files = append(files, newFile("android", GeneratedBuildFileName, "")) // Creates a //cc_toolchain package.
+	files = append(files, newFile("android", "constants.bzl", android.BazelCcToolchainVars(cfg)))
+
 	files = append(files, newFile("cc_toolchain", GeneratedBuildFileName, "")) // Creates a //cc_toolchain package.
 	files = append(files, newFile("cc_toolchain", "constants.bzl", cc_config.BazelCcToolchainVars(cfg)))
 
diff --git a/bp2build/conversion_test.go b/bp2build/conversion_test.go
index cfd6128..8de2f83 100644
--- a/bp2build/conversion_test.go
+++ b/bp2build/conversion_test.go
@@ -88,6 +88,14 @@
 
 	expectedFilePaths := []bazelFilepath{
 		{
+			dir:      "android",
+			basename: GeneratedBuildFileName,
+		},
+		{
+			dir:      "android",
+			basename: "constants.bzl",
+		},
+		{
 			dir:      "cc_toolchain",
 			basename: GeneratedBuildFileName,
 		},
diff --git a/bp2build/java_library_conversion_test.go b/bp2build/java_library_conversion_test.go
index 74e2dbd..00056f8 100644
--- a/bp2build/java_library_conversion_test.go
+++ b/bp2build/java_library_conversion_test.go
@@ -649,3 +649,46 @@
 				}),
 		}})
 }
+
+func TestJavaLibraryKotlinSrcs(t *testing.T) {
+	runJavaLibraryTestCase(t, Bp2buildTestCase{
+		Description: "java_library with kotlin  srcs",
+		Blueprint: `java_library {
+    name: "java-lib-1",
+    srcs: ["a.java", "b.java", "c.kt"],
+    bazel_module: { bp2build_available: true },
+}
+`,
+		ExpectedBazelTargets: []string{
+			MakeBazelTarget("kt_jvm_library", "java-lib-1", AttrNameToString{
+				"srcs": `[
+        "a.java",
+        "b.java",
+        "c.kt",
+    ]`,
+			}),
+		},
+	})
+}
+
+func TestJavaLibraryKotlinCommonSrcs(t *testing.T) {
+	runJavaLibraryTestCase(t, Bp2buildTestCase{
+		Description: "java_library with kotlin  common_srcs",
+		Blueprint: `java_library {
+    name: "java-lib-1",
+    srcs: ["a.java", "b.java"],
+    common_srcs: ["c.kt"],
+    bazel_module: { bp2build_available: true },
+}
+`,
+		ExpectedBazelTargets: []string{
+			MakeBazelTarget("kt_jvm_library", "java-lib-1", AttrNameToString{
+				"srcs": `[
+        "a.java",
+        "b.java",
+    ]`,
+				"common_srcs": `["c.kt"]`,
+			}),
+		},
+	})
+}
diff --git a/cc/config/global.go b/cc/config/global.go
index 9f18784..e5c0a8e 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -292,6 +292,8 @@
 	llvmNextExtraCommonGlobalCflags = []string{
 		// New warnings to be fixed after clang-r475365
 		"-Wno-error=single-bit-bitfield-constant-conversion", // http://b/243965903
+		// Skip deprecated flags.
+		"-Wno-unused-command-line-argument",
 	}
 
 	IllegalFlags = []string{
diff --git a/cc/config/tidy.go b/cc/config/tidy.go
index f32ebf2..1180da4 100644
--- a/cc/config/tidy.go
+++ b/cc/config/tidy.go
@@ -55,6 +55,21 @@
 		// http://b/241819232
 		"-misc-const-correctness",
 	}
+
+	extraArgFlags = []string{
+		// We might be using the static analyzer through clang tidy.
+		// https://bugs.llvm.org/show_bug.cgi?id=32914
+		"-D__clang_analyzer__",
+
+		// A recent change in clang-tidy (r328258) enabled destructor inlining, which
+		// appears to cause a number of false positives. Until that's resolved, this turns
+		// off the effects of r328258.
+		// https://bugs.llvm.org/show_bug.cgi?id=37459
+		"-Xclang",
+		"-analyzer-config",
+		"-Xclang",
+		"c++-temp-dtor-inlining=false",
+	}
 )
 
 func init() {
@@ -145,6 +160,8 @@
 		return strings.Join(globalNoErrorCheckList, ",")
 	})
 
+	exportedVars.ExportStringListStaticVariable("TidyExtraArgFlags", extraArgFlags)
+
 	// To reduce duplicate warnings from the same header files,
 	// header-filter will contain only the module directory and
 	// those specified by DEFAULT_TIDY_HEADER_DIRS.
@@ -235,6 +252,10 @@
 	return ""
 }
 
+func TidyExtraArgFlags() []string {
+	return extraArgFlags
+}
+
 func TidyFlagsForSrcFile(srcFile android.Path, flags string) string {
 	// Disable clang-analyzer-* checks globally for generated source files
 	// because some of them are too huge. Local .bp files can add wanted
diff --git a/cc/library.go b/cc/library.go
index 897f3c7..b639930 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -1875,25 +1875,21 @@
 	}
 }
 
+func currRefAbiDumpVersion(ctx ModuleContext, isVndk bool) string {
+	if isVndk {
+		// Each version of VNDK is independent, so follow the VNDK version which is the codename or PLATFORM_SDK_VERSION.
+		return ctx.Module().(*Module).VndkVersion()
+	} else if ctx.Config().PlatformSdkFinal() {
+		// After sdk finalization, the ABI of the latest API level must be consistent with the source code,
+		// so choose PLATFORM_SDK_VERSION as the current version.
+		return ctx.Config().PlatformSdkVersion().String()
+	} else {
+		return "current"
+	}
+}
+
 func (library *libraryDecorator) linkSAbiDumpFiles(ctx ModuleContext, objs Objects, fileName string, soFile android.Path) {
 	if library.sabi.shouldCreateSourceAbiDump() {
-		var version string
-		var prevVersion int
-
-		if ctx.useVndk() {
-			// For modules linking against vndk, follow its vndk version
-			version = ctx.Module().(*Module).VndkVersion()
-		} else {
-			// After sdk finalizatoin, the ABI of the latest API level must be consistent with the source code
-			// so the chosen reference dump is the PLATFORM_SDK_VERSION.
-			if ctx.Config().PlatformSdkFinal() {
-				version = ctx.Config().PlatformSdkVersion().String()
-			} else {
-				version = "current"
-			}
-			prevVersion = prevDumpRefVersion(ctx)
-		}
-
 		exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
 		var SourceAbiFlags []string
 		for _, dir := range exportIncludeDirs.Strings() {
@@ -1910,10 +1906,12 @@
 
 		addLsdumpPath(classifySourceAbiDump(ctx) + ":" + library.sAbiOutputFile.String())
 
+		isVndk := ctx.useVndk() && ctx.isVndk()
 		isNdk := ctx.isNdk(ctx.Config())
 		isLlndk := ctx.isImplementationForLLNDKPublic()
 		// If NDK or PLATFORM library, check against previous version ABI.
-		if !ctx.useVndk() {
+		if !isVndk {
+			prevVersion := prevDumpRefVersion(ctx)
 			prevRefAbiDumpFile := getRefAbiDumpFile(ctx, strconv.Itoa(prevVersion), fileName)
 			if prevRefAbiDumpFile != nil {
 				library.prevSAbiDiff = sourceAbiDiff(ctx, library.sAbiOutputFile.Path(),
@@ -1924,7 +1922,8 @@
 			}
 		}
 
-		refAbiDumpFile := getRefAbiDumpFile(ctx, version, fileName)
+		currVersion := currRefAbiDumpVersion(ctx, isVndk)
+		refAbiDumpFile := getRefAbiDumpFile(ctx, currVersion, fileName)
 		if refAbiDumpFile != nil {
 			library.sAbiDiff = sourceAbiDiff(ctx, library.sAbiOutputFile.Path(),
 				refAbiDumpFile, fileName,
diff --git a/cc/tidy.go b/cc/tidy.go
index a3d548b..bbcaece 100644
--- a/cc/tidy.go
+++ b/cc/tidy.go
@@ -136,19 +136,7 @@
 		flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before=-fno-caret-diagnostics")
 	}
 
-	extraArgFlags := []string{
-		// We might be using the static analyzer through clang tidy.
-		// https://bugs.llvm.org/show_bug.cgi?id=32914
-		"-D__clang_analyzer__",
-
-		// A recent change in clang-tidy (r328258) enabled destructor inlining, which
-		// appears to cause a number of false positives. Until that's resolved, this turns
-		// off the effects of r328258.
-		// https://bugs.llvm.org/show_bug.cgi?id=37459
-		"-Xclang", "-analyzer-config", "-Xclang", "c++-temp-dtor-inlining=false",
-	}
-
-	for _, f := range extraArgFlags {
+	for _, f := range config.TidyExtraArgFlags() {
 		flags.TidyFlags = append(flags.TidyFlags, "-extra-arg-before="+f)
 	}
 
diff --git a/cmd/soong_build/main.go b/cmd/soong_build/main.go
index 51d2345..bc2d5cb 100644
--- a/cmd/soong_build/main.go
+++ b/cmd/soong_build/main.go
@@ -157,9 +157,7 @@
 	defer ctx.EventHandler.End("mixed_build")
 
 	bazelHook := func() error {
-		ctx.EventHandler.Begin("bazel")
-		defer ctx.EventHandler.End("bazel")
-		return configuration.BazelContext.InvokeBazel(configuration)
+		return configuration.BazelContext.InvokeBazel(configuration, ctx)
 	}
 	ctx.SetBeforePrepareBuildActionsHook(bazelHook)
 	ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
diff --git a/filesystem/avb_add_hash_footer.go b/filesystem/avb_add_hash_footer.go
index af3bdbe..1ee0edc 100644
--- a/filesystem/avb_add_hash_footer.go
+++ b/filesystem/avb_add_hash_footer.go
@@ -23,10 +23,6 @@
 	"android/soong/android"
 )
 
-func init() {
-	android.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
-}
-
 type avbAddHashFooter struct {
 	android.ModuleBase
 
@@ -36,6 +32,17 @@
 	installDir android.InstallPath
 }
 
+type avbProp struct {
+	// Name of a property
+	Name *string
+
+	// Value of a property. Can't be used together with `file`.
+	Value *string
+
+	// File from which the value of the prop is read from. Can't be used together with `value`.
+	File *string `android:"path,arch_variant"`
+}
+
 type avbAddHashFooterProperties struct {
 	// Source file of this image. Can reference a genrule type module with the ":module" syntax.
 	Src *string `android:"path,arch_variant"`
@@ -57,6 +64,9 @@
 
 	// The salt in hex. Required for reproducible builds.
 	Salt *string
+
+	// List of properties to add to the footer
+	Props []avbProp
 }
 
 // The AVB footer adds verification information to the image.
@@ -106,6 +116,10 @@
 	}
 	cmd.FlagWithArg("--salt ", proptools.String(a.properties.Salt))
 
+	for _, prop := range a.properties.Props {
+		addAvbProp(ctx, cmd, prop)
+	}
+
 	cmd.FlagWithOutput("--image ", a.output)
 
 	builder.Build("avbAddHashFooter", fmt.Sprintf("avbAddHashFooter %s", ctx.ModuleName()))
@@ -114,6 +128,32 @@
 	ctx.InstallFile(a.installDir, a.installFileName(), a.output)
 }
 
+func addAvbProp(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, prop avbProp) {
+	name := proptools.String(prop.Name)
+	value := proptools.String(prop.Value)
+	file := proptools.String(prop.File)
+	if name == "" {
+		ctx.PropertyErrorf("name", "can't be empty")
+		return
+	}
+	if value == "" && file == "" {
+		ctx.PropertyErrorf("value", "either value or file should be set")
+		return
+	}
+	if value != "" && file != "" {
+		ctx.PropertyErrorf("value", "value and file can't be set at the same time")
+		return
+	}
+
+	if value != "" {
+		cmd.FlagWithArg("--prop ", proptools.ShellEscape(fmt.Sprintf("%s:%s", name, value)))
+	} else {
+		p := android.PathForModuleSrc(ctx, file)
+		cmd.Input(p)
+		cmd.FlagWithArg("--prop_from_file ", proptools.ShellEscape(fmt.Sprintf("%s:%s", name, cmd.PathForInput(p))))
+	}
+}
+
 var _ android.AndroidMkEntriesProvider = (*avbAddHashFooter)(nil)
 
 // Implements android.AndroidMkEntriesProvider
diff --git a/filesystem/filesystem.go b/filesystem/filesystem.go
index 6e1e78a..1365d4a 100644
--- a/filesystem/filesystem.go
+++ b/filesystem/filesystem.go
@@ -34,6 +34,7 @@
 func registerBuildComponents(ctx android.RegistrationContext) {
 	ctx.RegisterModuleType("android_filesystem", filesystemFactory)
 	ctx.RegisterModuleType("android_system_image", systemImageFactory)
+	ctx.RegisterModuleType("avb_add_hash_footer", avbAddHashFooterFactory)
 }
 
 type filesystem struct {
diff --git a/filesystem/filesystem_test.go b/filesystem/filesystem_test.go
index cda06d9..9bfcc3d 100644
--- a/filesystem/filesystem_test.go
+++ b/filesystem/filesystem_test.go
@@ -125,3 +125,37 @@
 	module := result.ModuleForTests("myfilesystem", "android_common").Module().(*systemImage)
 	android.AssertDeepEquals(t, "entries should have foo only", []string{"components/foo"}, module.entries)
 }
+
+func TestAvbAddHashFooter(t *testing.T) {
+	result := fixture.RunTestWithBp(t, `
+		avb_add_hash_footer {
+			name: "myfooter",
+			src: "input.img",
+			filename: "output.img",
+			partition_name: "mypartition",
+			private_key: "mykey",
+			salt: "1111",
+			props: [
+				{
+					name: "prop1",
+					value: "value1",
+				},
+				{
+					name: "prop2",
+					file: "value_file",
+				},
+			],
+		}
+	`)
+	cmd := result.ModuleForTests("myfooter", "android_arm64_armv8-a").Rule("avbAddHashFooter").RuleParams.Command
+	android.AssertStringDoesContain(t, "Can't find correct --partition_name argument",
+		cmd, "--partition_name mypartition")
+	android.AssertStringDoesContain(t, "Can't find correct --key argument",
+		cmd, "--key mykey")
+	android.AssertStringDoesContain(t, "Can't find --salt argument",
+		cmd, "--salt 1111")
+	android.AssertStringDoesContain(t, "Can't find --prop argument",
+		cmd, "--prop 'prop1:value1'")
+	android.AssertStringDoesContain(t, "Can't find --prop_from_file argument",
+		cmd, "--prop_from_file 'prop2:value_file'")
+}
diff --git a/go.mod b/go.mod
index 5f0b91a..7239f6d 100644
--- a/go.mod
+++ b/go.mod
@@ -1,24 +1,21 @@
 module android/soong
 
-require google.golang.org/protobuf v0.0.0
+require (
+  google.golang.org/protobuf v0.0.0
+  github.com/google/blueprint v0.0.0
+  prebuilts/bazel/common/proto/analysis_v2 v0.0.0
+  prebuilts/bazel/common/proto/build v0.0.0 // indirect
+)
 
-require github.com/google/blueprint v0.0.0
-
-replace google.golang.org/protobuf v0.0.0 => ../../external/golang-protobuf
-
-replace github.com/google/blueprint v0.0.0 => ../blueprint
+replace (
+  google.golang.org/protobuf v0.0.0 => ../../external/golang-protobuf
+  github.com/google/blueprint v0.0.0 => ../blueprint
+  github.com/google/go-cmp v0.5.5 => ../../external/go-cmp
+  prebuilts/bazel/common/proto/analysis_v2 => ../../prebuilts/bazel/common/proto/analysis_v2
+  prebuilts/bazel/common/proto/build => ../../prebuilts/bazel/common/proto/build
+)
 
 // Indirect deps from golang-protobuf
 exclude github.com/golang/protobuf v1.5.0
 
-replace github.com/google/go-cmp v0.5.5 => ../../external/go-cmp
-
-require prebuilts/bazel/common/proto/analysis_v2 v0.0.0
-
-replace prebuilts/bazel/common/proto/analysis_v2 => ../../prebuilts/bazel/common/proto/analysis_v2
-
-require prebuilts/bazel/common/proto/build v0.0.0 // indirect
-
-replace prebuilts/bazel/common/proto/build => ../../prebuilts/bazel/common/proto/build
-
-go 1.18
+go 2.0
diff --git a/java/aar.go b/java/aar.go
index 6261f29..0fdde03 100644
--- a/java/aar.go
+++ b/java/aar.go
@@ -1046,7 +1046,8 @@
 }
 
 func (a *AndroidLibrary) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
-	commonAttrs, depLabels := a.convertLibraryAttrsBp2Build(ctx)
+	commonAttrs, bp2buildInfo := a.convertLibraryAttrsBp2Build(ctx)
+	depLabels := bp2buildInfo.DepLabels
 
 	deps := depLabels.Deps
 	if !commonAttrs.Srcs.IsEmpty() {
diff --git a/java/app.go b/java/app.go
index 2a51e10..e36808f 100755
--- a/java/app.go
+++ b/java/app.go
@@ -1492,7 +1492,8 @@
 
 // ConvertWithBp2build is used to convert android_app to Bazel.
 func (a *AndroidApp) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
-	commonAttrs, depLabels := a.convertLibraryAttrsBp2Build(ctx)
+	commonAttrs, bp2BuildInfo := a.convertLibraryAttrsBp2Build(ctx)
+	depLabels := bp2BuildInfo.DepLabels
 
 	deps := depLabels.Deps
 	deps.Append(depLabels.StaticDeps)
diff --git a/java/java.go b/java/java.go
index 3471abb..ad46e98 100644
--- a/java/java.go
+++ b/java/java.go
@@ -25,6 +25,7 @@
 
 	"android/soong/bazel"
 	"android/soong/bazel/cquery"
+	"android/soong/remoteexec"
 
 	"github.com/google/blueprint"
 	"github.com/google/blueprint/proptools"
@@ -59,6 +60,8 @@
 	ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
 	ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
 	ctx.RegisterModuleType("dex_import", DexImportFactory)
+	ctx.RegisterModuleType("java_api_library", ApiLibraryFactory)
+	ctx.RegisterModuleType("java_api_contribution", ApiContributionFactory)
 
 	// This mutator registers dependencies on dex2oat for modules that should be
 	// dexpreopted. This is done late when the final variants have been
@@ -1529,6 +1532,182 @@
 	return module
 }
 
+type JavaApiContribution struct {
+	android.ModuleBase
+	android.DefaultableModuleBase
+
+	properties struct {
+		// name of the API surface
+		Api_surface *string
+
+		// relative path to the API signature text file
+		Api_file *string `android:"path"`
+	}
+}
+
+func ApiContributionFactory() android.Module {
+	module := &JavaApiContribution{}
+	android.InitAndroidModule(module)
+	android.InitDefaultableModule(module)
+	module.AddProperties(&module.properties)
+	return module
+}
+
+type JavaApiImportInfo struct {
+	ApiFile android.Path
+}
+
+var JavaApiImportProvider = blueprint.NewProvider(JavaApiImportInfo{})
+
+func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	apiFile := android.PathForModuleSrc(ctx, String(ap.properties.Api_file))
+	ctx.SetProvider(JavaApiImportProvider, JavaApiImportInfo{
+		ApiFile: apiFile,
+	})
+}
+
+type ApiLibrary struct {
+	android.ModuleBase
+	android.DefaultableModuleBase
+
+	properties JavaApiLibraryProperties
+
+	stubsSrcJar android.WritablePath
+	stubsJar    android.WritablePath
+}
+
+type JavaApiLibraryProperties struct {
+	// name of the API surface
+	Api_surface *string
+
+	// list of API provider modules that consists this API surface
+	Api_providers []string
+
+	// List of flags to be passed to the javac compiler to generate jar file
+	Javacflags []string
+}
+
+func ApiLibraryFactory() android.Module {
+	module := &ApiLibrary{}
+	android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
+	android.InitDefaultableModule(module)
+	module.AddProperties(&module.properties)
+	return module
+}
+
+func (al *ApiLibrary) ApiSurface() *string {
+	return al.properties.Api_surface
+}
+
+func (al *ApiLibrary) StubsJar() android.Path {
+	return al.stubsJar
+}
+
+func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
+	srcs android.Paths, homeDir android.WritablePath) *android.RuleBuilderCommand {
+	rule.Command().Text("rm -rf").Flag(homeDir.String())
+	rule.Command().Text("mkdir -p").Flag(homeDir.String())
+
+	cmd := rule.Command()
+	cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
+
+	if metalavaUseRbe(ctx) {
+		rule.Remoteable(android.RemoteRuleSupports{RBE: true})
+		execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
+		labels := map[string]string{"type": "tool", "name": "metalava"}
+
+		pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
+		rule.Rewrapper(&remoteexec.REParams{
+			Labels:          labels,
+			ExecStrategy:    execStrategy,
+			ToolchainInputs: []string{config.JavaCmd(ctx).String()},
+			Platform:        map[string]string{remoteexec.PoolKey: pool},
+		})
+	}
+
+	cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
+		Flag(config.JavacVmFlags).
+		Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
+		FlagWithArg("-encoding ", "UTF-8").
+		FlagWithInputList("--source-files ", srcs, " ")
+
+	cmd.Flag("--no-banner").
+		Flag("--color").
+		Flag("--quiet").
+		Flag("--format=v2").
+		FlagWithArg("--repeat-errors-max ", "10").
+		FlagWithArg("--hide ", "UnresolvedImport").
+		FlagWithArg("--hide ", "InvalidNullabilityOverride").
+		FlagWithArg("--hide ", "ChangedDefault")
+
+	return cmd
+}
+
+func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
+	if stubsDir.Valid() {
+		cmd.FlagWithArg("--stubs ", stubsDir.String())
+	}
+}
+
+var javaApiProviderTag = dependencyTag{name: "java-api-provider"}
+
+func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
+	apiProviders := al.properties.Api_providers
+	for _, apiProviderName := range apiProviders {
+		ctx.AddDependency(ctx.Module(), javaApiProviderTag, apiProviderName)
+	}
+}
+
+func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+
+	rule := android.NewRuleBuilder(pctx, ctx)
+
+	rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
+		android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
+		SandboxInputs()
+
+	var stubsDir android.OptionalPath
+	stubsDir = android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
+	rule.Command().Text("rm -rf").Text(stubsDir.String())
+	rule.Command().Text("mkdir -p").Text(stubsDir.String())
+
+	homeDir := android.PathForModuleOut(ctx, "metalava", "home")
+
+	apiProviders := al.properties.Api_providers
+	srcFiles := make([]android.Path, len(apiProviders))
+	for i, apiProviderName := range apiProviders {
+		apiProvider := ctx.GetDirectDepWithTag(apiProviderName, javaApiProviderTag)
+		if apiProvider == nil {
+			panic(fmt.Errorf("Java API provider module %s not found, called from %s", apiProviderName, al.Name()))
+		}
+		provider := ctx.OtherModuleProvider(apiProvider, JavaApiImportProvider).(JavaApiImportInfo)
+		srcFiles[i] = android.PathForModuleSrc(ctx, provider.ApiFile.String())
+	}
+
+	cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir)
+
+	al.stubsFlags(ctx, cmd, stubsDir)
+
+	al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
+	rule.Command().
+		BuiltTool("soong_zip").
+		Flag("-write_if_changed").
+		Flag("-jar").
+		FlagWithOutput("-o ", al.stubsSrcJar).
+		FlagWithArg("-C ", stubsDir.String()).
+		FlagWithArg("-D ", stubsDir.String())
+
+	rule.Build("metalava", "metalava merged")
+
+	al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), "android.jar")
+
+	var flags javaBuilderFlags
+	flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
+
+	TransformJavaToClasses(ctx, al.stubsJar, 0, android.Paths{},
+		android.Paths{al.stubsSrcJar}, flags, android.Paths{})
+}
+
 //
 // Java prebuilts
 //
@@ -2335,11 +2514,21 @@
 	Deps bazel.LabelListAttribute
 }
 
-// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
-// and also separates dependencies into dynamic dependencies and static dependencies.
-// Each corresponding Bazel target type, can have a different method for handling
-// dynamic vs. static dependencies, and so these are returned to the calling function.
-func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
+// bp2BuildJavaInfo has information needed for the conversion of  java*_modules
+// that is needed bor Bp2Build conversion but that requires different handling
+// depending on the module type.
+type bp2BuildJavaInfo struct {
+	// separates dependencies into dynamic dependencies and static dependencies.
+	DepLabels     *javaDependencyLabels
+	hasKotlinSrcs bool
+}
+
+// convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
+// converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
+// which has other non-attribute information needed for bp2build conversion
+// that needs different handling depending on the module types, and thus needs
+// to be returned to the calling function.
+func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) {
 	var srcs bazel.LabelListAttribute
 	var deps bazel.LabelList
 	var staticDeps bazel.LabelList
@@ -2358,14 +2547,18 @@
 	protoSrcPartition := "proto"
 	logtagSrcPartition := "logtag"
 	aidlSrcPartition := "aidl"
+	kotlinPartition := "kotlin"
 	srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
 		javaSrcPartition:   bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
 		logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
 		protoSrcPartition:  android.ProtoSrcLabelPartition,
 		aidlSrcPartition:   android.AidlSrcLabelPartition,
+		kotlinPartition:    bazel.LabelPartition{Extensions: []string{".kt"}},
 	})
 
 	javaSrcs := srcPartitions[javaSrcPartition]
+	kotlinSrcs := srcPartitions[kotlinPartition]
+	javaSrcs.Append(kotlinSrcs)
 
 	if !srcPartitions[logtagSrcPartition].IsEmpty() {
 		logtagsLibName := m.Name() + "_logtags"
@@ -2475,18 +2668,25 @@
 	depLabels.Deps = bazel.MakeLabelListAttribute(deps)
 	depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
 
-	return commonAttrs, depLabels
+	bp2BuildInfo := &bp2BuildJavaInfo{
+		DepLabels:     depLabels,
+		hasKotlinSrcs: !kotlinSrcs.IsEmpty(),
+	}
+
+	return commonAttrs, bp2BuildInfo
 }
 
 type javaLibraryAttributes struct {
 	*javaCommonAttributes
-	Deps      bazel.LabelListAttribute
-	Exports   bazel.LabelListAttribute
-	Neverlink bazel.BoolAttribute
+	Deps        bazel.LabelListAttribute
+	Exports     bazel.LabelListAttribute
+	Neverlink   bazel.BoolAttribute
+	Common_srcs bazel.LabelListAttribute
 }
 
 func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
-	commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
+	commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
+	depLabels := bp2BuildInfo.DepLabels
 
 	deps := depLabels.Deps
 	if !commonAttrs.Srcs.IsEmpty() {
@@ -2501,15 +2701,25 @@
 		ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
 	}
 
+	var props bazel.BazelTargetModuleProperties
 	attrs := &javaLibraryAttributes{
 		javaCommonAttributes: commonAttrs,
 		Deps:                 deps,
 		Exports:              depLabels.StaticDeps,
 	}
 
-	props := bazel.BazelTargetModuleProperties{
-		Rule_class:        "java_library",
-		Bzl_load_location: "//build/bazel/rules/java:library.bzl",
+	if !bp2BuildInfo.hasKotlinSrcs && len(m.properties.Common_srcs) == 0 {
+		props = bazel.BazelTargetModuleProperties{
+			Rule_class:        "java_library",
+			Bzl_load_location: "//build/bazel/rules/java:library.bzl",
+		}
+	} else {
+		attrs.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
+
+		props = bazel.BazelTargetModuleProperties{
+			Rule_class:        "kt_jvm_library",
+			Bzl_load_location: "@rules_kotlin//kotlin:jvm_library.bzl",
+		}
 	}
 
 	name := m.Name()
@@ -2526,7 +2736,8 @@
 
 // JavaBinaryHostBp2Build is for java_binary_host bp2build.
 func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
-	commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
+	commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
+	depLabels := bp2BuildInfo.DepLabels
 
 	deps := depLabels.Deps
 	deps.Append(depLabels.StaticDeps)
diff --git a/java/java_test.go b/java/java_test.go
index f06b520..3f8cd8e 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -1806,3 +1806,108 @@
 			srcs: ["foo.java"],
 		}`)
 }
+
+func TestJavaApiLibraryAndProviderLink(t *testing.T) {
+	provider_bp_a := `
+	java_api_contribution {
+		name: "foo1",
+		api_file: "foo1.txt",
+	}
+	`
+	provider_bp_b := `java_api_contribution {
+		name: "foo2",
+		api_file: "foo2.txt",
+	}
+	`
+	ctx, _ := testJavaWithFS(t, `
+		java_api_library {
+			name: "bar1",
+			api_surface: "public",
+			api_providers: ["foo1"],
+		}
+
+		java_api_library {
+			name: "bar2",
+			api_surface: "system",
+			api_providers: ["foo1", "foo2"],
+		}
+		`,
+		map[string][]byte{
+			"a/Android.bp": []byte(provider_bp_a),
+			"b/Android.bp": []byte(provider_bp_b),
+		})
+
+	testcases := []struct {
+		moduleName         string
+		sourceTextFileDirs []string
+	}{
+		{
+			moduleName:         "bar1",
+			sourceTextFileDirs: []string{"a/foo1.txt"},
+		},
+		{
+			moduleName:         "bar2",
+			sourceTextFileDirs: []string{"a/foo1.txt", "b/foo2.txt"},
+		},
+	}
+	for _, c := range testcases {
+		m := ctx.ModuleForTests(c.moduleName, "android_common")
+		manifest := m.Output("metalava.sbox.textproto")
+		sboxProto := android.RuleBuilderSboxProtoForTests(t, manifest)
+		manifestCommand := sboxProto.Commands[0].GetCommand()
+		sourceFilesFlag := "--source-files " + strings.Join(c.sourceTextFileDirs, " ")
+		android.AssertStringDoesContain(t, "source text files not present", manifestCommand, sourceFilesFlag)
+	}
+}
+
+func TestJavaApiLibraryJarGeneration(t *testing.T) {
+	provider_bp_a := `
+	java_api_contribution {
+		name: "foo1",
+		api_file: "foo1.txt",
+	}
+	`
+	provider_bp_b := `java_api_contribution {
+		name: "foo2",
+		api_file: "foo2.txt",
+	}
+	`
+	ctx, _ := testJavaWithFS(t, `
+		java_api_library {
+			name: "bar1",
+			api_surface: "public",
+			api_providers: ["foo1"],
+		}
+
+		java_api_library {
+			name: "bar2",
+			api_surface: "system",
+			api_providers: ["foo1", "foo2"],
+		}
+		`,
+		map[string][]byte{
+			"a/Android.bp": []byte(provider_bp_a),
+			"b/Android.bp": []byte(provider_bp_b),
+		})
+
+	testcases := []struct {
+		moduleName    string
+		outputJarName string
+	}{
+		{
+			moduleName:    "bar1",
+			outputJarName: "bar1/android.jar",
+		},
+		{
+			moduleName:    "bar2",
+			outputJarName: "bar2/android.jar",
+		},
+	}
+	for _, c := range testcases {
+		m := ctx.ModuleForTests(c.moduleName, "android_common")
+		outputs := fmt.Sprint(m.AllOutputs())
+		if !strings.Contains(outputs, c.outputJarName) {
+			t.Errorf("Module output does not contain expected jar %s", c.outputJarName)
+		}
+	}
+}
diff --git a/java/legacy_core_platform_api_usage.go b/java/legacy_core_platform_api_usage.go
index 8e22491..1f374b4 100644
--- a/java/legacy_core_platform_api_usage.go
+++ b/java/legacy_core_platform_api_usage.go
@@ -20,155 +20,39 @@
 )
 
 var legacyCorePlatformApiModules = []string{
-	"AAECarSystemUI",
-	"AAECarSystemUI-tests",
 	"ArcSettings",
-	"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",
-	"BackupEncryption",
-	"BackupFrameworksServicesRoboTests",
-	"backuplib",
-	"BandwidthEnforcementTest",
-	"BlockedNumberProvider",
-	"BluetoothInstrumentationTests",
-	"BluetoothMidiLib",
-	"BluetoothMidiService",
 	"BTTestApp",
-	"CallEnhancement",
 	"CapCtrlInterface",
-	"CarService",
-	"CarServiceTest",
-	"car-service-test-lib",
-	"car-service-test-static-lib",
-	"CertInstaller",
 	"com.qti.location.sdk",
-	"com.qti.media.secureprocessor",
-	"ConnectivityManagerTest",
-	"ContactsProvider",
-	"CorePerfTests",
-	"core-tests-support",
-	"cronet_impl_common_java",
-	"cronet_impl_native_java",
-	"cronet_impl_platform_java",
-	"CtsAppExitTestCases",
-	"CtsContentTestCases",
-	"CtsLibcoreWycheproofBCTestCases",
-	"CtsMediaTestCases",
-	"CtsNetTestCases",
-	"CtsNetTestCasesLatestSdk",
-	"CtsSecurityTestCases",
-	"CtsSuspendAppsTestCases",
-	"CtsUsageStatsTestCases",
-	"DeadpoolService",
-	"DeadpoolServiceBtServices",
-	"DeviceInfo",
-	"DiagnosticTools",
-	"DisplayCutoutEmulationEmu01Overlay",
-	"DocumentsUIGoogleTests",
-	"DocumentsUIPerfTests",
-	"DocumentsUITests",
-	"DocumentsUIUnitTests",
-	"DownloadProvider",
-	"DownloadProviderTests",
-	"DownloadProviderUi",
-	"ds-car-docs", // for AAOS API documentation only
-	"DynamicSystemInstallationService",
-	"EmergencyInfo-lib",
-	"EthernetServiceTests",
-	"ExternalStorageProvider",
 	"face-V1-0-javalib",
 	"FloralClocks",
 	"framework-jobscheduler",
 	"framework-minus-apex",
 	"framework-minus-apex-intdefs",
-	"FrameworkOverlayG6QU3",
 	"FrameworksCoreTests",
-	"FrameworksIkeTests",
-	"FrameworksNetCommonTests",
-	"FrameworksNetTests",
-	"FrameworksServicesRoboTests",
-	"FrameworksServicesTests",
-	"FrameworksMockingServicesTests",
-	"FrameworksUtilTests",
-	"GtsIncrementalInstallTestCases",
-	"GtsIncrementalInstallTriggerApp",
-	"GtsInstallerV2TestCases",
 	"HelloOslo",
-	"hid",
-	"hidl_test_java_java",
-	"hwbinder",
-	"imssettings",
 	"izat.lib.glue",
-	"KeyChain",
-	"LocalSettingsLib",
-	"LocalTransport",
-	"lockagent",
-	"mediaframeworktest",
 	"mediatek-ims-base",
-	"MmsService",
 	"ModemTestMode",
 	"MtkCapCtrl",
-	"MtpService",
-	"MultiDisplayProvider",
 	"my.tests.snapdragonsdktest",
 	"NetworkSetting",
-	"NetworkStackIntegrationTestsLib",
-	"NetworkStackNextIntegrationTests",
-	"NetworkStackNextTests",
-	"NetworkStackTests",
-	"NetworkStackTestsLib",
-	"online-gcm-ref-docs",
-	"online-gts-docs",
 	"PerformanceMode",
-	"platform_library-docs",
-	"PowerStatsService",
-	"PrintSpooler",
 	"pxp-monitor",
 	"QColor",
 	"qcom.fmradio",
-	"QDCMMobileApp",
 	"Qmmi",
 	"QPerformance",
-	"remotesimlockmanagerlibrary",
-	"RollbackTest",
 	"sam",
 	"saminterfacelibrary",
 	"sammanagerlibrary",
-	"service-blobstore",
-	"service-connectivity-pre-jarjar",
-	"service-jobscheduler",
 	"services",
-	"services.accessibility",
-	"services.backup",
 	"services.core.unboosted",
-	"services.devicepolicy",
-	"services.print",
-	"services.usage",
-	"services.usb",
 	"Settings-core",
 	"SettingsGoogle",
 	"SettingsGoogleOverlayCoral",
 	"SettingsGoogleOverlayFlame",
 	"SettingsLib",
-	"SettingsOverlayG020A",
-	"SettingsOverlayG020B",
-	"SettingsOverlayG020C",
-	"SettingsOverlayG020D",
-	"SettingsOverlayG020E",
-	"SettingsOverlayG020E_VN",
-	"SettingsOverlayG020F",
-	"SettingsOverlayG020F_VN",
-	"SettingsOverlayG020G",
-	"SettingsOverlayG020G_VN",
-	"SettingsOverlayG020H",
-	"SettingsOverlayG020H_VN",
 	"SettingsOverlayG020I",
 	"SettingsOverlayG020I_VN",
 	"SettingsOverlayG020J",
@@ -177,45 +61,15 @@
 	"SettingsOverlayG020P",
 	"SettingsOverlayG020Q",
 	"SettingsOverlayG025H",
-	"SettingsOverlayG025J",
-	"SettingsOverlayG025M",
-	"SettingsOverlayG025N",
 	"SettingsOverlayG5NZ6",
-	"SettingsProvider",
-	"SettingsProviderTest",
 	"SettingsRoboTests",
-	"Shell",
-	"ShellTests",
 	"SimContact",
 	"SimContacts",
 	"SimSettings",
-	"sl4a.Common",
-	"StatementService",
-	"SystemUI-core",
-	"SystemUISharedLib",
-	"SystemUI-tests",
 	"tcmiface",
-	"Telecom",
-	"TelecomUnitTests",
 	"telephony-common",
-	"TelephonyProviderTests",
 	"TeleService",
-	"testables",
-	"TetheringTests",
-	"TetheringTestsLib",
-	"time_zone_distro_installer",
-	"time_zone_distro_installer-tests",
-	"time_zone_distro-tests",
-	"time_zone_updater",
-	"TMobilePlanProvider",
-	"TvProvider",
-	"uiautomator-stubs-docs",
-	"uimgbamanagerlibrary",
-	"UsbHostExternalManagementTestApp",
-	"UserDictionaryProvider",
 	"UxPerformance",
-	"WallpaperBackup",
-	"WallpaperBackupAgentTests",
 	"WfdCommon",
 }
 
diff --git a/java/plugin.go b/java/plugin.go
index 123dbd4..731dfda 100644
--- a/java/plugin.go
+++ b/java/plugin.go
@@ -66,7 +66,8 @@
 // ConvertWithBp2build is used to convert android_app to Bazel.
 func (p *Plugin) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
 	pluginName := p.Name()
-	commonAttrs, depLabels := p.convertLibraryAttrsBp2Build(ctx)
+	commonAttrs, bp2BuildInfo := p.convertLibraryAttrsBp2Build(ctx)
+	depLabels := bp2BuildInfo.DepLabels
 
 	deps := depLabels.Deps
 	deps.Append(depLabels.StaticDeps)
diff --git a/ui/build/Android.bp b/ui/build/Android.bp
index cfcf804..7a8fca9 100644
--- a/ui/build/Android.bp
+++ b/ui/build/Android.bp
@@ -46,7 +46,6 @@
         "soong-ui-tracer",
     ],
     srcs: [
-        "bazel.go",
         "build.go",
         "cleanbuild.go",
         "config.go",
diff --git a/ui/build/bazel.go b/ui/build/bazel.go
deleted file mode 100644
index bd469a4..0000000
--- a/ui/build/bazel.go
+++ /dev/null
@@ -1,257 +0,0 @@
-// 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 build
-
-import (
-	"bytes"
-	"fmt"
-	"io/ioutil"
-	"os"
-	"path/filepath"
-	"strings"
-
-	"android/soong/bazel"
-	"android/soong/shared"
-	"android/soong/ui/metrics"
-)
-
-func getBazelInfo(ctx Context, config Config, bazelExecutable string, bazelEnv map[string]string, query string) string {
-	infoCmd := Command(ctx, config, "bazel", bazelExecutable)
-
-	if extraStartupArgs, ok := infoCmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
-		infoCmd.Args = append(infoCmd.Args, strings.Fields(extraStartupArgs)...)
-	}
-
-	// Obtain the output directory path in the execution root.
-	infoCmd.Args = append(infoCmd.Args,
-		"info",
-		query,
-	)
-
-	for k, v := range bazelEnv {
-		infoCmd.Environment.Set(k, v)
-	}
-
-	infoCmd.Dir = filepath.Join(config.OutDir(), "..")
-
-	queryResult := strings.TrimSpace(string(infoCmd.OutputOrFatal()))
-	return queryResult
-}
-
-// Main entry point to construct the Bazel build command line, environment
-// variables and post-processing steps (e.g. converge output directories)
-func runBazel(ctx Context, config Config) {
-	ctx.BeginTrace(metrics.RunBazel, "bazel")
-	defer ctx.EndTrace()
-
-	// "droid" is the default ninja target.
-	// TODO(b/160568333): stop hardcoding 'droid' to support building any
-	// Ninja target.
-	outputGroups := "droid"
-	if len(config.ninjaArgs) > 0 {
-		// At this stage, the residue slice of args passed to ninja
-		// are the ninja targets to build, which can correspond directly
-		// to ninja_build's output_groups.
-		outputGroups = strings.Join(config.ninjaArgs, ",")
-	}
-
-	// Environment variables are the primary mechanism to pass information from
-	// soong_ui configuration or context to Bazel.
-	bazelEnv := make(map[string]string)
-
-	// Use *_NINJA variables to pass the root-relative path of the combined,
-	// kati-generated, soong-generated, and packaging Ninja files to Bazel.
-	// Bazel reads these from the lunch() repository rule.
-	bazelEnv["COMBINED_NINJA"] = config.CombinedNinjaFile()
-	bazelEnv["KATI_NINJA"] = config.KatiBuildNinjaFile()
-	bazelEnv["PACKAGE_NINJA"] = config.KatiPackageNinjaFile()
-	bazelEnv["SOONG_NINJA"] = config.SoongNinjaFile()
-
-	// NOTE: When Bazel is used, config.DistDir() is rigged to return a fake distdir under config.OutDir()
-	// This is to ensure that Bazel can actually write there. See config.go for more details.
-	bazelEnv["DIST_DIR"] = config.DistDir()
-
-	bazelEnv["SHELL"] = "/bin/bash"
-
-	// `build/bazel/bin/bazel` is the default entry point for executing Bazel in the AOSP
-	// source tree.
-	bazelExecutable := filepath.Join("build", "bazel", "bin", "bazel")
-	cmd := Command(ctx, config, "bazel", bazelExecutable)
-
-	// Append custom startup flags to the Bazel command. Startup flags affect
-	// the Bazel server itself, and any changes to these flags would incur a
-	// restart of the server, losing much of the in-memory incrementality.
-	if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
-		cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
-	}
-
-	// Start constructing the `build` command.
-	actionName := bazel.BazelNinjaExecRunName
-	cmd.Args = append(cmd.Args,
-		"build",
-		// Use output_groups to select the set of outputs to produce from a
-		// ninja_build target.
-		"--output_groups="+outputGroups,
-		// Generate a performance profile
-		"--profile="+filepath.Join(shared.BazelMetricsFilename(config, actionName)),
-		"--slim_profile=true",
-	)
-
-	if config.UseRBE() {
-		for _, envVar := range []string{
-			// RBE client
-			"RBE_compare",
-			"RBE_exec_strategy",
-			"RBE_invocation_id",
-			"RBE_log_dir",
-			"RBE_num_retries_if_mismatched",
-			"RBE_platform",
-			"RBE_remote_accept_cache",
-			"RBE_remote_update_cache",
-			"RBE_server_address",
-			// TODO: remove old FLAG_ variables.
-			"FLAG_compare",
-			"FLAG_exec_root",
-			"FLAG_exec_strategy",
-			"FLAG_invocation_id",
-			"FLAG_log_dir",
-			"FLAG_platform",
-			"FLAG_remote_accept_cache",
-			"FLAG_remote_update_cache",
-			"FLAG_server_address",
-		} {
-			cmd.Args = append(cmd.Args,
-				"--action_env="+envVar)
-		}
-
-		// We need to calculate --RBE_exec_root ourselves
-		ctx.Println("Getting Bazel execution_root...")
-		cmd.Args = append(cmd.Args, "--action_env=RBE_exec_root="+getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "execution_root"))
-	}
-
-	// Ensure that the PATH environment variable value used in the action
-	// environment is the restricted set computed from soong_ui, and not a
-	// user-provided one, for hermeticity reasons.
-	if pathEnvValue, ok := config.environ.Get("PATH"); ok {
-		cmd.Environment.Set("PATH", pathEnvValue)
-		cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
-	}
-
-	// Allow Bazel actions to see the SHELL variable (passed to Bazel above)
-	cmd.Args = append(cmd.Args, "--action_env=SHELL")
-
-	// Append custom build flags to the Bazel command. Changes to these flags
-	// may invalidate Bazel's analysis cache.
-	// These should be appended as the final args, so that they take precedence.
-	if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
-		cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
-	}
-
-	// Append the label of the default ninja_build target.
-	cmd.Args = append(cmd.Args,
-		"//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
-	)
-
-	// Execute the command at the root of the directory.
-	cmd.Dir = filepath.Join(config.OutDir(), "..")
-
-	for k, v := range bazelEnv {
-		cmd.Environment.Set(k, v)
-	}
-
-	// Make a human-readable version of the bazelEnv map
-	bazelEnvStringBuffer := new(bytes.Buffer)
-	for k, v := range bazelEnv {
-		fmt.Fprintf(bazelEnvStringBuffer, "%s=%s ", k, v)
-	}
-
-	// Print the implicit command line
-	ctx.Println("Bazel implicit command line: " + strings.Join(cmd.Environment.Environ(), " ") + " " + cmd.Cmd.String() + "\n")
-
-	// Print the explicit command line too
-	ctx.Println("Bazel explicit command line: " + bazelEnvStringBuffer.String() + cmd.Cmd.String() + "\n")
-
-	// Execute the build command.
-	cmd.RunAndStreamOrFatal()
-
-	// Post-processing steps start here. Once the Bazel build completes, the
-	// output files are still stored in the execution root, not in $OUT_DIR.
-	// Ensure that the $OUT_DIR contains the expected set of files by symlinking
-	// the files from the execution root's output direction into $OUT_DIR.
-
-	ctx.Println("Getting Bazel output_path...")
-	outputBasePath := getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "output_path")
-	// TODO: Don't hardcode out/ as the bazel output directory. This is
-	// currently hardcoded as ninja_build.output_root.
-	bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
-
-	ctx.Println("Populating output directory...")
-	populateOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
-}
-
-// For all files F recursively under rootPath/relativePath, creates symlinks
-// such that OutDir/F resolves to rootPath/F via symlinks.
-// NOTE: For distdir paths we rename files instead of creating symlinks, so that the distdir is independent.
-func populateOutdir(ctx Context, config Config, rootPath string, relativePath string) {
-	destDir := filepath.Join(rootPath, relativePath)
-	os.MkdirAll(destDir, 0755)
-	files, err := ioutil.ReadDir(destDir)
-	if err != nil {
-		ctx.Fatal(err)
-	}
-
-	for _, f := range files {
-		// The original Bazel file path
-		destPath := filepath.Join(destDir, f.Name())
-
-		// The desired Soong file path
-		srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
-
-		destLstatResult, destLstatErr := os.Lstat(destPath)
-		if destLstatErr != nil {
-			ctx.Fatalf("Unable to Lstat dest %s: %s", destPath, destLstatErr)
-		}
-
-		srcLstatResult, srcLstatErr := os.Lstat(srcPath)
-
-		if srcLstatErr == nil {
-			if srcLstatResult.IsDir() && destLstatResult.IsDir() {
-				// src and dest are both existing dirs - recurse on the dest dir contents...
-				populateOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
-			} else {
-				// Ignore other pre-existing src files (could be pre-existing files, directories, symlinks, ...)
-				// This can arise for files which are generated under OutDir outside of soong_build, such as .bootstrap files.
-				// FIXME: This might cause a problem later e.g. if a symlink in the build graph changes...
-			}
-		} else {
-			if !os.IsNotExist(srcLstatErr) {
-				ctx.Fatalf("Unable to Lstat src %s: %s", srcPath, srcLstatErr)
-			}
-
-			if strings.Contains(destDir, config.DistDir()) {
-				// We need to make a "real" file/dir instead of making a symlink (because the distdir can't have symlinks)
-				// Rename instead of copy in order to save disk space.
-				if err := os.Rename(destPath, srcPath); err != nil {
-					ctx.Fatalf("Unable to rename %s -> %s due to error %s", srcPath, destPath, err)
-				}
-			} else {
-				// src does not exist, so try to create a src -> dest symlink (i.e. a Soong path -> Bazel path symlink)
-				if err := os.Symlink(destPath, srcPath); err != nil {
-					ctx.Fatalf("Unable to create symlink %s -> %s due to error %s", srcPath, destPath, err)
-				}
-			}
-		}
-	}
-}
diff --git a/ui/build/build.go b/ui/build/build.go
index b9bd898..d49a754 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -90,7 +90,7 @@
 	}
 }
 
-// These are bitmasks which can be used to check whether various flags are set e.g. whether to use Bazel.
+// These are bitmasks which can be used to check whether various flags are set
 const (
 	_ = iota
 	// Whether to run the kati config step.
@@ -102,9 +102,7 @@
 	// Whether to include the kati-generated ninja file in the combined ninja.
 	RunKatiNinja = 1 << iota
 	// Whether to run ninja on the combined ninja.
-	RunNinja = 1 << iota
-	// Whether to run bazel on the combined ninja.
-	RunBazel      = 1 << iota
+	RunNinja      = 1 << iota
 	RunBuildTests = 1 << iota
 	RunAll        = RunProductConfig | RunSoong | RunKati | RunKatiNinja | RunNinja
 )
@@ -324,11 +322,6 @@
 
 		runNinjaForBuild(ctx, config)
 	}
-
-	// Currently, using Bazel requires Kati and Soong to run first, so check whether to run Bazel last.
-	if what&RunBazel != 0 {
-		runBazel(ctx, config)
-	}
 }
 
 func evaluateWhatToRun(config Config, verboseln func(v ...interface{})) int {