Merge "Use existing BUILD files for test-related tools."
diff --git a/android/allowlists/allowlists.go b/android/allowlists/allowlists.go
index 9d3ecda..e7bd920 100644
--- a/android/allowlists/allowlists.go
+++ b/android/allowlists/allowlists.go
@@ -364,7 +364,6 @@
 		"external/guava":/* recursive = */ true,
 		"external/jsr305":/* recursive = */ true,
 		"external/protobuf":/* recursive = */ false,
-		"external/python/absl-py":/* recursive = */ true,
 
 		// this BUILD file is globbed by //external/icu/icu4c/source:icu4c_test_data's "data/**/*".
 		"external/icu/icu4c/source/data/unidata/norm2":/* recursive = */ false,
@@ -375,9 +374,12 @@
 		"packages/apps/Music":/* recursive = */ true,
 		"packages/apps/QuickSearchBox":/* recursive = */ true,
 
+		"prebuilts/abi-dumps/platform":/* recursive = */ true,
+		"prebuilts/abi-dumps/ndk":/* recursive = */ true,
 		"prebuilts/bazel":/* recursive = */ true,
 		"prebuilts/bundletool":/* recursive = */ true,
 		"prebuilts/clang/host/linux-x86":/* recursive = */ false,
+		"prebuilts/clang-tools":/* recursive = */ true,
 		"prebuilts/gcc":/* recursive = */ true,
 		"prebuilts/build-tools":/* recursive = */ true,
 		"prebuilts/jdk/jdk11":/* recursive = */ false,
@@ -1354,7 +1356,7 @@
 
 	// Bazel prod-mode allowlist. Modules in this list are built by Bazel
 	// in either prod mode or staging mode.
-	ProdMixedBuildsEnabledList = []string{}
+	ProdMixedBuildsEnabledList = []string{"com.android.tzdata"}
 
 	// Staging-mode allowlist. Modules in this list are only built
 	// by Bazel with --bazel-mode-staging. This list should contain modules
diff --git a/android/config.go b/android/config.go
index 52a8f13..f430b72 100644
--- a/android/config.go
+++ b/android/config.go
@@ -541,7 +541,30 @@
 			fmt.Fprintln(os.Stderr, "unsupported device arch 'riscv64' for Bazel: falling back to non-mixed build")
 			return false
 		}
-		// TODO(b/253664931): Add other fallback criteria below.
+		if c.IsEnvTrue("GLOBAL_THINLTO") {
+			fmt.Fprintln(os.Stderr, "unsupported env var GLOBAL_THINLTO for Bazel: falling back to non-mixed build")
+			return false
+		}
+		if c.IsEnvTrue("CLANG_COVERAGE") {
+			fmt.Fprintln(os.Stderr, "unsupported env var CLANG_COVERAGE for Bazel: falling back to non-mixed build")
+			return false
+		}
+		if len(c.productVariables.SanitizeHost) > 0 {
+			fmt.Fprintln(os.Stderr, "unsupported product var SanitizeHost for Bazel: falling back to non-mixed build")
+			return false
+		}
+		if len(c.productVariables.SanitizeDevice) > 0 {
+			fmt.Fprintln(os.Stderr, "unsupported product var SanitizeDevice for Bazel: falling back to non-mixed build")
+			return false
+		}
+		if len(c.productVariables.SanitizeDeviceDiag) > 0 {
+			fmt.Fprintln(os.Stderr, "unsupported product var SanitizeDeviceDiag for Bazel: falling back to non-mixed build")
+			return false
+		}
+		if len(c.productVariables.SanitizeDeviceArch) > 0 {
+			fmt.Fprintln(os.Stderr, "unsupported product var SanitizeDeviceArch for Bazel: falling back to non-mixed build")
+			return false
+		}
 		return true
 	}).(bool)
 
diff --git a/android/module.go b/android/module.go
index b41a898..681f724 100644
--- a/android/module.go
+++ b/android/module.go
@@ -2053,7 +2053,7 @@
 }
 
 func (m *ModuleBase) InstallInVendor() bool {
-	return Bool(m.commonProperties.Vendor)
+	return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Soc_specific) || Bool(m.commonProperties.Proprietary)
 }
 
 func (m *ModuleBase) InstallInRoot() bool {
diff --git a/bp2build/cc_library_conversion_test.go b/bp2build/cc_library_conversion_test.go
index 61acf68..edb0c43 100644
--- a/bp2build/cc_library_conversion_test.go
+++ b/bp2build/cc_library_conversion_test.go
@@ -1409,6 +1409,7 @@
 		"strip":                    true,
 		"inject_bssl_hash":         true,
 		"has_stubs":                true,
+		"stubs_symbol_file":        true,
 		"use_version_lib":          true,
 	}
 
@@ -2710,7 +2711,8 @@
 
 func TestCcLibraryStubs(t *testing.T) {
 	expectedBazelTargets := makeCcLibraryTargets("a", AttrNameToString{
-		"has_stubs": `True`,
+		"has_stubs":         `True`,
+		"stubs_symbol_file": `"a.map.txt"`,
 	})
 	expectedBazelTargets = append(expectedBazelTargets, makeCcStubSuiteTargets("a", AttrNameToString{
 		"soname":            `"a.so"`,
@@ -3600,3 +3602,46 @@
 		},
 	})
 }
+
+func TestCcLibraryHeaderAbiChecker(t *testing.T) {
+	runCcLibraryTestCase(t, Bp2buildTestCase{
+		Description:                "cc_library with header abi checker",
+		ModuleTypeUnderTest:        "cc_library",
+		ModuleTypeUnderTestFactory: cc.LibraryFactory,
+		Blueprint: `cc_library {
+    name: "foo",
+    header_abi_checker: {
+        enabled: true,
+        symbol_file: "a.map.txt",
+        exclude_symbol_versions: [
+						"29",
+						"30",
+				],
+        exclude_symbol_tags: [
+						"tag1",
+						"tag2",
+				],
+        check_all_apis: true,
+        diff_flags: ["-allow-adding-removing-weak-symbols"],
+    },
+    include_build_directory: false,
+}`,
+		ExpectedBazelTargets: []string{
+			MakeBazelTarget("cc_library_static", "foo_bp2build_cc_library_static", AttrNameToString{}),
+			MakeBazelTarget("cc_library_shared", "foo", AttrNameToString{
+				"abi_checker_enabled":     `True`,
+				"abi_checker_symbol_file": `"a.map.txt"`,
+				"abi_checker_exclude_symbol_versions": `[
+        "29",
+        "30",
+    ]`,
+				"abi_checker_exclude_symbol_tags": `[
+        "tag1",
+        "tag2",
+    ]`,
+				"abi_checker_check_all_apis": `True`,
+				"abi_checker_diff_flags":     `["-allow-adding-removing-weak-symbols"]`,
+			}),
+		},
+	})
+}
diff --git a/bp2build/cc_library_shared_conversion_test.go b/bp2build/cc_library_shared_conversion_test.go
index b86f607..7e1d111 100644
--- a/bp2build/cc_library_shared_conversion_test.go
+++ b/bp2build/cc_library_shared_conversion_test.go
@@ -543,7 +543,8 @@
     ]`,
 		}),
 			MakeBazelTarget("cc_library_shared", "a", AttrNameToString{
-				"has_stubs": `True`,
+				"has_stubs":         `True`,
+				"stubs_symbol_file": `"a.map.txt"`,
 			}),
 		},
 	})
@@ -845,3 +846,43 @@
 		},
 	})
 }
+
+func TestCcLibrarySharedHeaderAbiChecker(t *testing.T) {
+	runCcLibrarySharedTestCase(t, Bp2buildTestCase{
+		Description: "cc_library_shared with header abi checker",
+		Blueprint: `cc_library_shared {
+    name: "foo",
+    header_abi_checker: {
+        enabled: true,
+        symbol_file: "a.map.txt",
+        exclude_symbol_versions: [
+						"29",
+						"30",
+				],
+        exclude_symbol_tags: [
+						"tag1",
+						"tag2",
+				],
+        check_all_apis: true,
+        diff_flags: ["-allow-adding-removing-weak-symbols"],
+    },
+    include_build_directory: false,
+}`,
+		ExpectedBazelTargets: []string{
+			MakeBazelTarget("cc_library_shared", "foo", AttrNameToString{
+				"abi_checker_enabled":     `True`,
+				"abi_checker_symbol_file": `"a.map.txt"`,
+				"abi_checker_exclude_symbol_versions": `[
+        "29",
+        "30",
+    ]`,
+				"abi_checker_exclude_symbol_tags": `[
+        "tag1",
+        "tag2",
+    ]`,
+				"abi_checker_check_all_apis": `True`,
+				"abi_checker_diff_flags":     `["-allow-adding-removing-weak-symbols"]`,
+			}),
+		},
+	})
+}
diff --git a/bp2build/java_library_conversion_test.go b/bp2build/java_library_conversion_test.go
index 00056f8..e37fa62 100644
--- a/bp2build/java_library_conversion_test.go
+++ b/bp2build/java_library_conversion_test.go
@@ -53,11 +53,13 @@
 		ExpectedBazelTargets: []string{
 			MakeBazelTarget("java_library", "java-lib-1", AttrNameToString{
 				"srcs": `["a.java"]`,
-				"deps": `[":java-lib-2"]`,
+				"deps": `[":java-lib-2-neverlink"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 			MakeBazelTarget("java_library", "java-lib-2", AttrNameToString{
 				"srcs": `["b.java"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-2"),
 		},
 	})
 }
@@ -87,11 +89,12 @@
 			MakeBazelTarget("java_library", "java-lib-1", AttrNameToString{
 				"srcs": `["a.java"]`,
 				"deps": `[
-        ":java-lib-2",
+        ":java-lib-2-neverlink",
         ":java-lib-3",
     ]`,
 				"exports": `[":java-lib-3"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -113,6 +116,7 @@
 			MakeBazelTarget("java_library", "java-lib-1", AttrNameToString{
 				"exports": `[":java-lib-2"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -152,6 +156,7 @@
 			MakeBazelTarget("java_library", "java-lib-1", AttrNameToString{
 				"plugins": `[":java-plugin-1"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	}, func(ctx android.RegistrationContext) {
 		ctx.RegisterModuleType("java_plugin", java.PluginFactory)
@@ -170,6 +175,7 @@
 				"srcs":      `["a.java"]`,
 				"javacopts": `["-source 11 -target 11"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -193,6 +199,7 @@
     ]`,
 				"srcs": `["a.java"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -212,6 +219,7 @@
 				"javacopts": `["-Xsuper-fast"]`,
 				"srcs":      `["a.java"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -232,6 +240,7 @@
 				"javacopts": `["-Xsuper-fast"]`,
 				"srcs":      `["a.java"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -265,6 +274,7 @@
         ":example_lib_logtags",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "example_lib"),
 		}})
 }
 
@@ -286,6 +296,7 @@
         "res/b.res",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -310,6 +321,7 @@
         "res/dir1/b.res",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -330,6 +342,7 @@
 				"resource_strip_prefix": `"res"`,
 				"resources":             `["res/a.res"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -354,6 +367,7 @@
         "res/dir1/b.res",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-lib-1"),
 		},
 	})
 }
@@ -406,6 +420,7 @@
         "b.java",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "example_lib"),
 		}})
 }
 
@@ -435,6 +450,7 @@
 				"exports": `[":example_lib_java_aidl_library"]`,
 				"srcs":    `["a.java"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "example_lib"),
 		},
 	}, func(ctx android.RegistrationContext) {
 		ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
@@ -490,6 +506,7 @@
         ":random_other_files",
     ]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "example_lib"),
 			MakeBazelTargetNoRestrictions("filegroup", "random_other_files", AttrNameToString{
 				"srcs": `[
         "a.java",
@@ -529,6 +546,7 @@
 			MakeBazelTarget("java_library", "foo", AttrNameToString{
 				"exports": `[":foo_java_aidl_library"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "foo"),
 		},
 	}, func(ctx android.RegistrationContext) {
 		ctx.RegisterModuleType("filegroup", android.FileGroupFactory)
diff --git a/bp2build/java_library_host_conversion_test.go b/bp2build/java_library_host_conversion_test.go
index edd8690..14854c0 100644
--- a/bp2build/java_library_host_conversion_test.go
+++ b/bp2build/java_library_host_conversion_test.go
@@ -48,7 +48,15 @@
 		ExpectedBazelTargets: []string{
 			MakeBazelTarget("java_library", "java-lib-host-1", AttrNameToString{
 				"srcs": `["a.java"]`,
-				"deps": `[":java-lib-host-2"]`,
+				"deps": `[":java-lib-host-2-neverlink"]`,
+				"target_compatible_with": `select({
+        "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    })`,
+			}),
+			MakeBazelTarget("java_library", "java-lib-host-1-neverlink", AttrNameToString{
+				"exports":   `[":java-lib-host-1"]`,
+				"neverlink": `True`,
 				"target_compatible_with": `select({
         "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
         "//conditions:default": [],
@@ -62,6 +70,14 @@
         "//conditions:default": [],
     })`,
 			}),
+			MakeBazelTarget("java_library", "java-lib-host-2-neverlink", AttrNameToString{
+				"exports":   `[":java-lib-host-2"]`,
+				"neverlink": `True`,
+				"target_compatible_with": `select({
+        "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
+        "//conditions:default": [],
+    })`,
+			}),
 		},
 	})
 }
diff --git a/bp2build/java_proto_conversion_test.go b/bp2build/java_proto_conversion_test.go
index df0df2f..d25b7c4 100644
--- a/bp2build/java_proto_conversion_test.go
+++ b/bp2build/java_proto_conversion_test.go
@@ -91,6 +91,7 @@
 				MakeBazelTarget("java_library", "java-protos", AttrNameToString{
 					"exports": fmt.Sprintf(`[":%s"]`, javaLibraryName),
 				}),
+				MakeNeverlinkDuplicateTarget("java_library", "java-protos"),
 			},
 		})
 	}
@@ -119,6 +120,7 @@
 				"exports":   `[":java-protos_java_proto_lite"]`,
 				"javacopts": `["-source 1.7 -target 1.7"]`,
 			}),
+			MakeNeverlinkDuplicateTarget("java_library", "java-protos"),
 		},
 	})
 }
diff --git a/bp2build/testing.go b/bp2build/testing.go
index 0f1a8b2..4e63d19 100644
--- a/bp2build/testing.go
+++ b/bp2build/testing.go
@@ -532,3 +532,10 @@
 	}
 	return MakeBazelTarget("cc_stub_suite", name+"_stub_libs", stubSuiteAttrs)
 }
+
+func MakeNeverlinkDuplicateTarget(moduleType string, name string) string {
+	return MakeBazelTarget(moduleType, name+"-neverlink", AttrNameToString{
+		"neverlink": `True`,
+		"exports":   `[":` + name + `"]`,
+	})
+}
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 58bb57c..aaf21e9 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -227,27 +227,17 @@
 	}
 }
 
-func (library *libraryDecorator) getAbiDiffsForAndroidMkDeps() []string {
-	if library.static() {
-		return nil
-	}
-	var abiDiffs []string
-	if library.sAbiDiff.Valid() {
-		abiDiffs = append(abiDiffs, library.sAbiDiff.String())
-	}
-	if library.prevSAbiDiff.Valid() {
-		abiDiffs = append(abiDiffs, library.prevSAbiDiff.String())
-	}
-	return abiDiffs
-}
-
 func (library *libraryDecorator) androidMkEntriesWriteAdditionalDependenciesForSourceAbiDiff(entries *android.AndroidMkEntries) {
-	entries.AddStrings("LOCAL_ADDITIONAL_DEPENDENCIES", library.getAbiDiffsForAndroidMkDeps()...)
+	if !library.static() {
+		entries.AddPaths("LOCAL_ADDITIONAL_DEPENDENCIES", library.sAbiDiff)
+	}
 }
 
 // TODO(ccross): remove this once apex/androidmk.go is converted to AndroidMkEntries
 func (library *libraryDecorator) androidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer) {
-	fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES +=", strings.Join(library.getAbiDiffsForAndroidMkDeps(), " "))
+	if !library.static() {
+		fmt.Fprintln(w, "LOCAL_ADDITIONAL_DEPENDENCIES +=", strings.Join(library.sAbiDiff.Strings(), " "))
+	}
 }
 
 func (library *libraryDecorator) AndroidMkEntries(ctx AndroidMkContext, entries *android.AndroidMkEntries) {
diff --git a/cc/builder.go b/cc/builder.go
index 46cea0b..0629406 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -292,12 +292,6 @@
 		},
 		"extraFlags", "referenceDump", "libName", "arch", "errorMessage")
 
-	// Rule to unzip a reference abi dump.
-	unzipRefSAbiDump = pctx.AndroidStaticRule("unzipRefSAbiDump",
-		blueprint.RuleParams{
-			Command: "gunzip -c $in > $out",
-		})
-
 	// Rule to zip files.
 	zip = pctx.AndroidStaticRule("zip",
 		blueprint.RuleParams{
@@ -911,59 +905,17 @@
 	return android.OptionalPathForPath(outputFile)
 }
 
-// unzipRefDump registers a build statement to unzip a reference abi dump.
-func unzipRefDump(ctx android.ModuleContext, zippedRefDump android.Path, baseName string) android.Path {
-	outputFile := android.PathForModuleOut(ctx, baseName+"_ref.lsdump")
-	ctx.Build(pctx, android.BuildParams{
-		Rule:        unzipRefSAbiDump,
-		Description: "gunzip" + outputFile.Base(),
-		Output:      outputFile,
-		Input:       zippedRefDump,
-	})
-	return outputFile
-}
-
-// sourceAbiDiff registers a build statement to compare linked sAbi dump files (.lsdump).
-func sourceAbiDiff(ctx android.ModuleContext, inputDump, referenceDump android.Path,
-	baseName string, diffFlags []string, prevVersion int,
-	checkAllApis, isLlndkOrNdk, isVndkExt, previousVersionDiff bool) android.OptionalPath {
+func transformAbiDumpToAbiDiff(ctx android.ModuleContext, inputDump, referenceDump android.Path,
+	baseName, nameExt string, extraFlags []string, errorMessage string) android.Path {
 
 	var outputFile android.ModuleOutPath
-	if previousVersionDiff {
-		outputFile = android.PathForModuleOut(ctx, baseName+"."+strconv.Itoa(prevVersion)+".abidiff")
+	if nameExt != "" {
+		outputFile = android.PathForModuleOut(ctx, baseName+"."+nameExt+".abidiff")
 	} else {
 		outputFile = android.PathForModuleOut(ctx, baseName+".abidiff")
 	}
 	libName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
 
-	var extraFlags []string
-	if checkAllApis {
-		extraFlags = append(extraFlags, "-check-all-apis")
-	} else {
-		extraFlags = append(extraFlags,
-			"-allow-unreferenced-changes",
-			"-allow-unreferenced-elf-symbol-changes")
-	}
-
-	var errorMessage string
-	if previousVersionDiff {
-		errorMessage = "error: Please follow https://android.googlesource.com/platform/development/+/master/vndk/tools/header-checker/README.md#configure-cross_version-abi-check to resolve the ABI difference between your source code and version " + strconv.Itoa(prevVersion) + "."
-		sourceVersion := prevVersion + 1
-		extraFlags = append(extraFlags, "-target-version", strconv.Itoa(sourceVersion))
-	} else {
-		errorMessage = "error: Please update ABI references with: $$ANDROID_BUILD_TOP/development/vndk/tools/header-checker/utils/create_reference_dumps.py -l " + libName
-		extraFlags = append(extraFlags, "-target-version", "current")
-	}
-
-	if isLlndkOrNdk {
-		extraFlags = append(extraFlags, "-consider-opaque-types-different")
-	}
-	if isVndkExt || previousVersionDiff {
-		extraFlags = append(extraFlags, "-allow-extensions")
-	}
-	// TODO(b/232891473): Simplify the above logic with diffFlags.
-	extraFlags = append(extraFlags, diffFlags...)
-
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        sAbiDiff,
 		Description: "header-abi-diff " + outputFile.Base(),
@@ -978,7 +930,7 @@
 			"errorMessage":  errorMessage,
 		},
 	})
-	return android.OptionalPathForPath(outputFile)
+	return outputFile
 }
 
 // Generate a rule for extracting a table of contents from a shared library (.so)
diff --git a/cc/cc.go b/cc/cc.go
index 8b3f456..2ff5bba 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -2314,28 +2314,23 @@
 	return nonvariantLibs, variantLibs
 }
 
-func updateDepsWithApiImports(deps Deps, apiImports multitree.ApiImportInfo) Deps {
-	for idx, lib := range deps.SharedLibs {
-		deps.SharedLibs[idx] = GetReplaceModuleName(lib, apiImports.SharedLibs)
+func rewriteLibsForApiImports(c LinkableInterface, libs []string, replaceList map[string]string, config android.Config) ([]string, []string) {
+	nonVariantLibs := []string{}
+	variantLibs := []string{}
+
+	for _, lib := range libs {
+		replaceLibName := GetReplaceModuleName(lib, replaceList)
+		if replaceLibName == lib {
+			// Do not handle any libs which are not in API imports
+			nonVariantLibs = append(nonVariantLibs, replaceLibName)
+		} else if c.UseSdk() && inList(replaceLibName, *getNDKKnownLibs(config)) {
+			variantLibs = append(variantLibs, replaceLibName)
+		} else {
+			nonVariantLibs = append(nonVariantLibs, replaceLibName)
+		}
 	}
 
-	for idx, lib := range deps.LateSharedLibs {
-		deps.LateSharedLibs[idx] = GetReplaceModuleName(lib, apiImports.SharedLibs)
-	}
-
-	for idx, lib := range deps.RuntimeLibs {
-		deps.RuntimeLibs[idx] = GetReplaceModuleName(lib, apiImports.SharedLibs)
-	}
-
-	for idx, lib := range deps.SystemSharedLibs {
-		deps.SystemSharedLibs[idx] = GetReplaceModuleName(lib, apiImports.SharedLibs)
-	}
-
-	for idx, lib := range deps.ReexportSharedLibHeaders {
-		deps.ReexportSharedLibHeaders[idx] = GetReplaceModuleName(lib, apiImports.SharedLibs)
-	}
-
-	return deps
+	return nonVariantLibs, variantLibs
 }
 
 func (c *Module) DepsMutator(actx android.BottomUpMutatorContext) {
@@ -2354,8 +2349,15 @@
 	deps := c.deps(ctx)
 	apiImportInfo := GetApiImports(c, actx)
 
+	apiNdkLibs := []string{}
+	apiLateNdkLibs := []string{}
+
 	if ctx.Os() == android.Android && c.Target().NativeBridge != android.NativeBridgeEnabled {
-		deps = updateDepsWithApiImports(deps, apiImportInfo)
+		deps.SharedLibs, apiNdkLibs = rewriteLibsForApiImports(c, deps.SharedLibs, apiImportInfo.SharedLibs, ctx.Config())
+		deps.LateSharedLibs, apiLateNdkLibs = rewriteLibsForApiImports(c, deps.LateSharedLibs, apiImportInfo.SharedLibs, ctx.Config())
+		deps.SystemSharedLibs, _ = rewriteLibsForApiImports(c, deps.SystemSharedLibs, apiImportInfo.SharedLibs, ctx.Config())
+		deps.ReexportHeaderLibHeaders, _ = rewriteLibsForApiImports(c, deps.ReexportHeaderLibHeaders, apiImportInfo.SharedLibs, ctx.Config())
+		deps.ReexportSharedLibHeaders, _ = rewriteLibsForApiImports(c, deps.ReexportSharedLibHeaders, apiImportInfo.SharedLibs, ctx.Config())
 	}
 
 	c.Properties.AndroidMkSystemSharedLibs = deps.SystemSharedLibs
@@ -2542,12 +2544,20 @@
 		{Mutator: "version", Variation: version},
 		{Mutator: "link", Variation: "shared"},
 	}, ndkStubDepTag, variantNdkLibs...)
+	actx.AddVariationDependencies([]blueprint.Variation{
+		{Mutator: "version", Variation: version},
+		{Mutator: "link", Variation: "shared"},
+	}, ndkStubDepTag, apiNdkLibs...)
 
 	ndkLateStubDepTag := libraryDependencyTag{Kind: sharedLibraryDependency, Order: lateLibraryDependency, ndk: true, makeSuffix: "." + version}
 	actx.AddVariationDependencies([]blueprint.Variation{
 		{Mutator: "version", Variation: version},
 		{Mutator: "link", Variation: "shared"},
 	}, ndkLateStubDepTag, variantLateNdkLibs...)
+	actx.AddVariationDependencies([]blueprint.Variation{
+		{Mutator: "version", Variation: version},
+		{Mutator: "link", Variation: "shared"},
+	}, ndkLateStubDepTag, apiLateNdkLibs...)
 
 	if vndkdep := c.vndkdep; vndkdep != nil {
 		if vndkdep.isVndkExt() {
@@ -2601,6 +2611,10 @@
 		}
 		return
 	}
+	// TODO(b/244244438) : Remove this once all variants are implemented
+	if ccFrom, ok := from.(*Module); ok && ccFrom.isImportedApiLibrary() {
+		return
+	}
 	if from.SdkVersion() == "" {
 		// Platform code can link to anything
 		return
@@ -2627,6 +2641,10 @@
 			// the NDK.
 			return
 		}
+		if c.isImportedApiLibrary() {
+			// Imported library from the API surface is a stub library built against interface definition.
+			return
+		}
 	}
 
 	if strings.HasPrefix(ctx.ModuleName(), "libclang_rt.") && to.Module().Name() == "libc++" {
diff --git a/cc/config/global.go b/cc/config/global.go
index 8047d8e..61151d1 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -222,7 +222,6 @@
 		// http://b/145211066
 		"-Wno-implicit-int-float-conversion",
 		// New warnings to be fixed after clang-r377782.
-		"-Wno-sizeof-array-div",             // http://b/148815709
 		"-Wno-tautological-overlap-compare", // http://b/148815696
 		// New warnings to be fixed after clang-r383902.
 		"-Wno-deprecated-copy",                      // http://b/153746672
@@ -242,9 +241,15 @@
 		// New warnings to be fixed after clang-r468909
 		"-Wno-error=deprecated-builtins", // http://b/241601211
 		"-Wno-error=deprecated",          // in external/googletest/googletest
+		// New warnings to be fixed after clang-r475365
+		"-Wno-error=single-bit-bitfield-constant-conversion", // http://b/243965903
+		"-Wno-error=incompatible-function-pointer-types",     // http://b/257101299
+		"-Wno-error=enum-constexpr-conversion",               // http://b/243964282
 	}
 
 	noOverrideExternalGlobalCflags = []string{
+		// http://b/148815709
+		"-Wno-sizeof-array-div",
 		// http://b/197240255
 		"-Wno-unused-but-set-variable",
 		"-Wno-unused-but-set-parameter",
@@ -293,8 +298,6 @@
 	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{
@@ -308,8 +311,8 @@
 
 	// prebuilts/clang default settings.
 	ClangDefaultBase         = "prebuilts/clang/host"
-	ClangDefaultVersion      = "clang-r468909b"
-	ClangDefaultShortVersion = "15.0.3"
+	ClangDefaultVersion      = "clang-r475365"
+	ClangDefaultShortVersion = "16.0.1"
 
 	// Directories with warnings from Android.bp files.
 	WarningAllowedProjects = []string{
@@ -350,6 +353,7 @@
 			// Default to zero initialization.
 			"-ftrivial-auto-var-init=zero",
 			"-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang",
+			"-Wno-unused-command-line-argument",
 		}...)
 	exportedVars.ExportStringList("CommonGlobalCflags", bazelCommonGlobalCflags)
 
@@ -360,14 +364,14 @@
 		// Automatically initialize any uninitialized stack variables.
 		// Prefer zero-init if multiple options are set.
 		if ctx.Config().IsEnvTrue("AUTO_ZERO_INITIALIZE") {
-			flags = append(flags, "-ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang")
+			flags = append(flags, "-ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang -Wno-unused-command-line-argument")
 		} else if ctx.Config().IsEnvTrue("AUTO_PATTERN_INITIALIZE") {
 			flags = append(flags, "-ftrivial-auto-var-init=pattern")
 		} else if ctx.Config().IsEnvTrue("AUTO_UNINITIALIZE") {
 			flags = append(flags, "-ftrivial-auto-var-init=uninitialized")
 		} else {
 			// Default to zero initialization.
-			flags = append(flags, "-ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang")
+			flags = append(flags, "-ftrivial-auto-var-init=zero -enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang -Wno-unused-command-line-argument")
 		}
 
 		// Workaround for ccache with clang.
diff --git a/cc/library.go b/cc/library.go
index 0729ff4..1cad6b9 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -411,13 +411,15 @@
 
 		Additional_linker_inputs: linkerAttrs.additionalLinkerInputs,
 
-		Strip:    stripAttrsFromLinkerAttrs(&linkerAttrs),
-		Features: baseAttributes.features,
+		Strip:                             stripAttrsFromLinkerAttrs(&linkerAttrs),
+		Features:                          baseAttributes.features,
+		bazelCcHeaderAbiCheckerAttributes: bp2buildParseAbiCheckerProps(ctx, m),
 	}
 
 	if compilerAttrs.stubsSymbolFile != nil && len(compilerAttrs.stubsVersions.Value) > 0 {
 		hasStubs := true
 		sharedTargetAttrs.Has_stubs.SetValue(&hasStubs)
+		sharedTargetAttrs.Stubs_symbol_file = compilerAttrs.stubsSymbolFile
 	}
 
 	sharedTargetAttrs.Suffix = compilerAttrs.suffix
@@ -802,10 +804,7 @@
 	sAbiOutputFile android.OptionalPath
 
 	// Source Abi Diff
-	sAbiDiff android.OptionalPath
-
-	// Source Abi Diff against previous SDK version
-	prevSAbiDiff android.OptionalPath
+	sAbiDiff android.Paths
 
 	// Location of the static library in the sysroot. Empty if the library is
 	// not included in the NDK.
@@ -1735,7 +1734,6 @@
 
 	objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...)
 	objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...)
-
 	objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.StaticLibObjs.sAbiDumpFiles...)
 	objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.WholeStaticLibObjs.sAbiDumpFiles...)
 
@@ -1796,10 +1794,8 @@
 	return library.coverageOutputFile
 }
 
-// pathForVndkRefAbiDump returns an OptionalPath representing the path of the
-// reference abi dump for the given module. This is not guaranteed to be valid.
-func pathForVndkRefAbiDump(ctx android.ModuleInstallPathContext, version, fileName string,
-	isNdk, isVndk, isGzip bool) android.OptionalPath {
+func getRefAbiDumpFile(ctx android.ModuleInstallPathContext,
+	versionedDumpDir, fileName string) android.OptionalPath {
 
 	currentArchType := ctx.Arch().ArchType
 	primaryArchType := ctx.Config().DevicePrimaryArchType()
@@ -1808,73 +1804,34 @@
 		archName += "_" + primaryArchType.String()
 	}
 
+	return android.ExistentPathForSource(ctx, versionedDumpDir, archName, "source-based",
+		fileName+".lsdump")
+}
+
+func getRefAbiDumpDir(isNdk, isVndk bool) string {
 	var dirName string
 	if isNdk {
 		dirName = "ndk"
 	} else if isVndk {
 		dirName = "vndk"
 	} else {
-		dirName = "platform" // opt-in libs
+		dirName = "platform"
 	}
-
-	binderBitness := ctx.DeviceConfig().BinderBitness()
-
-	var ext string
-	if isGzip {
-		ext = ".lsdump.gz"
-	} else {
-		ext = ".lsdump"
-	}
-
-	return android.ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
-		version, binderBitness, archName, "source-based",
-		fileName+ext)
+	return filepath.Join("prebuilts", "abi-dumps", dirName)
 }
 
-func getRefAbiDumpFile(ctx ModuleContext, vndkVersion, fileName string) android.Path {
-	// The logic must be consistent with classifySourceAbiDump.
-	isNdk := ctx.isNdk(ctx.Config())
-	isVndk := ctx.useVndk() && ctx.isVndk()
-
-	refAbiDumpTextFile := pathForVndkRefAbiDump(ctx, vndkVersion, fileName, isNdk, isVndk, false)
-	refAbiDumpGzipFile := pathForVndkRefAbiDump(ctx, vndkVersion, fileName, isNdk, isVndk, true)
-
-	if refAbiDumpTextFile.Valid() {
-		if refAbiDumpGzipFile.Valid() {
-			ctx.ModuleErrorf(
-				"Two reference ABI dump files are found: %q and %q. Please delete the stale one.",
-				refAbiDumpTextFile, refAbiDumpGzipFile)
-			return nil
-		}
-		return refAbiDumpTextFile.Path()
-	}
-	if refAbiDumpGzipFile.Valid() {
-		return unzipRefDump(ctx, refAbiDumpGzipFile.Path(), fileName)
-	}
-	return nil
-}
-
-func prevDumpRefVersion(ctx ModuleContext) int {
+func prevRefAbiDumpVersion(ctx ModuleContext, dumpDir string) int {
 	sdkVersionInt := ctx.Config().PlatformSdkVersion().FinalInt()
 	sdkVersionStr := ctx.Config().PlatformSdkVersion().String()
 
 	if ctx.Config().PlatformSdkFinal() {
 		return sdkVersionInt - 1
 	} else {
-		var dirName string
-
-		isNdk := ctx.isNdk(ctx.Config())
-		if isNdk {
-			dirName = "ndk"
-		} else {
-			dirName = "platform"
-		}
-
 		// The platform SDK version can be upgraded before finalization while the corresponding abi dumps hasn't
 		// been generated. Thus the Cross-Version Check chooses PLATFORM_SDK_VERION - 1 as previous version.
 		// This situation could be identified by checking the existence of the PLATFORM_SDK_VERION dump directory.
-		refDumpDir := android.ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName, sdkVersionStr)
-		if refDumpDir.Valid() {
+		versionedDumpDir := android.ExistentPathForSource(ctx, dumpDir, sdkVersionStr)
+		if versionedDumpDir.Valid() {
 			return sdkVersionInt
 		} else {
 			return sdkVersionInt - 1
@@ -1895,6 +1852,54 @@
 	}
 }
 
+// sourceAbiDiff registers a build statement to compare linked sAbi dump files (.lsdump).
+func (library *libraryDecorator) sourceAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
+	baseName, nameExt string, isLlndkOrNdk, allowExtensions bool,
+	sourceVersion, errorMessage string) {
+
+	sourceDump := library.sAbiOutputFile.Path()
+
+	extraFlags := []string{"-target-version", sourceVersion}
+	if Bool(library.Properties.Header_abi_checker.Check_all_apis) {
+		extraFlags = append(extraFlags, "-check-all-apis")
+	} else {
+		extraFlags = append(extraFlags,
+			"-allow-unreferenced-changes",
+			"-allow-unreferenced-elf-symbol-changes")
+	}
+	if isLlndkOrNdk {
+		extraFlags = append(extraFlags, "-consider-opaque-types-different")
+	}
+	if allowExtensions {
+		extraFlags = append(extraFlags, "-allow-extensions")
+	}
+	extraFlags = append(extraFlags, library.Properties.Header_abi_checker.Diff_flags...)
+
+	library.sAbiDiff = append(
+		library.sAbiDiff,
+		transformAbiDumpToAbiDiff(ctx, sourceDump, referenceDump,
+			baseName, nameExt, extraFlags, errorMessage))
+}
+
+func (library *libraryDecorator) crossVersionAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
+	baseName string, isLlndkOrNdk bool, sourceVersion, prevVersion string) {
+
+	errorMessage := "error: Please follow https://android.googlesource.com/platform/development/+/master/vndk/tools/header-checker/README.md#configure-cross_version-abi-check to resolve the ABI difference between your source code and version " + prevVersion + "."
+
+	library.sourceAbiDiff(ctx, referenceDump, baseName, prevVersion,
+		isLlndkOrNdk, /* allowExtensions */ true, sourceVersion, errorMessage)
+}
+
+func (library *libraryDecorator) sameVersionAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
+	baseName string, isLlndkOrNdk, allowExtensions bool) {
+
+	libName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
+	errorMessage := "error: Please update ABI references with: $$ANDROID_BUILD_TOP/development/vndk/tools/header-checker/utils/create_reference_dumps.py -l " + libName
+
+	library.sourceAbiDiff(ctx, referenceDump, baseName, /* nameExt */ "",
+		isLlndkOrNdk, allowExtensions, "current", errorMessage)
+}
+
 func (library *libraryDecorator) linkSAbiDumpFiles(ctx ModuleContext, objs Objects, fileName string, soFile android.Path) {
 	if library.sabi.shouldCreateSourceAbiDump() {
 		exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
@@ -1913,31 +1918,31 @@
 
 		addLsdumpPath(classifySourceAbiDump(ctx) + ":" + library.sAbiOutputFile.String())
 
+		// The logic must be consistent with classifySourceAbiDump.
 		isVndk := ctx.useVndk() && ctx.isVndk()
 		isNdk := ctx.isNdk(ctx.Config())
 		isLlndk := ctx.isImplementationForLLNDKPublic()
+		dumpDir := getRefAbiDumpDir(isNdk, isVndk)
+		binderBitness := ctx.DeviceConfig().BinderBitness()
 		// If NDK or PLATFORM library, check against previous version ABI.
 		if !isVndk {
-			prevVersion := prevDumpRefVersion(ctx)
-			prevRefAbiDumpFile := getRefAbiDumpFile(ctx, strconv.Itoa(prevVersion), fileName)
-			if prevRefAbiDumpFile != nil {
-				library.prevSAbiDiff = sourceAbiDiff(ctx, library.sAbiOutputFile.Path(),
-					prevRefAbiDumpFile, fileName,
-					library.Properties.Header_abi_checker.Diff_flags, prevVersion,
-					Bool(library.Properties.Header_abi_checker.Check_all_apis),
-					isLlndk || isNdk, ctx.IsVndkExt(), true)
+			prevVersionInt := prevRefAbiDumpVersion(ctx, dumpDir)
+			prevVersion := strconv.Itoa(prevVersionInt)
+			prevDumpDir := filepath.Join(dumpDir, prevVersion, binderBitness)
+			prevDumpFile := getRefAbiDumpFile(ctx, prevDumpDir, fileName)
+			if prevDumpFile.Valid() {
+				library.crossVersionAbiDiff(ctx, prevDumpFile.Path(),
+					fileName, isLlndk || isNdk,
+					strconv.Itoa(prevVersionInt+1), prevVersion)
 			}
 		}
-
+		// Check against the current version.
 		currVersion := currRefAbiDumpVersion(ctx, isVndk)
-		refAbiDumpFile := getRefAbiDumpFile(ctx, currVersion, fileName)
-		if refAbiDumpFile != nil {
-			library.sAbiDiff = sourceAbiDiff(ctx, library.sAbiOutputFile.Path(),
-				refAbiDumpFile, fileName,
-				library.Properties.Header_abi_checker.Diff_flags,
-				/* unused if not previousVersionDiff */ 0,
-				Bool(library.Properties.Header_abi_checker.Check_all_apis),
-				isLlndk || isNdk, ctx.IsVndkExt(), false)
+		currDumpDir := filepath.Join(dumpDir, currVersion, binderBitness)
+		currDumpFile := getRefAbiDumpFile(ctx, currDumpDir, fileName)
+		if currDumpFile.Valid() {
+			library.sameVersionAbiDiff(ctx, currDumpFile.Path(),
+				fileName, isLlndk || isNdk, ctx.IsVndkExt())
 		}
 	}
 }
@@ -2757,6 +2762,29 @@
 	return outputFile
 }
 
+func bp2buildParseAbiCheckerProps(ctx android.TopDownMutatorContext, module *Module) bazelCcHeaderAbiCheckerAttributes {
+	lib, ok := module.linker.(*libraryDecorator)
+	if !ok {
+		return bazelCcHeaderAbiCheckerAttributes{}
+	}
+
+	abiChecker := lib.Properties.Header_abi_checker
+
+	abiCheckerAttrs := bazelCcHeaderAbiCheckerAttributes{
+		Abi_checker_enabled:                 abiChecker.Enabled,
+		Abi_checker_exclude_symbol_versions: abiChecker.Exclude_symbol_versions,
+		Abi_checker_exclude_symbol_tags:     abiChecker.Exclude_symbol_tags,
+		Abi_checker_check_all_apis:          abiChecker.Check_all_apis,
+		Abi_checker_diff_flags:              abiChecker.Diff_flags,
+	}
+	if abiChecker.Symbol_file != nil {
+		symbolFile := android.BazelLabelForModuleSrcSingle(ctx, *abiChecker.Symbol_file)
+		abiCheckerAttrs.Abi_checker_symbol_file = &symbolFile
+	}
+
+	return abiCheckerAttrs
+}
+
 func sharedOrStaticLibraryBp2Build(ctx android.TopDownMutatorContext, module *Module, isStatic bool) {
 	baseAttributes := bp2BuildParseBaseProps(ctx, module)
 	compilerAttrs := baseAttributes.compilerAttributes
@@ -2863,10 +2891,13 @@
 			Features: baseAttributes.features,
 
 			Suffix: compilerAttrs.suffix,
+
+			bazelCcHeaderAbiCheckerAttributes: bp2buildParseAbiCheckerProps(ctx, module),
 		}
 		if compilerAttrs.stubsSymbolFile != nil && len(compilerAttrs.stubsVersions.Value) > 0 {
 			hasStubs := true
 			sharedLibAttrs.Has_stubs.SetValue(&hasStubs)
+			sharedLibAttrs.Stubs_symbol_file = compilerAttrs.stubsSymbolFile
 		}
 		attrs = sharedLibAttrs
 	}
@@ -2943,11 +2974,14 @@
 
 	Features bazel.StringListAttribute
 
-	Has_stubs bazel.BoolAttribute
+	Has_stubs         bazel.BoolAttribute
+	Stubs_symbol_file *string
 
 	Inject_bssl_hash bazel.BoolAttribute
 
 	Suffix bazel.StringAttribute
+
+	bazelCcHeaderAbiCheckerAttributes
 }
 
 type bazelCcStubSuiteAttributes struct {
@@ -2958,3 +2992,12 @@
 	Soname          *string
 	Deps            bazel.LabelListAttribute
 }
+
+type bazelCcHeaderAbiCheckerAttributes struct {
+	Abi_checker_enabled                 *bool
+	Abi_checker_symbol_file             *bazel.Label
+	Abi_checker_exclude_symbol_versions []string
+	Abi_checker_exclude_symbol_tags     []string
+	Abi_checker_check_all_apis          *bool
+	Abi_checker_diff_flags              []string
+}
diff --git a/cc/library_stub.go b/cc/library_stub.go
index 043c03c..22e61a7 100644
--- a/cc/library_stub.go
+++ b/cc/library_stub.go
@@ -15,14 +15,17 @@
 package cc
 
 import (
+	"regexp"
 	"strings"
 
-	"github.com/google/blueprint/proptools"
-
 	"android/soong/android"
 	"android/soong/multitree"
 )
 
+var (
+	ndkVariantRegex = regexp.MustCompile("ndk\\.([a-zA-Z0-9]+)")
+)
+
 func init() {
 	RegisterLibraryStubBuildComponents(android.InitRegistrationContext)
 }
@@ -45,13 +48,17 @@
 	}
 
 	if m.UseVndk() && apiLibrary.hasLLNDKStubs() {
-		// Add LLNDK dependencies
-		for _, variant := range apiLibrary.properties.Variants {
-			if variant == "llndk" {
-				variantName := BuildApiVariantName(m.BaseModuleName(), "llndk", "")
-				ctx.AddDependency(m, nil, variantName)
-				break
-			}
+		// Add LLNDK variant dependency
+		if inList("llndk", apiLibrary.properties.Variants) {
+			variantName := BuildApiVariantName(m.BaseModuleName(), "llndk", "")
+			ctx.AddDependency(m, nil, variantName)
+		}
+	} else if m.IsSdkVariant() {
+		// Add NDK variant dependencies
+		targetVariant := "ndk." + m.StubsVersion()
+		if inList(targetVariant, apiLibrary.properties.Variants) {
+			variantName := BuildApiVariantName(m.BaseModuleName(), targetVariant, "")
+			ctx.AddDependency(m, nil, variantName)
 		}
 	}
 }
@@ -117,12 +124,31 @@
 	}
 }
 
+func (d *apiLibraryDecorator) linkerInit(ctx BaseModuleContext) {
+	d.baseLinker.linkerInit(ctx)
+
+	if d.hasNDKStubs() {
+		// Set SDK version of module as current
+		ctx.Module().(*Module).Properties.Sdk_version = StringPtr("current")
+
+		// Add NDK stub as NDK known libs
+		name := ctx.ModuleName()
+
+		ndkKnownLibsLock.Lock()
+		ndkKnownLibs := getNDKKnownLibs(ctx.Config())
+		if !inList(name, *ndkKnownLibs) {
+			*ndkKnownLibs = append(*ndkKnownLibs, name)
+		}
+		ndkKnownLibsLock.Unlock()
+	}
+}
+
 func (d *apiLibraryDecorator) link(ctx ModuleContext, flags Flags, deps PathDeps, objects Objects) android.Path {
 	m, _ := ctx.Module().(*Module)
 
 	var in android.Path
 
-	if src := proptools.String(d.properties.Src); src != "" {
+	if src := String(d.properties.Src); src != "" {
 		in = android.PathForModuleSrc(ctx, src)
 	}
 
@@ -149,7 +175,7 @@
 					variantMod.exportProperties.Export_headers...)
 
 				// Export headers as system include dirs if specified. Mostly for libc
-				if proptools.Bool(variantMod.exportProperties.Export_headers_as_system) {
+				if Bool(variantMod.exportProperties.Export_headers_as_system) {
 					d.libraryDecorator.flagExporter.Properties.Export_system_include_dirs = append(
 						d.libraryDecorator.flagExporter.Properties.Export_system_include_dirs,
 						d.libraryDecorator.flagExporter.Properties.Export_include_dirs...)
@@ -157,6 +183,29 @@
 				}
 			}
 		}
+	} else if m.IsSdkVariant() {
+		// NDK Variant
+		apiVariantModule := BuildApiVariantName(m.BaseModuleName(), "ndk", m.StubsVersion())
+
+		var mod android.Module
+
+		ctx.VisitDirectDeps(func(depMod android.Module) {
+			if depMod.Name() == apiVariantModule {
+				mod = depMod
+			}
+		})
+
+		if mod != nil {
+			variantMod, ok := mod.(*CcApiVariant)
+			if ok {
+				in = variantMod.Src()
+
+				// Copy NDK properties to cc_api_library module
+				d.libraryDecorator.flagExporter.Properties.Export_include_dirs = append(
+					d.libraryDecorator.flagExporter.Properties.Export_include_dirs,
+					variantMod.exportProperties.Export_headers...)
+			}
+		}
 	}
 
 	// Flags reexported from dependencies. (e.g. vndk_prebuilt_shared)
@@ -214,6 +263,14 @@
 
 	// TODO(b/244244438) Create more version information for NDK and APEX variations
 	// NDK variants
+
+	if m.IsSdkVariant() {
+		// TODO(b/249193999) Do not check if module has NDK stubs once all NDK cc_api_library contains ndk variant of cc_api_variant.
+		if d.hasNDKStubs() {
+			return d.getNdkVersions()
+		}
+	}
+
 	if m.MinSdkVersion() == "" {
 		return nil
 	}
@@ -229,14 +286,30 @@
 }
 
 func (d *apiLibraryDecorator) hasLLNDKStubs() bool {
+	return inList("llndk", d.properties.Variants)
+}
+
+func (d *apiLibraryDecorator) hasNDKStubs() bool {
 	for _, variant := range d.properties.Variants {
-		if strings.Contains(variant, "llndk") {
+		if ndkVariantRegex.MatchString(variant) {
 			return true
 		}
 	}
 	return false
 }
 
+func (d *apiLibraryDecorator) getNdkVersions() []string {
+	ndkVersions := []string{}
+
+	for _, variant := range d.properties.Variants {
+		if match := ndkVariantRegex.FindStringSubmatch(variant); len(match) == 2 {
+			ndkVersions = append(ndkVersions, match[1])
+		}
+	}
+
+	return ndkVersions
+}
+
 // 'cc_api_headers' is similar with 'cc_api_library', but which replaces
 // header libraries. The module will replace any dependencies to existing
 // original header libraries.
@@ -320,18 +393,18 @@
 func (v *CcApiVariant) GenerateAndroidBuildActions(ctx android.ModuleContext) {
 	// No need to build
 
-	if proptools.String(v.properties.Src) == "" {
+	if String(v.properties.Src) == "" {
 		ctx.PropertyErrorf("src", "src is a required property")
 	}
 
 	// Skip the existence check of the stub prebuilt file.
 	// The file is not guaranteed to exist during Soong analysis.
 	// Build orchestrator will be responsible for creating a connected ninja graph.
-	v.src = android.MaybeExistentPathForSource(ctx, ctx.ModuleDir(), proptools.String(v.properties.Src))
+	v.src = android.MaybeExistentPathForSource(ctx, ctx.ModuleDir(), String(v.properties.Src))
 }
 
 func (v *CcApiVariant) Name() string {
-	version := proptools.String(v.properties.Version)
+	version := String(v.properties.Version)
 	return BuildApiVariantName(v.BaseModuleName(), *v.properties.Variant, version)
 }
 
@@ -349,8 +422,10 @@
 }
 
 // Implement ImageInterface to generate image variants
-func (v *CcApiVariant) ImageMutatorBegin(ctx android.BaseModuleContext)               {}
-func (v *CcApiVariant) CoreVariantNeeded(ctx android.BaseModuleContext) bool          { return false }
+func (v *CcApiVariant) ImageMutatorBegin(ctx android.BaseModuleContext) {}
+func (v *CcApiVariant) CoreVariantNeeded(ctx android.BaseModuleContext) bool {
+	return String(v.properties.Variant) == "ndk"
+}
 func (v *CcApiVariant) RamdiskVariantNeeded(ctx android.BaseModuleContext) bool       { return false }
 func (v *CcApiVariant) VendorRamdiskVariantNeeded(ctx android.BaseModuleContext) bool { return false }
 func (v *CcApiVariant) DebugRamdiskVariantNeeded(ctx android.BaseModuleContext) bool  { return false }
@@ -359,7 +434,7 @@
 	var variations []string
 	platformVndkVersion := ctx.DeviceConfig().PlatformVndkVersion()
 
-	if proptools.String(v.properties.Variant) == "llndk" {
+	if String(v.properties.Variant) == "llndk" {
 		variations = append(variations, VendorVariationPrefix+platformVndkVersion)
 		variations = append(variations, ProductVariationPrefix+platformVndkVersion)
 	}
diff --git a/cc/library_stub_test.go b/cc/library_stub_test.go
index 8ce74c4..e372860 100644
--- a/cc/library_stub_test.go
+++ b/cc/library_stub_test.go
@@ -322,16 +322,188 @@
 
 	ctx := prepareForCcTest.RunTestWithBp(t, bp)
 
-	libfoo := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Module()
+	binfoo := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Module()
 	libbarApiImport := ctx.ModuleForTests("libbar.apiimport", "android_vendor.29_arm64_armv8-a_shared").Module()
 	libbarApiVariant := ctx.ModuleForTests("libbar.llndk.apiimport", "android_vendor.29_arm64_armv8-a").Module()
 
-	android.AssertBoolEquals(t, "Stub library from API surface should be linked", true, hasDirectDependency(t, ctx, libfoo, libbarApiImport))
+	android.AssertBoolEquals(t, "Stub library from API surface should be linked", true, hasDirectDependency(t, ctx, binfoo, libbarApiImport))
 	android.AssertBoolEquals(t, "Stub library variant from API surface should be linked", true, hasDirectDependency(t, ctx, libbarApiImport, libbarApiVariant))
 
-	libFooLibFlags := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Rule("ld").Args["libFlags"]
-	android.AssertStringDoesContain(t, "Vendor binary should be linked with LLNDK variant source", libFooLibFlags, "libbar_llndk.so")
+	binFooLibFlags := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Rule("ld").Args["libFlags"]
+	android.AssertStringDoesContain(t, "Vendor binary should be linked with LLNDK variant source", binFooLibFlags, "libbar_llndk.so")
 
-	libFooCFlags := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Rule("cc").Args["cFlags"]
-	android.AssertStringDoesContain(t, "Vendor binary should include headers from the LLNDK variant source", libFooCFlags, "-Ilibbar_llndk_include")
+	binFooCFlags := ctx.ModuleForTests("binfoo", "android_vendor.29_arm64_armv8-a").Rule("cc").Args["cFlags"]
+	android.AssertStringDoesContain(t, "Vendor binary should include headers from the LLNDK variant source", binFooCFlags, "-Ilibbar_llndk_include")
+}
+
+func TestApiLibraryWithNdkVariant(t *testing.T) {
+	bp := `
+		cc_binary {
+			name: "binfoo",
+			sdk_version: "29",
+			srcs: ["binfoo.cc"],
+			shared_libs: ["libbar"],
+			stl: "c++_shared",
+		}
+
+		cc_binary {
+			name: "binbaz",
+			sdk_version: "30",
+			srcs: ["binbaz.cc"],
+			shared_libs: ["libbar"],
+			stl: "c++_shared",
+		}
+
+		cc_api_library {
+			name: "libbar",
+			// TODO(b/244244438) Remove src property once all variants are implemented.
+			src: "libbar.so",
+			variants: [
+				"ndk.29",
+				"ndk.30",
+				"ndk.current",
+			],
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "29",
+			src: "libbar_ndk_29.so",
+			export_headers: ["libbar_ndk_29_include"]
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "30",
+			src: "libbar_ndk_30.so",
+			export_headers: ["libbar_ndk_30_include"]
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "current",
+			src: "libbar_ndk_current.so",
+			export_headers: ["libbar_ndk_current_include"]
+		}
+
+		api_imports {
+			name: "api_imports",
+			shared_libs: [
+				"libbar",
+			],
+			header_libs: [],
+		}
+	`
+
+	ctx := prepareForCcTest.RunTestWithBp(t, bp)
+
+	binfoo := ctx.ModuleForTests("binfoo", "android_arm64_armv8-a_sdk").Module()
+	libbarApiImportv29 := ctx.ModuleForTests("libbar.apiimport", "android_arm64_armv8-a_sdk_shared_29").Module()
+	libbarApiVariantv29 := ctx.ModuleForTests("libbar.ndk.29.apiimport", "android_arm64_armv8-a_sdk").Module()
+	libbarApiImportv30 := ctx.ModuleForTests("libbar.apiimport", "android_arm64_armv8-a_sdk_shared_30").Module()
+	libbarApiVariantv30 := ctx.ModuleForTests("libbar.ndk.30.apiimport", "android_arm64_armv8-a_sdk").Module()
+
+	android.AssertBoolEquals(t, "Stub library from API surface should be linked with target version", true, hasDirectDependency(t, ctx, binfoo, libbarApiImportv29))
+	android.AssertBoolEquals(t, "Stub library variant from API surface should be linked with target version", true, hasDirectDependency(t, ctx, libbarApiImportv29, libbarApiVariantv29))
+	android.AssertBoolEquals(t, "Stub library from API surface should not be linked with different version", false, hasDirectDependency(t, ctx, binfoo, libbarApiImportv30))
+	android.AssertBoolEquals(t, "Stub library variant from API surface should not be linked with different version", false, hasDirectDependency(t, ctx, libbarApiImportv29, libbarApiVariantv30))
+
+	binbaz := ctx.ModuleForTests("binbaz", "android_arm64_armv8-a_sdk").Module()
+
+	android.AssertBoolEquals(t, "Stub library from API surface should be linked with target version", true, hasDirectDependency(t, ctx, binbaz, libbarApiImportv30))
+	android.AssertBoolEquals(t, "Stub library from API surface should not be linked with different version", false, hasDirectDependency(t, ctx, binbaz, libbarApiImportv29))
+
+	binFooLibFlags := ctx.ModuleForTests("binfoo", "android_arm64_armv8-a_sdk").Rule("ld").Args["libFlags"]
+	android.AssertStringDoesContain(t, "Binary using sdk should be linked with NDK variant source", binFooLibFlags, "libbar_ndk_29.so")
+
+	binFooCFlags := ctx.ModuleForTests("binfoo", "android_arm64_armv8-a_sdk").Rule("cc").Args["cFlags"]
+	android.AssertStringDoesContain(t, "Binary using sdk should include headers from the NDK variant source", binFooCFlags, "-Ilibbar_ndk_29_include")
+}
+
+func TestApiLibraryWithMultipleVariants(t *testing.T) {
+	bp := `
+		cc_binary {
+			name: "binfoo",
+			sdk_version: "29",
+			srcs: ["binfoo.cc"],
+			shared_libs: ["libbar"],
+			stl: "c++_shared",
+		}
+
+		cc_binary {
+			name: "binbaz",
+			vendor: true,
+			srcs: ["binbaz.cc"],
+			shared_libs: ["libbar"],
+		}
+
+		cc_api_library {
+			name: "libbar",
+			// TODO(b/244244438) Remove src property once all variants are implemented.
+			src: "libbar.so",
+			vendor_available: true,
+			variants: [
+				"llndk",
+				"ndk.29",
+				"ndk.30",
+				"ndk.current",
+			],
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "29",
+			src: "libbar_ndk_29.so",
+			export_headers: ["libbar_ndk_29_include"]
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "30",
+			src: "libbar_ndk_30.so",
+			export_headers: ["libbar_ndk_30_include"]
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "ndk",
+			version: "current",
+			src: "libbar_ndk_current.so",
+			export_headers: ["libbar_ndk_current_include"]
+		}
+
+		cc_api_variant {
+			name: "libbar",
+			variant: "llndk",
+			src: "libbar_llndk.so",
+			export_headers: ["libbar_llndk_include"]
+		}
+
+		api_imports {
+			name: "api_imports",
+			shared_libs: [
+				"libbar",
+			],
+			header_libs: [],
+		}
+	`
+	ctx := prepareForCcTest.RunTestWithBp(t, bp)
+
+	binfoo := ctx.ModuleForTests("binfoo", "android_arm64_armv8-a_sdk").Module()
+	libbarApiImportv29 := ctx.ModuleForTests("libbar.apiimport", "android_arm64_armv8-a_sdk_shared_29").Module()
+	libbarApiImportLlndk := ctx.ModuleForTests("libbar.apiimport", "android_vendor.29_arm64_armv8-a_shared").Module()
+
+	android.AssertBoolEquals(t, "Binary using SDK should be linked with API library from NDK variant", true, hasDirectDependency(t, ctx, binfoo, libbarApiImportv29))
+	android.AssertBoolEquals(t, "Binary using SDK should not be linked with API library from LLNDK variant", false, hasDirectDependency(t, ctx, binfoo, libbarApiImportLlndk))
+
+	binbaz := ctx.ModuleForTests("binbaz", "android_vendor.29_arm64_armv8-a").Module()
+
+	android.AssertBoolEquals(t, "Vendor binary should be linked with API library from LLNDK variant", true, hasDirectDependency(t, ctx, binbaz, libbarApiImportLlndk))
+	android.AssertBoolEquals(t, "Vendor binary should not be linked with API library from NDK variant", false, hasDirectDependency(t, ctx, binbaz, libbarApiImportv29))
+
 }
diff --git a/cc/ndk_library.go b/cc/ndk_library.go
index d704e32..2473ba2 100644
--- a/cc/ndk_library.go
+++ b/cc/ndk_library.go
@@ -396,14 +396,14 @@
 }
 
 func (this *stubDecorator) diffAbi(ctx ModuleContext) {
-	missingPrebuiltError := fmt.Sprintf(
-		"Did not find prebuilt ABI dump for %q. Generate with "+
-			"//development/tools/ndk/update_ndk_abi.sh.", this.libraryName(ctx))
-
 	// Catch any ABI changes compared to the checked-in definition of this API
 	// level.
 	abiDiffPath := android.PathForModuleOut(ctx, "abidiff.timestamp")
 	prebuiltAbiDump := this.findPrebuiltAbiDump(ctx, this.apiLevel)
+	missingPrebuiltError := fmt.Sprintf(
+		"Did not find prebuilt ABI dump for %q (%q). Generate with "+
+			"//development/tools/ndk/update_ndk_abi.sh.", this.libraryName(ctx),
+		prebuiltAbiDump.InvalidReason())
 	if !prebuiltAbiDump.Valid() {
 		ctx.Build(pctx, android.BuildParams{
 			Rule:   android.ErrorRule,
diff --git a/cc/sdk.go b/cc/sdk.go
index a0d196b..3e50c9f 100644
--- a/cc/sdk.go
+++ b/cc/sdk.go
@@ -31,6 +31,7 @@
 
 	switch m := ctx.Module().(type) {
 	case LinkableInterface:
+		ccModule, isCcModule := ctx.Module().(*Module)
 		if m.AlwaysSdk() {
 			if !m.UseSdk() && !m.SplitPerApiLevel() {
 				ctx.ModuleErrorf("UseSdk() must return true when AlwaysSdk is set, did the factory forget to set Sdk_version?")
@@ -58,11 +59,32 @@
 				modules[1].(*Module).Properties.PreventInstall = true
 			}
 			ctx.AliasVariation("")
+		} else if isCcModule && ccModule.isImportedApiLibrary() {
+			apiLibrary, _ := ccModule.linker.(*apiLibraryDecorator)
+			if apiLibrary.hasNDKStubs() && ccModule.canUseSdk() {
+				// Handle cc_api_library module with NDK stubs and variants only which can use SDK
+				modules := ctx.CreateVariations("", "sdk")
+				modules[1].(*Module).Properties.IsSdkVariant = true
+				if ctx.Config().UnbundledBuildApps() {
+					// For an unbundled apps build, hide the platform variant from Make.
+					modules[0].(*Module).Properties.HideFromMake = true
+					modules[0].(*Module).Properties.PreventInstall = true
+				} else {
+					// For a platform build, mark the SDK variant so that it gets a ".sdk" suffix when
+					// exposed to Make.
+					modules[1].(*Module).Properties.SdkAndPlatformVariantVisibleToMake = true
+					modules[1].(*Module).Properties.PreventInstall = true
+				}
+			} else {
+				ccModule.Properties.Sdk_version = nil
+				ctx.CreateVariations("")
+				ctx.AliasVariation("")
+			}
 		} else {
-			if m, ok := ctx.Module().(*Module); ok {
+			if isCcModule {
 				// Clear the sdk_version property for modules that don't have an SDK variant so
 				// later code doesn't get confused by it.
-				m.Properties.Sdk_version = nil
+				ccModule.Properties.Sdk_version = nil
 			}
 			ctx.CreateVariations("")
 			ctx.AliasVariation("")
@@ -79,6 +101,11 @@
 	case *snapshotModule:
 		ctx.CreateVariations("")
 	case *CcApiVariant:
-		ctx.CreateVariations("")
+		ccApiVariant, _ := ctx.Module().(*CcApiVariant)
+		if String(ccApiVariant.properties.Variant) == "ndk" {
+			ctx.CreateVariations("sdk")
+		} else {
+			ctx.CreateVariations("")
+		}
 	}
 }
diff --git a/cmd/soong_build/main.go b/cmd/soong_build/main.go
index bc2d5cb..3bc311b 100644
--- a/cmd/soong_build/main.go
+++ b/cmd/soong_build/main.go
@@ -276,6 +276,7 @@
 			src != "BUILD" &&
 			src != "BUILD.bazel" &&
 			!strings.HasPrefix(src, "build/bazel") &&
+			!strings.HasPrefix(src, "external/bazel-skylib") &&
 			!strings.HasPrefix(src, "prebuilts/clang") {
 			ret = append(ret, src)
 		}
@@ -578,6 +579,17 @@
 	// FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
 	excludes = append(excludes, "frameworks/compile/slang")
 
+	// FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink directory that contains a BUILD file.
+	// The bazel files finder code doesn't traverse into symlink dirs, and hence is not aware of this BUILD file and exclude it accordingly
+	// during symlink forest generation when checking against keepExistingBuildFiles allowlist.
+	//
+	// This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
+	// currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
+	//
+	// This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in source symlink dirs according
+	// to the keepExistingBuildFile allowlist.
+	excludes = append(excludes, "prebuilts/clang/host/linux-x86/clang-dev")
+
 	return excludes
 }
 
diff --git a/cmd/soong_build/queryview.go b/cmd/soong_build/queryview.go
index cd1d6fb..a876522 100644
--- a/cmd/soong_build/queryview.go
+++ b/cmd/soong_build/queryview.go
@@ -15,6 +15,7 @@
 package main
 
 import (
+	"io/fs"
 	"io/ioutil"
 	"os"
 	"path/filepath"
@@ -35,6 +36,11 @@
 
 	filesToWrite := bp2build.CreateBazelFiles(ctx.Config(), ruleShims, res.BuildDirToTargets(),
 		ctx.Mode())
+	bazelRcFiles, err2 := CopyBazelRcFiles()
+	if err2 != nil {
+		return err2
+	}
+	filesToWrite = append(filesToWrite, bazelRcFiles...)
 	for _, f := range filesToWrite {
 		if err := writeReadOnlyFile(outDir, f); err != nil {
 			return err
@@ -44,6 +50,32 @@
 	return nil
 }
 
+// CopyBazelRcFiles creates BazelFiles for all the bazelrc files under
+// build/bazel. They're needed because the rc files are still read when running
+// queryview, so they have to be in the queryview workspace.
+func CopyBazelRcFiles() ([]bp2build.BazelFile, error) {
+	result := make([]bp2build.BazelFile, 0)
+	err := filepath.WalkDir(filepath.Join(topDir, "build/bazel"), func(path string, info fs.DirEntry, err error) error {
+		if filepath.Ext(path) == ".bazelrc" {
+			contents, err := os.ReadFile(path)
+			if err != nil {
+				return err
+			}
+			path, err = filepath.Rel(topDir, path)
+			if err != nil {
+				return err
+			}
+			result = append(result, bp2build.BazelFile{
+				Dir:      filepath.Dir(path),
+				Basename: filepath.Base(path),
+				Contents: string(contents),
+			})
+		}
+		return nil
+	})
+	return result, err
+}
+
 // The auto-conversion directory should be read-only, sufficient for bazel query. The files
 // are not intended to be edited by end users.
 func writeReadOnlyFile(dir string, f bp2build.BazelFile) error {
diff --git a/java/Android.bp b/java/Android.bp
index 9d63319..27a0a38 100644
--- a/java/Android.bp
+++ b/java/Android.bp
@@ -104,6 +104,7 @@
         "plugin_test.go",
         "prebuilt_apis_test.go",
         "proto_test.go",
+        "resourceshrinker_test.go",
         "rro_test.go",
         "sdk_test.go",
         "sdk_library_test.go",
diff --git a/java/dex.go b/java/dex.go
index de36b18..40ee99d 100644
--- a/java/dex.go
+++ b/java/dex.go
@@ -63,6 +63,7 @@
 		// classes referenced by the app manifest.  Defaults to false.
 		No_aapt_flags *bool
 
+		// If true, optimize for size by removing unused resources. Defaults to false.
 		Shrink_resources *bool
 
 		// Flags to pass to proguard.
diff --git a/java/java.go b/java/java.go
index 6eeb95d..e37a77e 100644
--- a/java/java.go
+++ b/java/java.go
@@ -1662,7 +1662,7 @@
 	var srcFiles []android.Path
 	ctx.VisitDirectDepsWithTag(javaApiContributionTag, func(dep android.Module) {
 		provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo)
-		srcFiles = append(srcFiles, android.PathForModuleSrc(ctx, provider.ApiFile.String()))
+		srcFiles = append(srcFiles, android.PathForSource(ctx, provider.ApiFile.String()))
 	})
 
 	cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir)
@@ -1687,6 +1687,8 @@
 
 	TransformJavaToClasses(ctx, al.stubsJar, 0, android.Paths{},
 		android.Paths{al.stubsSrcJar}, flags, android.Paths{})
+
+	ctx.Phony(ctx.ModuleName(), al.stubsJar)
 }
 
 //
@@ -2620,7 +2622,7 @@
 	if m.properties.Libs != nil {
 
 		// TODO 244210934 ALIX Check if this else statement breaks presubmits get rid of it if it doesn't
-		if strings.HasPrefix(ctx.ModuleType(), "java_binary") {
+		if strings.HasPrefix(ctx.ModuleType(), "java_binary") || strings.HasPrefix(ctx.ModuleType(), "java_library") {
 			for _, d := range m.properties.Libs {
 				neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
 				neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
@@ -2688,12 +2690,21 @@
 		Deps:                 deps,
 		Exports:              depLabels.StaticDeps,
 	}
+	name := m.Name()
 
 	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",
 		}
+
+		ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
+		neverlinkProp := true
+		neverLinkAttrs := &javaLibraryAttributes{
+			Exports:   bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
+			Neverlink: bazel.BoolAttribute{Value: &neverlinkProp},
+		}
+		ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs)
 	} else {
 		attrs.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
 
@@ -2701,10 +2712,10 @@
 			Rule_class:        "kt_jvm_library",
 			Bzl_load_location: "@rules_kotlin//kotlin:jvm_library.bzl",
 		}
+		// TODO (b/244210934): create neverlink-duplicate target once kt_jvm_library supports neverlink attribute
+		ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
 	}
 
-	name := m.Name()
-	ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
 }
 
 type javaBinaryHostAttributes struct {
diff --git a/java/resourceshrinker_test.go b/java/resourceshrinker_test.go
new file mode 100644
index 0000000..3bbf116
--- /dev/null
+++ b/java/resourceshrinker_test.go
@@ -0,0 +1,53 @@
+// Copyright 2022 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 (
+	"testing"
+
+	"android/soong/android"
+)
+
+func TestShrinkResourcesArgs(t *testing.T) {
+	result := android.GroupFixturePreparers(
+		PrepareForTestWithJavaDefaultModules,
+	).RunTestWithBp(t, `
+		android_app {
+			name: "app_shrink",
+			platform_apis: true,
+			optimize: {
+				shrink_resources: true,
+			}
+		}
+
+		android_app {
+			name: "app_no_shrink",
+			platform_apis: true,
+			optimize: {
+				shrink_resources: false,
+			}
+		}
+	`)
+
+	appShrink := result.ModuleForTests("app_shrink", "android_common")
+	appShrinkResources := appShrink.Rule("shrinkResources")
+	android.AssertStringDoesContain(t, "expected shrinker.xml in app_shrink resource shrinker flags",
+		appShrinkResources.Args["raw_resources"], "shrinker.xml")
+
+	appNoShrink := result.ModuleForTests("app_no_shrink", "android_common")
+	if appNoShrink.MaybeRule("shrinkResources").Rule != nil {
+		t.Errorf("unexpected shrinkResources rule for app_no_shrink")
+	}
+}
diff --git a/java/testing.go b/java/testing.go
index 49430ee..ccbb638 100644
--- a/java/testing.go
+++ b/java/testing.go
@@ -74,6 +74,7 @@
 		// Needed for R8 rules on apps
 		"build/make/core/proguard.flags":             nil,
 		"build/make/core/proguard_basic_keeps.flags": nil,
+		"prebuilts/cmdline-tools/shrinker.xml":       nil,
 	}.AddToFixture(),
 )
 
diff --git a/licenses/Android.bp b/licenses/Android.bp
index 54981e1..eabc303 100644
--- a/licenses/Android.bp
+++ b/licenses/Android.bp
@@ -839,84 +839,84 @@
 
 license_kind {
     name: "SPDX-license-identifier-LGPL",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.0",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.0.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.0+",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.0+.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.0-only",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.0-only.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.0-or-later",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.0-or-later.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.1",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.1.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.1+",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.1+.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.1-only",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.1-only.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-2.1-or-later",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-2.1-or-later.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-3.0",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-3.0.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-3.0+",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-3.0+.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-3.0-only",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-3.0-only.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPL-3.0-or-later",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPL-3.0-or-later.html",
 }
 
 license_kind {
     name: "SPDX-license-identifier-LGPLLR",
-    conditions: ["restricted_allows_dynamic_linking"],
+    conditions: ["restricted_if_statically_linked"],
     url: "https://spdx.org/licenses/LGPLLR.html",
 }
 
diff --git a/tests/bp2build_bazel_test.sh b/tests/bp2build_bazel_test.sh
index 32cb003..679ac55 100755
--- a/tests/bp2build_bazel_test.sh
+++ b/tests/bp2build_bazel_test.sh
@@ -65,7 +65,7 @@
   outdir=out2
   trap "rm -rf $outdir" EXIT
   # Modify OUT_DIR in a subshell so it doesn't affect the top level one.
-  (export OUT_DIR=$outdir; run_soong bp2build && run_bazel build --config=bp2build --config=ci //a:g)
+  (export OUT_DIR=$outdir; run_soong bp2build && run_bazel build --config=bp2build //a:g)
 }
 
 test_different_relative_outdir
@@ -87,7 +87,7 @@
   outdir=$(mktemp -t -d st.XXXXX)
   trap 'rm -rf $outdir' EXIT
   # Modify OUT_DIR in a subshell so it doesn't affect the top level one.
-  (export OUT_DIR=$outdir; run_soong bp2build && run_bazel build --config=bp2build --config=ci //a:g)
+  (export OUT_DIR=$outdir; run_soong bp2build && run_bazel build --config=bp2build //a:g)
 }
 
 test_different_absolute_outdir
@@ -146,7 +146,7 @@
   fi
 
   # NOTE: We don't actually use the extra BUILD file for anything here
-  run_bazel build --config=android --config=bp2build --config=ci //foo/...
+  run_bazel build --config=android --package_path=out/soong/workspace //foo/...
 
   local the_answer_file="bazel-out/android_target-fastbuild/bin/foo/convertible_soong_module/the_answer.txt"
   if [[ ! -f "${the_answer_file}" ]]; then
@@ -191,10 +191,10 @@
 
   run_soong bp2build
 
-  run_bazel build --config=android --config=bp2build --config=ci //a:qq
+  run_bazel build --config=android --package_path=out/soong/workspace //a:qq
   local -r output_mtime1=$(stat -c "%y" bazel-bin/a/_objs/qq/qq.o)
 
-  run_bazel build --config=android --config=bp2build --config=ci //a:qq
+  run_bazel build --config=android --package_path=out/soong/workspace //a:qq
   local -r output_mtime2=$(stat -c "%y" bazel-bin/a/_objs/qq/qq.o)
 
   if [[ "$output_mtime1" != "$output_mtime2" ]]; then
@@ -205,7 +205,7 @@
 #define QQ 2
 EOF
 
-  run_bazel build --config=android --config=bp2build --config=ci //a:qq
+  run_bazel build --config=android --package_path=out/soong/workspace //a:qq
   local -r output_mtime3=$(stat -c "%y" bazel-bin/a/_objs/qq/qq.o)
 
   if [[ "$output_mtime1" == "$output_mtime3" ]]; then
diff --git a/tests/run_integration_tests.sh b/tests/run_integration_tests.sh
index dbab7ec..1e07727 100755
--- a/tests/run_integration_tests.sh
+++ b/tests/run_integration_tests.sh
@@ -12,5 +12,4 @@
 
 # The following tests build against the full source tree and don't rely on the
 # mock client.
-# TODO(b/260278287) the bazel server won't shut down for some reason when run on the build server
-# "$TOP/build/soong/tests/apex_comparison_tests.sh"
+"$TOP/build/soong/tests/apex_comparison_tests.sh"