Merge "Annotate dependency tags for dependencies of installed files"
diff --git a/android/Android.bp b/android/Android.bp
index fe0befd..47e941b 100644
--- a/android/Android.bp
+++ b/android/Android.bp
@@ -6,6 +6,7 @@
         "blueprint-bootstrap",
         "soong",
         "soong-android-soongconfig",
+        "soong-bazel",
         "soong-env",
         "soong-shared",
         "soong-ui-metrics_proto",
diff --git a/android/androidmk.go b/android/androidmk.go
index cfd7c91..4adbb22 100644
--- a/android/androidmk.go
+++ b/android/androidmk.go
@@ -417,7 +417,7 @@
 type androidMkSingleton struct{}
 
 func (c *androidMkSingleton) GenerateBuildActions(ctx SingletonContext) {
-	if !ctx.Config().EmbeddedInMake() {
+	if !ctx.Config().KatiEnabled() {
 		return
 	}
 
diff --git a/android/androidmk_test.go b/android/androidmk_test.go
index 10527b9..bb03378 100644
--- a/android/androidmk_test.go
+++ b/android/androidmk_test.go
@@ -78,7 +78,7 @@
 	`
 
 	config := TestConfig(buildDir, nil, bp, nil)
-	config.inMake = true // Enable androidmk Singleton
+	config.katiEnabled = true // Enable androidmk Singleton
 
 	ctx := NewTestContext(config)
 	ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
@@ -250,7 +250,7 @@
 
 	for _, testCase := range testCases {
 		config := TestConfig(buildDir, nil, testCase.bp, nil)
-		config.inMake = true // Enable androidmk Singleton
+		config.katiEnabled = true // Enable androidmk Singleton
 
 		ctx := NewTestContext(config)
 		ctx.RegisterSingletonType("androidmk", AndroidMkSingleton)
diff --git a/android/apex.go b/android/apex.go
index 276f7a4..a4ff0f9 100644
--- a/android/apex.go
+++ b/android/apex.go
@@ -25,32 +25,54 @@
 )
 
 var (
+	// This is the sdk version when APEX was first introduced
 	SdkVersion_Android10 = uncheckedFinalApiLevel(29)
 )
 
-// ApexInfo describes the metadata common to all modules in an apexBundle.
+// ApexInfo describes the metadata about one or more apexBundles that an apex variant of a module is
+// part of.  When an apex variant is created, the variant is associated with one apexBundle. But
+// when multiple apex variants are merged for deduping (see mergeApexVariations), this holds the
+// information about the apexBundles that are merged together.
+// Accessible via `ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)`
 type ApexInfo struct {
-	// Name of the apex variation that this module is mutated into, or "" for
-	// a platform variant.  Note that a module can be included in multiple APEXes,
-	// in which case, the module is mutated into one or more variants, each of
-	// which is for one or more APEXes.
+	// Name of the apex variation that this module (i.e. the apex variant of the module) is
+	// mutated into, or "" for a platform (i.e. non-APEX) variant. Note that a module can be
+	// included in multiple APEXes, in which case, the module is mutated into one or more
+	// variants, each of which is for an APEX. The variants then can later be deduped if they
+	// don't need to be compiled differently. This is an optimization done in
+	// mergeApexVariations.
 	ApexVariationName string
 
-	// Serialized ApiLevel. Use via MinSdkVersion() method. Cannot be stored in
-	// its struct form because this is cloned into properties structs, and
-	// ApiLevel has private members.
+	// Serialized ApiLevel that this module has to support at minimum. Should be accessed via
+	// MinSdkVersion() method. Cannot be stored in its struct form because this is cloned into
+	// properties structs, and ApiLevel has private members.
 	MinSdkVersionStr string
 
-	// True if the module comes from an updatable APEX.
-	Updatable    bool
+	// True if this module comes from an updatable apexBundle.
+	Updatable bool
+
+	// The list of SDK modules that the containing apexBundle depends on.
 	RequiredSdks SdkRefs
 
-	InApexes     []string
+	// List of apexBundles that this apex variant of the module is associated with. Initially,
+	// the size of this list is one because one apex variant is associated with one apexBundle.
+	// When multiple apex variants are merged in mergeApexVariations, ApexInfo struct of the
+	// merged variant holds the list of apexBundles that are merged together.
+	InApexes []string
+
+	// Pointers to the ApexContents struct each of which is for apexBundle modules that this
+	// module is part of. The ApexContents gives information about which modules the apexBundle
+	// has and whether a module became part of the apexBundle via a direct dependency or not.
 	ApexContents []*ApexContents
 }
 
 var ApexInfoProvider = blueprint.NewMutatorProvider(ApexInfo{}, "apex")
 
+// mergedName gives the name of the alias variation that will be used when multiple apex variations
+// of a module can be deduped into one variation. For example, if libfoo is included in both apex.a
+// and apex.b, and if the two APEXes have the same min_sdk_version (say 29), then libfoo doesn't
+// have to be built twice, but only once. In that case, the two apex variations apex.a and apex.b
+// are configured to have the same alias variation named apex29.
 func (i ApexInfo) mergedName(ctx PathContext) string {
 	name := "apex" + strconv.Itoa(i.MinSdkVersion(ctx).FinalOrFutureInt())
 	for _, sdk := range i.RequiredSdks {
@@ -59,14 +81,19 @@
 	return name
 }
 
-func (this *ApexInfo) MinSdkVersion(ctx PathContext) ApiLevel {
-	return ApiLevelOrPanic(ctx, this.MinSdkVersionStr)
+// MinSdkVersion gives the api level that this module has to support at minimum. This is from the
+// min_sdk_version property of the containing apexBundle.
+func (i ApexInfo) MinSdkVersion(ctx PathContext) ApiLevel {
+	return ApiLevelOrPanic(ctx, i.MinSdkVersionStr)
 }
 
+// IsForPlatform tells whether this module is for the platform or not. If false is returned, it
+// means that this apex variant of the module is built for an APEX.
 func (i ApexInfo) IsForPlatform() bool {
 	return i.ApexVariationName == ""
 }
 
+// InApex tells whether this apex variant of the module is part of the given apexBundle or not.
 func (i ApexInfo) InApex(apex string) bool {
 	for _, a := range i.InApexes {
 		if a == apex {
@@ -76,102 +103,111 @@
 	return false
 }
 
-// ApexTestForInfo stores the contents of APEXes for which this module is a test and thus has
-// access to APEX internals.
+// ApexTestForInfo stores the contents of APEXes for which this module is a test - although this
+// module is not part of the APEX - and thus has access to APEX internals.
 type ApexTestForInfo struct {
 	ApexContents []*ApexContents
 }
 
 var ApexTestForInfoProvider = blueprint.NewMutatorProvider(ApexTestForInfo{}, "apex_test_for")
 
-// Extracted from ApexModule to make it easier to define custom subsets of the
-// ApexModule interface and improve code navigation within the IDE.
+// DepIsInSameApex defines an interface that should be used to determine whether a given dependency
+// should be considered as part of the same APEX as the current module or not. Note: this was
+// extracted from ApexModule to make it easier to define custom subsets of the ApexModule interface
+// and improve code navigation within the IDE.
 type DepIsInSameApex interface {
-	// DepIsInSameApex tests if the other module 'dep' is installed to the same
-	// APEX as this module
+	// DepIsInSameApex tests if the other module 'dep' is considered as part of the same APEX as
+	// this module. For example, a static lib dependency usually returns true here, while a
+	// shared lib dependency to a stub library returns false.
 	DepIsInSameApex(ctx BaseModuleContext, dep Module) bool
 }
 
-// ApexModule is the interface that a module type is expected to implement if
-// the module has to be built differently depending on whether the module
-// is destined for an apex or not (installed to one of the regular partitions).
+// ApexModule is the interface that a module type is expected to implement if the module has to be
+// built differently depending on whether the module is destined for an APEX or not (i.e., installed
+// to one of the regular partitions).
 //
-// Native shared libraries are one such module type; when it is built for an
-// APEX, it should depend only on stable interfaces such as NDK, stable AIDL,
-// or C APIs from other APEXs.
+// Native shared libraries are one such module type; when it is built for an APEX, it should depend
+// only on stable interfaces such as NDK, stable AIDL, or C APIs from other APEXes.
 //
-// A module implementing this interface will be mutated into multiple
-// variations by apex.apexMutator if it is directly or indirectly included
-// in one or more APEXs. Specifically, if a module is included in apex.foo and
-// apex.bar then three apex variants are created: platform, apex.foo and
-// apex.bar. The platform variant is for the regular partitions
-// (e.g., /system or /vendor, etc.) while the other two are for the APEXs,
-// respectively.
+// A module implementing this interface will be mutated into multiple variations by apex.apexMutator
+// if it is directly or indirectly included in one or more APEXes. Specifically, if a module is
+// included in apex.foo and apex.bar then three apex variants are created: platform, apex.foo and
+// apex.bar. The platform variant is for the regular partitions (e.g., /system or /vendor, etc.)
+// while the other two are for the APEXs, respectively. The latter two variations can be merged (see
+// mergedName) when the two APEXes have the same min_sdk_version requirement.
 type ApexModule interface {
 	Module
 	DepIsInSameApex
 
 	apexModuleBase() *ApexModuleBase
 
-	// Marks that this module should be built for the specified APEX.
-	// Call this before apex.apexMutator is run.
+	// Marks that this module should be built for the specified APEX. Call this BEFORE
+	// apex.apexMutator is run.
 	BuildForApex(apex ApexInfo)
 
-	// Returns true if this module is present in any APEXes
-	// directly or indirectly.
-	// Call this after apex.apexMutator is run.
+	// Returns true if this module is present in any APEX either directly or indirectly. Call
+	// this after apex.apexMutator is run.
 	InAnyApex() bool
 
-	// Returns true if this module is directly in any APEXes.
-	// Call this after apex.apexMutator is run.
+	// Returns true if this module is directly in any APEX. Call this AFTER apex.apexMutator is
+	// run.
 	DirectlyInAnyApex() bool
 
-	// Returns true if any variant of this module is directly in any APEXes.
-	// Call this after apex.apexMutator is run.
+	// Returns true in the primary variant of a module if _any_ variant of the module is
+	// directly in any apex. This includes host, arch, asan, etc. variants. It is unused in any
+	// variant that is not the primary variant. Ideally this wouldn't be used, as it incorrectly
+	// mixes arch variants if only one arch is in an apex, but a few places depend on it, for
+	// example when an ASAN variant is created before the apexMutator. Call this after
+	// apex.apexMutator is run.
 	AnyVariantDirectlyInAnyApex() bool
 
-	// Tests if this module could have APEX variants. APEX variants are
-	// created only for the modules that returns true here. This is useful
-	// for not creating APEX variants for certain types of shared libraries
-	// such as NDK stubs.
+	// Tests if this module could have APEX variants. Even when a module type implements
+	// ApexModule interface, APEX variants are created only for the module instances that return
+	// true here. This is useful for not creating APEX variants for certain types of shared
+	// libraries such as NDK stubs.
 	CanHaveApexVariants() bool
 
-	// Tests if this module can be installed to APEX as a file. For example,
-	// this would return true for shared libs while return false for static
-	// libs.
+	// Tests if this module can be installed to APEX as a file. For example, this would return
+	// true for shared libs while return false for static libs because static libs are not
+	// installable module (but it can still be mutated for APEX)
 	IsInstallableToApex() bool
 
-	// Tests if this module is available for the specified APEX or ":platform"
+	// Tests if this module is available for the specified APEX or ":platform". This is from the
+	// apex_available property of the module.
 	AvailableFor(what string) bool
 
-	// Return true if this module is not available to platform (i.e. apex_available
-	// property doesn't have "//apex_available:platform"), or shouldn't be available
-	// to platform, which is the case when this module depends on other module that
-	// isn't available to platform.
+	// Returns true if this module is not available to platform (i.e. apex_available property
+	// doesn't have "//apex_available:platform"), or shouldn't be available to platform, which
+	// is the case when this module depends on other module that isn't available to platform.
 	NotAvailableForPlatform() bool
 
-	// Mark that this module is not available to platform. Set by the
+	// Marks that this module is not available to platform. Set by the
 	// check-platform-availability mutator in the apex package.
 	SetNotAvailableForPlatform()
 
-	// List of APEXes that this module tests. The module has access to
-	// the private part of the listed APEXes even when it is not included in the
-	// APEXes.
+	// Returns the list of APEXes that this module is a test for. The module has access to the
+	// private part of the listed APEXes even when it is not included in the APEXes. This by
+	// default returns nil. A module type should override the default implementation. For
+	// example, cc_test module type returns the value of test_for here.
 	TestFor() []string
 
-	// Returns nil if this module supports sdkVersion
-	// Otherwise, returns error with reason
+	// Returns nil (success) if this module should support the given sdk version. Returns an
+	// error if not. No default implementation is provided for this method. A module type
+	// implementing this interface should provide an implementation. A module supports an sdk
+	// version when the module's min_sdk_version is equal to or less than the given sdk version.
 	ShouldSupportSdkVersion(ctx BaseModuleContext, sdkVersion ApiLevel) error
 
-	// Returns true if this module needs a unique variation per apex, for example if
-	// use_apex_name_macro is set.
+	// Returns true if this module needs a unique variation per apex, effectively disabling the
+	// deduping. This is turned on when, for example if use_apex_name_macro is set so that each
+	// apex variant should be built with different macro definitions.
 	UniqueApexVariations() bool
 }
 
+// Properties that are common to all module types implementing ApexModule interface.
 type ApexProperties struct {
-	// Availability of this module in APEXes. Only the listed APEXes can contain
-	// this module. If the module has stubs then other APEXes and the platform may
-	// access it through them (subject to visibility).
+	// Availability of this module in APEXes. Only the listed APEXes can contain this module. If
+	// the module has stubs then other APEXes and the platform may access it through them
+	// (subject to visibility).
 	//
 	// "//apex_available:anyapex" is a pseudo APEX name that matches to any APEX.
 	// "//apex_available:platform" refers to non-APEX partitions like "system.img".
@@ -179,29 +215,23 @@
 	// Default is ["//apex_available:platform"].
 	Apex_available []string
 
-	// AnyVariantDirectlyInAnyApex is true in the primary variant of a module if _any_ variant
-	// of the module is directly in any apex.  This includes host, arch, asan, etc. variants.
-	// It is unused in any variant that is not the primary variant.
-	// Ideally this wouldn't be used, as it incorrectly mixes arch variants if only one arch
-	// is in an apex, but a few places depend on it, for example when an ASAN variant is
-	// created before the apexMutator.
-	AnyVariantDirectlyInAnyApex bool `blueprint:"mutated"`
-
-	// DirectlyInAnyApex is true if any APEX variant (including the "" variant used for the
-	// platform) of this module is directly in any APEX.
-	DirectlyInAnyApex bool `blueprint:"mutated"`
-
-	// DirectlyInAnyApex is true if any APEX variant (including the "" variant used for the
-	// platform) of this module is directly or indirectly in any APEX.
+	// See ApexModule.InAnyApex()
 	InAnyApex bool `blueprint:"mutated"`
 
+	// See ApexModule.DirectlyInAnyApex()
+	DirectlyInAnyApex bool `blueprint:"mutated"`
+
+	// See ApexModule.AnyVariantDirectlyInAnyApex()
+	AnyVariantDirectlyInAnyApex bool `blueprint:"mutated"`
+
+	// See ApexModule.NotAvailableForPlatform()
 	NotAvailableForPlatform bool `blueprint:"mutated"`
 
+	// See ApexModule.UniqueApexVariants()
 	UniqueApexVariationsForDeps bool `blueprint:"mutated"`
 }
 
-// Marker interface that identifies dependencies that are excluded from APEX
-// contents.
+// Marker interface that identifies dependencies that are excluded from APEX contents.
 type ExcludeFromApexContentsTag interface {
 	blueprint.DependencyTag
 
@@ -209,85 +239,122 @@
 	ExcludeFromApexContents()
 }
 
-// Marker interface that identifies dependencies that should inherit the DirectlyInAnyApex
-// state from the parent to the child.  For example, stubs libraries are marked as
-// DirectlyInAnyApex if their implementation is in an apex.
+// Marker interface that identifies dependencies that should inherit the DirectlyInAnyApex state
+// from the parent to the child. For example, stubs libraries are marked as DirectlyInAnyApex if
+// their implementation is in an apex.
 type CopyDirectlyInAnyApexTag interface {
 	blueprint.DependencyTag
 
+	// Method that differentiates this interface from others.
 	CopyDirectlyInAnyApex()
 }
 
-// Provides default implementation for the ApexModule interface. APEX-aware
+// ApexModuleBase provides the default implementation for the ApexModule interface. APEX-aware
 // modules are expected to include this struct and call InitApexModule().
 type ApexModuleBase struct {
 	ApexProperties ApexProperties
 
 	canHaveApexVariants bool
 
-	apexVariationsLock sync.Mutex // protects apexVariations during parallel apexDepsMutator
-	apexVariations     []ApexInfo
+	apexInfos     []ApexInfo
+	apexInfosLock sync.Mutex // protects apexInfos during parallel apexDepsMutator
 }
 
+// Initializes ApexModuleBase struct. Not calling this (even when inheriting from ApexModuleBase)
+// prevents the module from being mutated for apexBundle.
+func InitApexModule(m ApexModule) {
+	base := m.apexModuleBase()
+	base.canHaveApexVariants = true
+
+	m.AddProperties(&base.ApexProperties)
+}
+
+// Implements ApexModule
 func (m *ApexModuleBase) apexModuleBase() *ApexModuleBase {
 	return m
 }
 
+// Implements ApexModule
 func (m *ApexModuleBase) ApexAvailable() []string {
 	return m.ApexProperties.Apex_available
 }
 
-func (m *ApexModuleBase) TestFor() []string {
-	// To be implemented by concrete types inheriting ApexModuleBase
-	return nil
-}
-
-func (m *ApexModuleBase) UniqueApexVariations() bool {
-	return false
-}
-
+// Implements ApexModule
 func (m *ApexModuleBase) BuildForApex(apex ApexInfo) {
-	m.apexVariationsLock.Lock()
-	defer m.apexVariationsLock.Unlock()
-	for _, v := range m.apexVariations {
+	m.apexInfosLock.Lock()
+	defer m.apexInfosLock.Unlock()
+	for _, v := range m.apexInfos {
 		if v.ApexVariationName == apex.ApexVariationName {
 			return
 		}
 	}
-	m.apexVariations = append(m.apexVariations, apex)
+	m.apexInfos = append(m.apexInfos, apex)
 }
 
-func (m *ApexModuleBase) DirectlyInAnyApex() bool {
-	return m.ApexProperties.DirectlyInAnyApex
-}
-
-func (m *ApexModuleBase) AnyVariantDirectlyInAnyApex() bool {
-	return m.ApexProperties.AnyVariantDirectlyInAnyApex
-}
-
+// Implements ApexModule
 func (m *ApexModuleBase) InAnyApex() bool {
 	return m.ApexProperties.InAnyApex
 }
 
+// Implements ApexModule
+func (m *ApexModuleBase) DirectlyInAnyApex() bool {
+	return m.ApexProperties.DirectlyInAnyApex
+}
+
+// Implements ApexModule
+func (m *ApexModuleBase) AnyVariantDirectlyInAnyApex() bool {
+	return m.ApexProperties.AnyVariantDirectlyInAnyApex
+}
+
+// Implements ApexModule
 func (m *ApexModuleBase) CanHaveApexVariants() bool {
 	return m.canHaveApexVariants
 }
 
+// Implements ApexModule
 func (m *ApexModuleBase) IsInstallableToApex() bool {
-	// should be overriden if needed
+	// If needed, this will bel overridden by concrete types inheriting
+	// ApexModuleBase
 	return false
 }
 
+// Implements ApexModule
+func (m *ApexModuleBase) TestFor() []string {
+	// If needed, this will be overridden by concrete types inheriting
+	// ApexModuleBase
+	return nil
+}
+
+// Implements ApexModule
+func (m *ApexModuleBase) UniqueApexVariations() bool {
+	// If needed, this will bel overridden by concrete types inheriting
+	// ApexModuleBase
+	return false
+}
+
+// Implements ApexModule
+func (m *ApexModuleBase) DepIsInSameApex(ctx BaseModuleContext, dep Module) bool {
+	// By default, if there is a dependency from A to B, we try to include both in the same
+	// APEX, unless B is explicitly from outside of the APEX (i.e. a stubs lib). Thus, returning
+	// true. This is overridden by some module types like apex.ApexBundle, cc.Module,
+	// java.Module, etc.
+	return true
+}
+
 const (
 	AvailableToPlatform = "//apex_available:platform"
 	AvailableToAnyApex  = "//apex_available:anyapex"
 	AvailableToGkiApex  = "com.android.gki.*"
 )
 
+// CheckAvailableForApex provides the default algorithm for checking the apex availability. When the
+// availability is empty, it defaults to ["//apex_available:platform"] which means "available to the
+// platform but not available to any APEX". When the list is not empty, `what` is matched against
+// the list. If there is any matching element in the list, thus function returns true. The special
+// availability "//apex_available:anyapex" matches with anything except for
+// "//apex_available:platform".
 func CheckAvailableForApex(what string, apex_available []string) bool {
 	if len(apex_available) == 0 {
-		// apex_available defaults to ["//apex_available:platform"],
-		// which means 'available to the platform but no apexes'.
 		return what == AvailableToPlatform
 	}
 	return InList(what, apex_available) ||
@@ -295,25 +362,22 @@
 		(strings.HasPrefix(what, "com.android.gki.") && InList(AvailableToGkiApex, apex_available))
 }
 
+// Implements ApexModule
 func (m *ApexModuleBase) AvailableFor(what string) bool {
 	return CheckAvailableForApex(what, m.ApexProperties.Apex_available)
 }
 
+// Implements ApexModule
 func (m *ApexModuleBase) NotAvailableForPlatform() bool {
 	return m.ApexProperties.NotAvailableForPlatform
 }
 
+// Implements ApexModule
 func (m *ApexModuleBase) SetNotAvailableForPlatform() {
 	m.ApexProperties.NotAvailableForPlatform = true
 }
 
-func (m *ApexModuleBase) DepIsInSameApex(ctx BaseModuleContext, dep Module) bool {
-	// By default, if there is a dependency from A to B, we try to include both in the same APEX,
-	// unless B is explicitly from outside of the APEX (i.e. a stubs lib). Thus, returning true.
-	// This is overridden by some module types like apex.ApexBundle, cc.Module, java.Module, etc.
-	return true
-}
-
+// This function makes sure that the apex_available property is valid
 func (m *ApexModuleBase) checkApexAvailableProperty(mctx BaseModuleContext) {
 	for _, n := range m.ApexProperties.Apex_available {
 		if n == AvailableToPlatform || n == AvailableToAnyApex || n == AvailableToGkiApex {
@@ -331,22 +395,23 @@
 func (a byApexName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
 func (a byApexName) Less(i, j int) bool { return a[i].ApexVariationName < a[j].ApexVariationName }
 
-// mergeApexVariations deduplicates APEX variations that would build identically into a common
-// variation.  It returns the reduced list of variations and a list of aliases from the original
+// mergeApexVariations deduplicates apex variations that would build identically into a common
+// variation. It returns the reduced list of variations and a list of aliases from the original
 // variation names to the new variation names.
-func mergeApexVariations(ctx PathContext, apexVariations []ApexInfo) (merged []ApexInfo, aliases [][2]string) {
-	sort.Sort(byApexName(apexVariations))
+func mergeApexVariations(ctx PathContext, apexInfos []ApexInfo) (merged []ApexInfo, aliases [][2]string) {
+	sort.Sort(byApexName(apexInfos))
 	seen := make(map[string]int)
-	for _, apexInfo := range apexVariations {
+	for _, apexInfo := range apexInfos {
 		apexName := apexInfo.ApexVariationName
 		mergedName := apexInfo.mergedName(ctx)
 		if index, exists := seen[mergedName]; exists {
+			// Variants having the same mergedName are deduped
 			merged[index].InApexes = append(merged[index].InApexes, apexName)
 			merged[index].ApexContents = append(merged[index].ApexContents, apexInfo.ApexContents...)
 			merged[index].Updatable = merged[index].Updatable || apexInfo.Updatable
 		} else {
 			seen[mergedName] = len(merged)
-			apexInfo.ApexVariationName = apexInfo.mergedName(ctx)
+			apexInfo.ApexVariationName = mergedName
 			apexInfo.InApexes = CopyOf(apexInfo.InApexes)
 			apexInfo.ApexContents = append([]*ApexContents(nil), apexInfo.ApexContents...)
 			merged = append(merged, apexInfo)
@@ -356,75 +421,78 @@
 	return merged, aliases
 }
 
+// CreateApexVariations mutates a given module into multiple apex variants each of which is for an
+// apexBundle (and/or the platform) where the module is part of.
 func CreateApexVariations(mctx BottomUpMutatorContext, module ApexModule) []Module {
 	base := module.apexModuleBase()
-	if len(base.apexVariations) > 0 {
-		base.checkApexAvailableProperty(mctx)
 
-		var apexVariations []ApexInfo
-		var aliases [][2]string
-		if !mctx.Module().(ApexModule).UniqueApexVariations() && !base.ApexProperties.UniqueApexVariationsForDeps {
-			apexVariations, aliases = mergeApexVariations(mctx, base.apexVariations)
-		} else {
-			apexVariations = base.apexVariations
-		}
-		// base.apexVariations is only needed to propagate the list of apexes from
-		// apexDepsMutator to apexMutator.  It is no longer accurate after
-		// mergeApexVariations, and won't be copied to all but the first created
-		// variant.  Clear it so it doesn't accidentally get used later.
-		base.apexVariations = nil
-
-		sort.Sort(byApexName(apexVariations))
-		variations := []string{}
-		variations = append(variations, "") // Original variation for platform
-		for _, apex := range apexVariations {
-			variations = append(variations, apex.ApexVariationName)
-		}
-
-		defaultVariation := ""
-		mctx.SetDefaultDependencyVariation(&defaultVariation)
-
-		var inApex ApexMembership
-		for _, a := range apexVariations {
-			for _, apexContents := range a.ApexContents {
-				inApex = inApex.merge(apexContents.contents[mctx.ModuleName()])
-			}
-		}
-
-		base.ApexProperties.InAnyApex = true
-		base.ApexProperties.DirectlyInAnyApex = inApex == directlyInApex
-
-		modules := mctx.CreateVariations(variations...)
-		for i, mod := range modules {
-			platformVariation := i == 0
-			if platformVariation && !mctx.Host() && !mod.(ApexModule).AvailableFor(AvailableToPlatform) {
-				// Do not install the module for platform, but still allow it to output
-				// uninstallable AndroidMk entries in certain cases when they have
-				// side effects.
-				mod.MakeUninstallable()
-			}
-			if !platformVariation {
-				mctx.SetVariationProvider(mod, ApexInfoProvider, apexVariations[i-1])
-			}
-		}
-
-		for _, alias := range aliases {
-			mctx.CreateAliasVariation(alias[0], alias[1])
-		}
-
-		return modules
+	// Shortcut
+	if len(base.apexInfos) == 0 {
+		return nil
 	}
-	return nil
+
+	// Do some validity checks.
+	// TODO(jiyong): is this the right place?
+	base.checkApexAvailableProperty(mctx)
+
+	var apexInfos []ApexInfo
+	var aliases [][2]string
+	if !mctx.Module().(ApexModule).UniqueApexVariations() && !base.ApexProperties.UniqueApexVariationsForDeps {
+		apexInfos, aliases = mergeApexVariations(mctx, base.apexInfos)
+	} else {
+		apexInfos = base.apexInfos
+	}
+	// base.apexInfos is only needed to propagate the list of apexes from apexDepsMutator to
+	// apexMutator. It is no longer accurate after mergeApexVariations, and won't be copied to
+	// all but the first created variant. Clear it so it doesn't accidentally get used later.
+	base.apexInfos = nil
+	sort.Sort(byApexName(apexInfos))
+
+	var inApex ApexMembership
+	for _, a := range apexInfos {
+		for _, apexContents := range a.ApexContents {
+			inApex = inApex.merge(apexContents.contents[mctx.ModuleName()])
+		}
+	}
+	base.ApexProperties.InAnyApex = true
+	base.ApexProperties.DirectlyInAnyApex = inApex == directlyInApex
+
+	defaultVariation := ""
+	mctx.SetDefaultDependencyVariation(&defaultVariation)
+
+	variations := []string{defaultVariation}
+	for _, a := range apexInfos {
+		variations = append(variations, a.ApexVariationName)
+	}
+	modules := mctx.CreateVariations(variations...)
+	for i, mod := range modules {
+		platformVariation := i == 0
+		if platformVariation && !mctx.Host() && !mod.(ApexModule).AvailableFor(AvailableToPlatform) {
+			// Do not install the module for platform, but still allow it to output
+			// uninstallable AndroidMk entries in certain cases when they have side
+			// effects.  TODO(jiyong): move this routine to somewhere else
+			mod.MakeUninstallable()
+		}
+		if !platformVariation {
+			mctx.SetVariationProvider(mod, ApexInfoProvider, apexInfos[i-1])
+		}
+	}
+
+	for _, alias := range aliases {
+		mctx.CreateAliasVariation(alias[0], alias[1])
+	}
+
+	return modules
 }
 
-// UpdateUniqueApexVariationsForDeps sets UniqueApexVariationsForDeps if any dependencies
-// that are in the same APEX have unique APEX variations so that the module can link against
-// the right variant.
+// UpdateUniqueApexVariationsForDeps sets UniqueApexVariationsForDeps if any dependencies that are
+// in the same APEX have unique APEX variations so that the module can link against the right
+// variant.
 func UpdateUniqueApexVariationsForDeps(mctx BottomUpMutatorContext, am ApexModule) {
-	// anyInSameApex returns true if the two ApexInfo lists contain any values in an InApexes list
-	// in common.  It is used instead of DepIsInSameApex because it needs to determine if the dep
-	// is in the same APEX due to being directly included, not only if it is included _because_ it
-	// is a dependency.
+	// anyInSameApex returns true if the two ApexInfo lists contain any values in an InApexes
+	// list in common. It is used instead of DepIsInSameApex because it needs to determine if
+	// the dep is in the same APEX due to being directly included, not only if it is included
+	// _because_ it is a dependency.
 	anyInSameApex := func(a, b []ApexInfo) bool {
 		collectApexes := func(infos []ApexInfo) []string {
 			var ret []string
@@ -446,9 +514,10 @@
 		return false
 	}
 
+	// If any of the dependencies requires unique apex variations, so does this module.
 	mctx.VisitDirectDeps(func(dep Module) {
 		if depApexModule, ok := dep.(ApexModule); ok {
-			if anyInSameApex(depApexModule.apexModuleBase().apexVariations, am.apexModuleBase().apexVariations) &&
+			if anyInSameApex(depApexModule.apexModuleBase().apexInfos, am.apexModuleBase().apexInfos) &&
 				(depApexModule.UniqueApexVariations() ||
 					depApexModule.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps) {
 				am.apexModuleBase().ApexProperties.UniqueApexVariationsForDeps = true
@@ -457,10 +526,10 @@
 	})
 }
 
-// UpdateDirectlyInAnyApex uses the final module to store if any variant of this
-// module is directly in any APEX, and then copies the final value to all the modules.
-// It also copies the DirectlyInAnyApex value to any direct dependencies with a
-// CopyDirectlyInAnyApexTag dependency tag.
+// UpdateDirectlyInAnyApex uses the final module to store if any variant of this module is directly
+// in any APEX, and then copies the final value to all the modules. It also copies the
+// DirectlyInAnyApex value to any direct dependencies with a CopyDirectlyInAnyApexTag dependency
+// tag.
 func UpdateDirectlyInAnyApex(mctx BottomUpMutatorContext, am ApexModule) {
 	base := am.apexModuleBase()
 	// Copy DirectlyInAnyApex and InAnyApex from any direct dependencies with a
@@ -475,14 +544,13 @@
 
 	if base.ApexProperties.DirectlyInAnyApex {
 		// Variants of a module are always visited sequentially in order, so it is safe to
-		// write to another variant of this module.
-		// For a BottomUpMutator the PrimaryModule() is visited first and FinalModule() is
-		// visited last.
+		// write to another variant of this module. For a BottomUpMutator the
+		// PrimaryModule() is visited first and FinalModule() is visited last.
 		mctx.FinalModule().(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex = true
 	}
 
-	// If this is the FinalModule (last visited module) copy AnyVariantDirectlyInAnyApex to
-	// all the other variants
+	// If this is the FinalModule (last visited module) copy
+	// AnyVariantDirectlyInAnyApex to all the other variants
 	if am == mctx.FinalModule().(ApexModule) {
 		mctx.VisitAllModuleVariants(func(variant Module) {
 			variant.(ApexModule).apexModuleBase().ApexProperties.AnyVariantDirectlyInAnyApex =
@@ -491,6 +559,7 @@
 	}
 }
 
+// ApexMembership tells how a module became part of an APEX.
 type ApexMembership int
 
 const (
@@ -499,20 +568,21 @@
 	directlyInApex
 )
 
-// Each apexBundle has an apexContents, and modules in that apex have a provider containing the
-// apexContents of each apexBundle they are part of.
+// ApexContents gives an information about member modules of an apexBundle.  Each apexBundle has an
+// apexContents, and modules in that apex have a provider containing the apexContents of each
+// apexBundle they are part of.
 type ApexContents struct {
-	ApexName string
+	// map from a module name to its membership to this apexBUndle
 	contents map[string]ApexMembership
 }
 
-func NewApexContents(name string, contents map[string]ApexMembership) *ApexContents {
+func NewApexContents(contents map[string]ApexMembership) *ApexContents {
 	return &ApexContents{
-		ApexName: name,
 		contents: contents,
 	}
 }
 
+// Updates an existing membership by adding a new direct (or indirect) membership
 func (i ApexMembership) Add(direct bool) ApexMembership {
 	if direct || i == directlyInApex {
 		return directlyInApex
@@ -520,6 +590,10 @@
 	return indirectlyInApex
 }
 
+// Merges two membership into one. Merging is needed because a module can be a part of an apexBundle
+// in many different paths. For example, it could be dependend on by the apexBundle directly, but at
+// the same time, there might be an indirect dependency to the module. In that case, the more
+// specific dependency (the direct one) is chosen.
 func (i ApexMembership) merge(other ApexMembership) ApexMembership {
 	if other == directlyInApex || i == directlyInApex {
 		return directlyInApex
@@ -531,16 +605,19 @@
 	return notInApex
 }
 
-func (ac *ApexContents) DirectlyInApex(name string) bool {
-	return ac.contents[name] == directlyInApex
+// Tests whether a module named moduleName is directly included in the apexBundle where this
+// ApexContents is tagged.
+func (ac *ApexContents) DirectlyInApex(moduleName string) bool {
+	return ac.contents[moduleName] == directlyInApex
 }
 
-func (ac *ApexContents) InApex(name string) bool {
-	return ac.contents[name] != notInApex
+// Tests whether a module named moduleName is included in the apexBundle where this ApexContent is
+// tagged.
+func (ac *ApexContents) InApex(moduleName string) bool {
+	return ac.contents[moduleName] != notInApex
 }
 
-// Tests whether a module named moduleName is directly depended on by all APEXes
-// in an ApexInfo.
+// Tests whether a module named moduleName is directly depended on by all APEXes in an ApexInfo.
 func DirectlyInAllApexes(apexInfo ApexInfo, moduleName string) bool {
 	for _, contents := range apexInfo.ApexContents {
 		if !contents.DirectlyInApex(moduleName) {
@@ -550,12 +627,15 @@
 	return true
 }
 
-func InitApexModule(m ApexModule) {
-	base := m.apexModuleBase()
-	base.canHaveApexVariants = true
-
-	m.AddProperties(&base.ApexProperties)
-}
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//Below are routines for extra safety checks.
+//
+// BuildDepsInfoLists is to flatten the dependency graph for an apexBundle into a text file
+// (actually two in slightly different formats). The files are mostly for debugging, for example to
+// see why a certain module is included in an APEX via which dependency path.
+//
+// CheckMinSdkVersion is to make sure that all modules in an apexBundle satisfy the min_sdk_version
+// requirement of the apexBundle.
 
 // A dependency info for a single ApexModule, either direct or transitive.
 type ApexModuleDepInfo struct {
@@ -705,7 +785,8 @@
 	WalkPayloadDeps(ctx ModuleContext, do PayloadDepsCallback)
 }
 
-// CheckMinSdkVersion checks if every dependency of an updatable module sets min_sdk_version accordingly
+// CheckMinSdkVersion checks if every dependency of an updatable module sets min_sdk_version
+// accordingly
 func CheckMinSdkVersion(m UpdatableModule, ctx ModuleContext, minSdkVersion ApiLevel) {
 	// do not enforce min_sdk_version for host
 	if ctx.Host() {
@@ -725,8 +806,9 @@
 
 	m.WalkPayloadDeps(ctx, func(ctx ModuleContext, from blueprint.Module, to ApexModule, externalDep bool) bool {
 		if externalDep {
-			// external deps are outside the payload boundary, which is "stable" interface.
-			// We don't have to check min_sdk_version for external dependencies.
+			// external deps are outside the payload boundary, which is "stable"
+			// interface. We don't have to check min_sdk_version for external
+			// dependencies.
 			return false
 		}
 		if am, ok := from.(DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
diff --git a/android/config.go b/android/config.go
index d833c5c..b481cac 100644
--- a/android/config.go
+++ b/android/config.go
@@ -112,7 +112,9 @@
 	envDeps   map[string]string
 	envFrozen bool
 
-	inMake bool
+	// Changes behavior based on whether Kati runs after soong_build, or if soong_build
+	// runs standalone.
+	katiEnabled bool
 
 	captureBuild      bool // true for tests, saves build parameters for each module
 	ignoreEnvironment bool // true for tests, returns empty from all Getenv calls
@@ -228,7 +230,8 @@
 		envCopy[k] = v
 	}
 
-	// Copy the real PATH value to the test environment, it's needed by HostSystemTool() used in x86_darwin_host.go
+	// Copy the real PATH value to the test environment, it's needed by
+	// NonHermeticHostSystemTool() used in x86_darwin_host.go
 	envCopy["PATH"] = originalEnv["PATH"]
 
 	config := &config{
@@ -263,10 +266,6 @@
 
 	config.mockFileSystem(bp, fs)
 
-	if err := config.fromEnv(); err != nil {
-		panic(err)
-	}
-
 	return Config{config}
 }
 
@@ -390,9 +389,9 @@
 		return Config{}, err
 	}
 
-	inMakeFile := filepath.Join(buildDir, ".soong.in_make")
-	if _, err := os.Stat(absolutePath(inMakeFile)); err == nil {
-		config.inMake = true
+	KatiEnabledMarkerFile := filepath.Join(buildDir, ".soong.kati_enabled")
+	if _, err := os.Stat(absolutePath(KatiEnabledMarkerFile)); err == nil {
+		config.katiEnabled = true
 	}
 
 	targets, err := decodeTargetProductVariables(config)
@@ -436,10 +435,6 @@
 		config.AndroidFirstDeviceTarget = firstTarget(config.Targets[Android], "lib64", "lib32")[0]
 	}
 
-	if err := config.fromEnv(); err != nil {
-		return Config{}, err
-	}
-
 	if Bool(config.productVariables.GcovCoverage) && Bool(config.productVariables.ClangCoverage) {
 		return Config{}, fmt.Errorf("GcovCoverage and ClangCoverage cannot both be set")
 	}
@@ -487,17 +482,6 @@
 	c.mockBpList = blueprint.MockModuleListFile
 }
 
-func (c *config) fromEnv() error {
-	switch c.Getenv("EXPERIMENTAL_JAVA_LANGUAGE_LEVEL_9") {
-	case "", "true":
-		// Do nothing
-	default:
-		return fmt.Errorf("The environment variable EXPERIMENTAL_JAVA_LANGUAGE_LEVEL_9 is no longer supported. Java language level 9 is now the global default.")
-	}
-
-	return nil
-}
-
 func (c *config) StopBefore() bootstrap.StopBefore {
 	return c.stopBefore
 }
@@ -530,9 +514,12 @@
 	return PathForOutput(ctx, "host", c.PrebuiltOS(), "framework", path)
 }
 
-// HostSystemTool looks for non-hermetic tools from the system we're running on.
-// Generally shouldn't be used, but useful to find the XCode SDK, etc.
-func (c *config) HostSystemTool(name string) string {
+// NonHermeticHostSystemTool looks for non-hermetic tools from the system we're
+// running on. These tools are not checked-in to AOSP, and therefore could lead
+// to reproducibility problems. Should not be used for other than finding the
+// XCode SDK (xcrun, sw_vers), etc. See ui/build/paths/config.go for the
+// allowlist of host system tools.
+func (c *config) NonHermeticHostSystemTool(name string) string {
 	for _, dir := range filepath.SplitList(c.Getenv("PATH")) {
 		path := filepath.Join(dir, name)
 		if s, err := os.Stat(path); err != nil {
@@ -541,7 +528,10 @@
 			return path
 		}
 	}
-	return name
+	panic(fmt.Errorf(
+		"Unable to use '%s' as a host system tool for build system "+
+			"hermeticity reasons. See build/soong/ui/build/paths/config.go "+
+			"for the full list of allowed host tools on your system.", name))
 }
 
 // PrebuiltOS returns the name of the host OS used in prebuilts directories
@@ -619,8 +609,8 @@
 	return c.envDeps
 }
 
-func (c *config) EmbeddedInMake() bool {
-	return c.inMake
+func (c *config) KatiEnabled() bool {
+	return c.katiEnabled
 }
 
 func (c *config) BuildId() string {
diff --git a/android/filegroup.go b/android/filegroup.go
index 68311e3..9425616 100644
--- a/android/filegroup.go
+++ b/android/filegroup.go
@@ -15,6 +15,7 @@
 package android
 
 import (
+	"android/soong/bazel"
 	"strings"
 )
 
@@ -37,6 +38,9 @@
 	// Create a make variable with the specified name that contains the list of files in the
 	// filegroup, relative to the root of the source tree.
 	Export_to_make_var *string
+
+	// Properties for Bazel migration purposes.
+	bazel.Properties
 }
 
 type fileGroup struct {
diff --git a/android/makevars.go b/android/makevars.go
index f784395..5101436 100644
--- a/android/makevars.go
+++ b/android/makevars.go
@@ -213,7 +213,7 @@
 }
 
 func (s *makeVarsSingleton) GenerateBuildActions(ctx SingletonContext) {
-	if !ctx.Config().EmbeddedInMake() {
+	if !ctx.Config().KatiEnabled() {
 		return
 	}
 
diff --git a/android/module.go b/android/module.go
index 072f41b..bd60829 100644
--- a/android/module.go
+++ b/android/module.go
@@ -1444,7 +1444,7 @@
 
 	if len(deps) > 0 {
 		suffix := ""
-		if ctx.Config().EmbeddedInMake() {
+		if ctx.Config().KatiEnabled() {
 			suffix = "-soong"
 		}
 
@@ -2324,7 +2324,7 @@
 	}
 
 	if m.Device() {
-		if m.Config().EmbeddedInMake() && !m.InstallBypassMake() {
+		if m.Config().KatiEnabled() && !m.InstallBypassMake() {
 			return true
 		}
 
@@ -2377,7 +2377,7 @@
 			Input:       srcPath,
 			Implicits:   implicitDeps,
 			OrderOnly:   orderOnlyDeps,
-			Default:     !m.Config().EmbeddedInMake(),
+			Default:     !m.Config().KatiEnabled(),
 		})
 
 		m.installFiles = append(m.installFiles, fullInstallPath)
@@ -2409,7 +2409,7 @@
 			Description: "install symlink " + fullInstallPath.Base(),
 			Output:      fullInstallPath,
 			Input:       srcPath,
-			Default:     !m.Config().EmbeddedInMake(),
+			Default:     !m.Config().KatiEnabled(),
 			Args: map[string]string{
 				"fromPath": relPath,
 			},
@@ -2440,7 +2440,7 @@
 			Rule:        Symlink,
 			Description: "install symlink " + fullInstallPath.Base() + " -> " + absPath,
 			Output:      fullInstallPath,
-			Default:     !m.Config().EmbeddedInMake(),
+			Default:     !m.Config().KatiEnabled(),
 			Args: map[string]string{
 				"fromPath": absPath,
 			},
@@ -2582,6 +2582,15 @@
 			return nil, fmt.Errorf("failed to get output files from module %q", pathContextName(ctx, module))
 		}
 		return paths, nil
+	} else if sourceFileProducer, ok := module.(SourceFileProducer); ok {
+		if tag != "" {
+			return nil, fmt.Errorf("module %q is a SourceFileProducer, not an OutputFileProducer, and so does not support tag %q", pathContextName(ctx, module), tag)
+		}
+		paths := sourceFileProducer.Srcs()
+		if len(paths) == 0 {
+			return nil, fmt.Errorf("failed to get output files from module %q", pathContextName(ctx, module))
+		}
+		return paths, nil
 	} else {
 		return nil, fmt.Errorf("module %q is not an OutputFileProducer", pathContextName(ctx, module))
 	}
@@ -2669,7 +2678,7 @@
 	})
 
 	suffix := ""
-	if ctx.Config().EmbeddedInMake() {
+	if ctx.Config().KatiEnabled() {
 		suffix = "-soong"
 	}
 
@@ -2677,7 +2686,7 @@
 	ctx.Phony("checkbuild"+suffix, checkbuildDeps...)
 
 	// Make will generate the MODULES-IN-* targets
-	if ctx.Config().EmbeddedInMake() {
+	if ctx.Config().KatiEnabled() {
 		return
 	}
 
diff --git a/android/paths.go b/android/paths.go
index b13979d..a62c9e3 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -1312,7 +1312,7 @@
 
 	ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
 
-	if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
+	if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
 		ret = ret.ToMakePath()
 	}
 
diff --git a/android/phony.go b/android/phony.go
index f8e5a44..0adbb55 100644
--- a/android/phony.go
+++ b/android/phony.go
@@ -53,7 +53,7 @@
 		p.phonyMap[phony] = SortedUniquePaths(p.phonyMap[phony])
 	}
 
-	if !ctx.Config().EmbeddedInMake() {
+	if !ctx.Config().KatiEnabled() {
 		for _, phony := range p.phonyList {
 			ctx.Build(pctx, BuildParams{
 				Rule:      blueprint.Phony,
diff --git a/android/testing.go b/android/testing.go
index 1e2ae13..6539063 100644
--- a/android/testing.go
+++ b/android/testing.go
@@ -424,8 +424,8 @@
 
 }
 
-func SetInMakeForTests(config Config) {
-	config.inMake = true
+func SetKatiEnabledForTests(config Config) {
+	config.katiEnabled = true
 }
 
 func AndroidMkEntriesForTest(t *testing.T, config Config, bpPath string, mod blueprint.Module) []AndroidMkEntries {
diff --git a/apex/androidmk.go b/apex/androidmk.go
index 993260c..fe89b73 100644
--- a/apex/androidmk.go
+++ b/apex/androidmk.go
@@ -36,6 +36,33 @@
 	return a.androidMkForType()
 }
 
+// nameInMake converts apexFileClass into the corresponding class name in Make.
+func (class apexFileClass) nameInMake() string {
+	switch class {
+	case etc:
+		return "ETC"
+	case nativeSharedLib:
+		return "SHARED_LIBRARIES"
+	case nativeExecutable, shBinary, pyBinary, goBinary:
+		return "EXECUTABLES"
+	case javaSharedLib:
+		return "JAVA_LIBRARIES"
+	case nativeTest:
+		return "NATIVE_TESTS"
+	case app, appSet:
+		// b/142537672 Why isn't this APP? We want to have full control over
+		// the paths and file names of the apk file under the flattend APEX.
+		// If this is set to APP, then the paths and file names are modified
+		// by the Make build system. For example, it is installed to
+		// /system/apex/<apexname>/app/<Appname>/<apexname>.<Appname>/ instead of
+		// /system/apex/<apexname>/app/<Appname> because the build system automatically
+		// appends module name (which is <apexname>.<Appname> to the path.
+		return "ETC"
+	default:
+		panic(fmt.Errorf("unknown class %d", class))
+	}
+}
+
 func (a *apexBundle) androidMkForFiles(w io.Writer, apexBundleName, apexName, moduleDir string,
 	apexAndroidMkData android.AndroidMkData) []string {
 
@@ -68,10 +95,10 @@
 
 	var postInstallCommands []string
 	for _, fi := range a.filesInfo {
-		if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
+		if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
 			// TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
-			linkTarget := filepath.Join("/system", fi.Path())
-			linkPath := filepath.Join(a.installDir.ToMakePath().String(), apexBundleName, fi.Path())
+			linkTarget := filepath.Join("/system", fi.path())
+			linkPath := filepath.Join(a.installDir.ToMakePath().String(), apexBundleName, fi.path())
 			mkdirCmd := "mkdir -p " + filepath.Dir(linkPath)
 			linkCmd := "ln -sfn " + linkTarget + " " + linkPath
 			postInstallCommands = append(postInstallCommands, mkdirCmd, linkCmd)
@@ -85,7 +112,7 @@
 			continue
 		}
 
-		linkToSystemLib := a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform()
+		linkToSystemLib := a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform()
 
 		var moduleName string
 		if linkToSystemLib {
@@ -151,7 +178,7 @@
 			fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
 		}
 		fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
-		fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
+		fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.nameInMake())
 		if fi.module != nil {
 			archStr := fi.module.Target().Arch.ArchType.String()
 			host := false
@@ -189,7 +216,7 @@
 			// soong_java_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .jar  Therefore
 			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
 			// we will have foo.jar.jar
-			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.Stem(), ".jar"))
+			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.stem(), ".jar"))
 			if javaModule, ok := fi.module.(java.ApexDependency); ok {
 				fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", javaModule.ImplementationAndResourcesJars()[0].String())
 				fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", javaModule.HeaderJars()[0].String())
@@ -205,7 +232,7 @@
 			// soong_app_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .apk  Therefore
 			// we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
 			// we will have foo.apk.apk
-			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.Stem(), ".apk"))
+			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.stem(), ".apk"))
 			if app, ok := fi.module.(*java.AndroidApp); ok {
 				if jniCoverageOutputs := app.JniCoverageOutputs(); len(jniCoverageOutputs) > 0 {
 					fmt.Fprintln(w, "LOCAL_PREBUILT_COVERAGE_ARCHIVE :=", strings.Join(jniCoverageOutputs.Strings(), " "))
@@ -224,7 +251,7 @@
 			fmt.Fprintln(w, "LOCAL_APKCERTS_FILE :=", as.APKCertsFile().String())
 			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_android_app_set.mk")
 		case nativeSharedLib, nativeExecutable, nativeTest:
-			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.Stem())
+			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.stem())
 			if ccMod, ok := fi.module.(*cc.Module); ok {
 				if ccMod.UnstrippedOutputFile() != nil {
 					fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", ccMod.UnstrippedOutputFile().String())
@@ -236,7 +263,7 @@
 			}
 			fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_cc_prebuilt.mk")
 		default:
-			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.Stem())
+			fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.stem())
 			if fi.builtFile == a.manifestPbOut && apexType == flattenedApex {
 				if a.primaryApexType {
 					// To install companion files (init_rc, vintf_fragments)
diff --git a/apex/apex.go b/apex/apex.go
index ce323ca..a645b06 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -12,6 +12,8 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+// package apex implements build rules for creating the APEX files which are container for
+// lower-level system components. See https://source.android.com/devices/tech/ota/apex
 package apex
 
 import (
@@ -63,57 +65,99 @@
 }
 
 type apexBundleProperties struct {
-	// Json manifest file describing meta info of this APEX bundle. Default:
-	// "apex_manifest.json"
+	// Json manifest file describing meta info of this APEX bundle. Refer to
+	// system/apex/proto/apex_manifest.proto for the schema. Default: "apex_manifest.json"
 	Manifest *string `android:"path"`
 
-	// AndroidManifest.xml file used for the zip container of this APEX bundle.
-	// If unspecified, a default one is automatically generated.
+	// AndroidManifest.xml file used for the zip container of this APEX bundle. If unspecified,
+	// a default one is automatically generated.
 	AndroidManifest *string `android:"path"`
 
-	// Canonical name of the APEX bundle. Used to determine the path to the activated APEX on
-	// device (/apex/<apex_name>).
-	// If unspecified, defaults to the value of name.
+	// Canonical name of this APEX bundle. Used to determine the path to the activated APEX on
+	// device (/apex/<apex_name>). If unspecified, follows the name property.
 	Apex_name *string
 
-	// Determines the file contexts file for setting security context to each file in this APEX bundle.
-	// For platform APEXes, this should points to a file under /system/sepolicy
-	// Default: /system/sepolicy/apex/<module_name>_file_contexts.
+	// Determines the file contexts file for setting the security contexts to files in this APEX
+	// bundle. For platform APEXes, this should points to a file under /system/sepolicy Default:
+	// /system/sepolicy/apex/<module_name>_file_contexts.
 	File_contexts *string `android:"path"`
 
 	ApexNativeDependencies
 
-	// List of java libraries that are embedded inside this APEX bundle
+	Multilib apexMultilibProperties
+
+	// List of java libraries that are embedded inside this APEX bundle.
 	Java_libs []string
 
-	// List of prebuilt files that are embedded inside this APEX bundle
+	// List of prebuilt files that are embedded inside this APEX bundle.
 	Prebuilts []string
 
-	// List of BPF programs inside APEX
+	// List of BPF programs inside this APEX bundle.
 	Bpfs []string
 
-	// Name of the apex_key module that provides the private key to sign APEX
+	// Name of the apex_key module that provides the private key to sign this APEX bundle.
 	Key *string
 
-	// The type of APEX to build. Controls what the APEX payload is. Either
-	// 'image', 'zip' or 'both'. Default: 'image'.
-	Payload_type *string
-
-	// The name of a certificate in the default certificate directory, blank to use the default product certificate,
-	// or an android_app_certificate module name in the form ":module".
+	// Specifies the certificate and the private key to sign the zip container of this APEX. If
+	// this is "foo", foo.x509.pem and foo.pk8 under PRODUCT_DEFAULT_DEV_CERTIFICATE are used
+	// as the certificate and the private key, respectively. If this is ":module", then the
+	// certificate and the private key are provided from the android_app_certificate module
+	// named "module".
 	Certificate *string
 
-	// Whether this APEX is installable to one of the partitions. Default: true.
+	// The minimum SDK version that this APEX must support at minimum. This is usually set to
+	// the SDK version that the APEX was first introduced.
+	Min_sdk_version *string
+
+	// Whether this APEX is considered updatable or not. When set to true, this will enforce
+	// additional rules for making sure that the APEX is truly updatable. To be updatable,
+	// min_sdk_version should be set as well. This will also disable the size optimizations like
+	// symlinking to the system libs. Default is false.
+	Updatable *bool
+
+	// Whether this APEX is installable to one of the partitions like system, vendor, etc.
+	// Default: true.
 	Installable *bool
 
-	// For native libraries and binaries, use the vendor variant instead of the core (platform) variant.
-	// Default is false.
+	// For native libraries and binaries, use the vendor variant instead of the core (platform)
+	// variant. Default is false. DO NOT use this for APEXes that are installed to the system or
+	// system_ext partition.
 	Use_vendor *bool
 
-	// For telling the apex to ignore special handling for system libraries such as bionic. Default is false.
+	// If set true, VNDK libs are considered as stable libs and are not included in this APEX.
+	// Should be only used in non-system apexes (e.g. vendor: true). Default is false.
+	Use_vndk_as_stable *bool
+
+	// List of SDKs that are used to build this APEX. A reference to an SDK should be either
+	// `name#version` or `name` which is an alias for `name#current`. If left empty,
+	// `platform#current` is implied. This value affects all modules included in this APEX. In
+	// other words, they are also built with the SDKs specified here.
+	Uses_sdks []string
+
+	// The type of APEX to build. Controls what the APEX payload is. Either 'image', 'zip' or
+	// 'both'. When set to image, contents are stored in a filesystem image inside a zip
+	// container. When set to zip, contents are stored in a zip container directly. This type is
+	// mostly for host-side debugging. When set to both, the two types are both built. Default
+	// is 'image'.
+	Payload_type *string
+
+	// The type of filesystem to use when the payload_type is 'image'. Either 'ext4' or 'f2fs'.
+	// Default 'ext4'.
+	Payload_fs_type *string
+
+	// For telling the APEX to ignore special handling for system libraries such as bionic.
+	// Default is false.
 	Ignore_system_library_special_case *bool
 
-	Multilib apexMultilibProperties
+	// Whenever apex_payload.img of the APEX should include dm-verity hashtree. Should be only
+	// used in tests.
+	Test_only_no_hashtree *bool
+
+	// Whenever apex_payload.img of the APEX should not be dm-verity signed. Should be only
+	// used in tests.
+	Test_only_unsigned_payload *bool
+
+	IsCoverageVariant bool `blueprint:"mutated"`
 
 	// List of sanitizer names that this APEX is enabled for
 	SanitizerNames []string `blueprint:"mutated"`
@@ -122,57 +166,23 @@
 
 	HideFromMake bool `blueprint:"mutated"`
 
-	// package format of this apex variant; could be non-flattened, flattened, or zip.
-	// imageApex, zipApex or flattened
+	// Internal package method for this APEX. When payload_type is image, this can be either
+	// imageApex or flattenedApex depending on Config.FlattenApex(). When payload_type is zip,
+	// this becomes zipApex.
 	ApexType apexPackaging `blueprint:"mutated"`
-
-	// List of SDKs that are used to build this APEX. A reference to an SDK should be either
-	// `name#version` or `name` which is an alias for `name#current`. If left empty, `platform#current`
-	// is implied. This value affects all modules included in this APEX. In other words, they are
-	// also built with the SDKs specified here.
-	Uses_sdks []string
-
-	// Whenever apex_payload.img of the APEX should include dm-verity hashtree.
-	// Should be only used in tests#.
-	Test_only_no_hashtree *bool
-
-	// Whenever apex_payload.img of the APEX should not be dm-verity signed.
-	// Should be only used in tests#.
-	Test_only_unsigned_payload *bool
-
-	IsCoverageVariant bool `blueprint:"mutated"`
-
-	// Whether this APEX is considered updatable or not. When set to true, this will enforce additional
-	// rules for making sure that the APEX is truly updatable.
-	// - To be updatable, min_sdk_version should be set as well
-	// This will also disable the size optimizations like symlinking to the system libs.
-	// Default is false.
-	Updatable *bool
-
-	// The minimum SDK version that this apex must be compatibile with.
-	Min_sdk_version *string
-
-	// If set true, VNDK libs are considered as stable libs and are not included in this apex.
-	// Should be only used in non-system apexes (e.g. vendor: true).
-	// Default is false.
-	Use_vndk_as_stable *bool
-
-	// The type of filesystem to use for an image apex. Either 'ext4' or 'f2fs'.
-	// Default 'ext4'.
-	Payload_fs_type *string
 }
 
 type ApexNativeDependencies struct {
-	// List of native libraries
+	// List of native libraries that are embedded inside this APEX.
 	Native_shared_libs []string
 
-	// List of JNI libraries
+	// List of JNI libraries that are embedded inside this APEX.
 	Jni_libs []string
 
-	// List of native executables
+	// List of native executables that are embedded inside this APEX.
 	Binaries []string
 
-	// List of native tests
+	// List of native tests that are embedded inside this APEX.
 	Tests []string
 }
 
@@ -217,25 +227,26 @@
 	}
 }
 
+// These properties can be used in override_apex to override the corresponding properties in the
+// base apex.
 type overridableProperties struct {
-	// List of APKs to package inside APEX
+	// List of APKs that are embedded inside this APEX.
 	Apps []string
 
-	// List of runtime resource overlays (RROs) inside APEX
+	// List of runtime resource overlays (RROs) that are embedded inside this APEX.
 	Rros []string
 
-	// Names of modules to be overridden. Listed modules can only be other binaries
-	// (in Make or Soong).
-	// This does not completely prevent installation of the overridden binaries, but if both
-	// binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will be removed
-	// from PRODUCT_PACKAGES.
+	// Names of modules to be overridden. Listed modules can only be other binaries (in Make or
+	// Soong). This does not completely prevent installation of the overridden binaries, but if
+	// both binaries would be installed by default (in PRODUCT_PACKAGES) the other binary will
+	// be removed from PRODUCT_PACKAGES.
 	Overrides []string
 
-	// Logging Parent value
+	// Logging parent value.
 	Logging_parent string
 
-	// Apex Container Package Name.
-	// Override value for attribute package:name in AndroidManifest.xml
+	// Apex Container package name. Override value for attribute package:name in
+	// AndroidManifest.xml
 	Package_name string
 
 	// A txt file containing list of files that are allowed to be included in this APEX.
@@ -243,187 +254,202 @@
 }
 
 type apexBundle struct {
+	// Inherited structs
 	android.ModuleBase
 	android.DefaultableModuleBase
 	android.OverridableModuleBase
 	android.SdkBase
 
+	// Properties
 	properties            apexBundleProperties
 	targetProperties      apexTargetBundleProperties
 	overridableProperties overridableProperties
+	vndkProperties        apexVndkProperties // only for apex_vndk modules
 
-	// specific to apex_vndk modules
-	vndkProperties apexVndkProperties
+	///////////////////////////////////////////////////////////////////////////////////////////
+	// Inputs
 
-	bundleModuleFile android.WritablePath
-	outputFile       android.WritablePath
-	installDir       android.InstallPath
-
-	prebuiltFileToDelete string
-
+	// Keys for apex_paylaod.img
 	public_key_file  android.Path
 	private_key_file android.Path
 
+	// Cert/priv-key for the zip container
 	container_certificate_file android.Path
 	container_private_key_file android.Path
 
-	fileContexts android.WritablePath
+	// Flags for special variants of APEX
+	testApex bool
+	vndkApex bool
+	artApex  bool
 
-	// list of files to be included in this apex
-	filesInfo []apexFile
-
-	// list of module names that should be installed along with this APEX
-	requiredDeps []string
-
-	// list of module names that this APEX is including (to be shown via *-deps-info target)
-	android.ApexBundleDepsInfo
-
-	testApex        bool
-	vndkApex        bool
-	artApex         bool
+	// Tells whether this variant of the APEX bundle is the primary one or not. Only the primary
+	// one gets installed to the device.
 	primaryApexType bool
 
-	manifestJsonOut android.WritablePath
-	manifestPbOut   android.WritablePath
-
-	// list of commands to create symlinks for backward compatibility.
-	// these commands will be attached as LOCAL_POST_INSTALL_CMD to
-	// apex package itself(for unflattened build) or apex_manifest(for flattened build)
-	// so that compat symlinks are always installed regardless of TARGET_FLATTEN_APEX setting.
-	compatSymlinks []string
-
-	// Suffix of module name in Android.mk
-	// ".flattened", ".apex", ".zipapex", or ""
+	// Suffix of module name in Android.mk ".flattened", ".apex", ".zipapex", or ""
 	suffix string
 
-	installedFilesFile android.WritablePath
+	// File system type of apex_payload.img
+	payloadFsType fsType
 
-	// Whether to create symlink to the system file instead of having a file
-	// inside the apex or not
+	// Whether to create symlink to the system file instead of having a file inside the apex or
+	// not
 	linkToSystemLib bool
 
+	// List of files to be included in this APEX. This is filled in the first part of
+	// GenerateAndroidBuildActions.
+	filesInfo []apexFile
+
+	// List of other module names that should be installed when this APEX gets installed.
+	requiredDeps []string
+
+	///////////////////////////////////////////////////////////////////////////////////////////
+	// Outputs (final and intermediates)
+
+	// Processed apex manifest in JSONson format (for Q)
+	manifestJsonOut android.WritablePath
+
+	// Processed apex manifest in PB format (for R+)
+	manifestPbOut android.WritablePath
+
+	// Processed file_contexts files
+	fileContexts android.WritablePath
+
 	// Struct holding the merged notice file paths in different formats
 	mergedNotices android.NoticeOutputs
 
+	// The built APEX file. This is the main product.
+	outputFile android.WritablePath
+
+	// The built APEX file in app bundle format. This file is not directly installed to the
+	// device. For an APEX, multiple app bundles are created each of which is for a specific ABI
+	// like arm, arm64, x86, etc. Then they are processed again (outside of the Android build
+	// system) to be merged into a single app bundle file that Play accepts. See
+	// vendor/google/build/build_unbundled_mainline_module.sh for more detail.
+	bundleModuleFile android.WritablePath
+
+	// Target path to install this APEX. Usually out/target/product/<device>/<partition>/apex.
+	installDir android.InstallPath
+
+	// List of commands to create symlinks for backward compatibility. These commands will be
+	// attached as LOCAL_POST_INSTALL_CMD to apex package itself (for unflattened build) or
+	// apex_manifest (for flattened build) so that compat symlinks are always installed
+	// regardless of TARGET_FLATTEN_APEX setting.
+	compatSymlinks []string
+
+	// Text file having the list of individual files that are included in this APEX. Used for
+	// debugging purpose.
+	installedFilesFile android.WritablePath
+
+	// List of module names that this APEX is including (to be shown via *-deps-info target).
+	// Used for debugging purpose.
+	android.ApexBundleDepsInfo
+
 	// Optional list of lint report zip files for apexes that contain java or app modules
 	lintReports android.Paths
 
-	payloadFsType fsType
+	prebuiltFileToDelete string
 
 	distFiles android.TaggedDistFiles
 }
 
+// apexFileClass represents a type of file that can be included in APEX.
 type apexFileClass int
 
 const (
-	etc apexFileClass = iota
-	nativeSharedLib
-	nativeExecutable
-	shBinary
-	pyBinary
+	app apexFileClass = iota
+	appSet
+	etc
 	goBinary
 	javaSharedLib
+	nativeExecutable
+	nativeSharedLib
 	nativeTest
-	app
-	appSet
+	pyBinary
+	shBinary
 )
 
-func (class apexFileClass) NameInMake() string {
-	switch class {
-	case etc:
-		return "ETC"
-	case nativeSharedLib:
-		return "SHARED_LIBRARIES"
-	case nativeExecutable, shBinary, pyBinary, goBinary:
-		return "EXECUTABLES"
-	case javaSharedLib:
-		return "JAVA_LIBRARIES"
-	case nativeTest:
-		return "NATIVE_TESTS"
-	case app, appSet:
-		// b/142537672 Why isn't this APP? We want to have full control over
-		// the paths and file names of the apk file under the flattend APEX.
-		// If this is set to APP, then the paths and file names are modified
-		// by the Make build system. For example, it is installed to
-		// /system/apex/<apexname>/app/<Appname>/<apexname>.<Appname>/ instead of
-		// /system/apex/<apexname>/app/<Appname> because the build system automatically
-		// appends module name (which is <apexname>.<Appname> to the path.
-		return "ETC"
-	default:
-		panic(fmt.Errorf("unknown class %d", class))
-	}
-}
-
-// apexFile represents a file in an APEX bundle
+// apexFile represents a file in an APEX bundle. This is created during the first half of
+// GenerateAndroidBuildActions by traversing the dependencies of the APEX. Then in the second half
+// of the function, this is used to create commands that copies the files into a staging directory,
+// where they are packaged into the APEX file. This struct is also used for creating Make modules
+// for each of the files in case when the APEX is flattened.
 type apexFile struct {
-	builtFile android.Path
-	stem      string
-	// Module name of `module` in AndroidMk. Note the generated AndroidMk module for
-	// apexFile is named something like <AndroidMk module name>.<apex name>[<apex suffix>]
-	androidMkModuleName string
-	installDir          string
-	class               apexFileClass
-	module              android.Module
-	// list of symlinks that will be created in installDir that point to this apexFile
-	symlinks      []string
-	dataPaths     []android.DataPath
-	transitiveDep bool
-	moduleDir     string
+	// buildFile is put in the installDir inside the APEX.
+	builtFile   android.Path
+	noticeFiles android.Paths
+	installDir  string
+	customStem  string
+	symlinks    []string // additional symlinks
 
-	requiredModuleNames       []string
-	targetRequiredModuleNames []string
-	hostRequiredModuleNames   []string
+	// Info for Android.mk Module name of `module` in AndroidMk. Note the generated AndroidMk
+	// module for apexFile is named something like <AndroidMk module name>.<apex name>[<apex
+	// suffix>]
+	androidMkModuleName       string             // becomes LOCAL_MODULE
+	class                     apexFileClass      // becomes LOCAL_MODULE_CLASS
+	moduleDir                 string             // becomes LOCAL_PATH
+	requiredModuleNames       []string           // becomes LOCAL_REQUIRED_MODULES
+	targetRequiredModuleNames []string           // becomes LOCAL_TARGET_REQUIRED_MODULES
+	hostRequiredModuleNames   []string           // becomes LOCAL_HOST_REQUIRED_MODULES
+	dataPaths                 []android.DataPath // becomes LOCAL_TEST_DATA
 
 	jacocoReportClassesFile android.Path     // only for javalibs and apps
 	lintDepSets             java.LintDepSets // only for javalibs and apps
 	certificate             java.Certificate // only for apps
 	overriddenPackageName   string           // only for apps
 
-	isJniLib bool
+	transitiveDep bool
+	isJniLib      bool
 
-	noticeFiles android.Paths
+	// TODO(jiyong): remove this
+	module android.Module
 }
 
+// TODO(jiyong): shorten the arglist using an option struct
 func newApexFile(ctx android.BaseModuleContext, builtFile android.Path, androidMkModuleName string, installDir string, class apexFileClass, module android.Module) apexFile {
 	ret := apexFile{
 		builtFile:           builtFile,
-		androidMkModuleName: androidMkModuleName,
 		installDir:          installDir,
+		androidMkModuleName: androidMkModuleName,
 		class:               class,
 		module:              module,
 	}
 	if module != nil {
+		ret.noticeFiles = module.NoticeFiles()
 		ret.moduleDir = ctx.OtherModuleDir(module)
 		ret.requiredModuleNames = module.RequiredModuleNames()
 		ret.targetRequiredModuleNames = module.TargetRequiredModuleNames()
 		ret.hostRequiredModuleNames = module.HostRequiredModuleNames()
-		ret.noticeFiles = module.NoticeFiles()
 	}
 	return ret
 }
 
-func (af *apexFile) Ok() bool {
+func (af *apexFile) ok() bool {
 	return af.builtFile != nil && af.builtFile.String() != ""
 }
 
+// apexRelativePath returns the relative path of the given path from the install directory of this
+// apexFile.
+// TODO(jiyong): rename this
 func (af *apexFile) apexRelativePath(path string) string {
 	return filepath.Join(af.installDir, path)
 }
 
-// Path() returns path of this apex file relative to the APEX root
-func (af *apexFile) Path() string {
-	return af.apexRelativePath(af.Stem())
+// path returns path of this apex file relative to the APEX root
+func (af *apexFile) path() string {
+	return af.apexRelativePath(af.stem())
 }
 
-func (af *apexFile) Stem() string {
-	if af.stem != "" {
-		return af.stem
+// stem returns the base filename of this apex file
+func (af *apexFile) stem() string {
+	if af.customStem != "" {
+		return af.customStem
 	}
 	return af.builtFile.Base()
 }
 
-// SymlinkPaths() returns paths of the symlinks (if any) relative to the APEX root
-func (af *apexFile) SymlinkPaths() []string {
+// symlinkPaths returns paths of the symlinks (if any) relative to the APEX root
+func (af *apexFile) symlinkPaths() []string {
 	var ret []string
 	for _, symlink := range af.symlinks {
 		ret = append(ret, af.apexRelativePath(symlink))
@@ -431,7 +457,9 @@
 	return ret
 }
 
-func (af *apexFile) AvailableToPlatform() bool {
+// availableToPlatform tests whether this apexFile is from a module that can be installed to the
+// platform.
+func (af *apexFile) availableToPlatform() bool {
 	if af.module == nil {
 		return false
 	}
@@ -441,37 +469,70 @@
 	return false
 }
 
-func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
-	nativeModules ApexNativeDependencies,
-	target android.Target, imageVariation string) {
-	// Use *FarVariation* to be able to depend on modules having
-	// conflicting variations with this module. This is required since
-	// arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
-	// for native shared libs.
+////////////////////////////////////////////////////////////////////////////////////////////////////
+// Mutators
+//
+// Brief description about mutators for APEX. The following three mutators are the most important
+// ones.
+//
+// 1) DepsMutator: from the properties like native_shared_libs, java_libs, etc., modules are added
+// to the (direct) dependencies of this APEX bundle.
+//
+// 2) apexDepsMutator: this is a post-deps mutator, so runs after DepsMutator. Its goal is to
+// collect modules that are direct and transitive dependencies of each APEX bundle. The collected
+// modules are marked as being included in the APEX via BuildForApex().
+//
+// 3) apexMutator: this is a post-deps mutator that runs after apexDepsMutator. For each module that
+// are marked by the apexDepsMutator, apex variations are created using CreateApexVariations().
 
+type dependencyTag struct {
+	blueprint.BaseDependencyTag
+	name string
+
+	// Determines if the dependent will be part of the APEX payload. Can be false for the
+	// dependencies to the signing key module, etc.
+	payload bool
+}
+
+var (
+	androidAppTag  = dependencyTag{name: "androidApp", payload: true}
+	bpfTag         = dependencyTag{name: "bpf", payload: true}
+	certificateTag = dependencyTag{name: "certificate"}
+	executableTag  = dependencyTag{name: "executable", payload: true}
+	javaLibTag     = dependencyTag{name: "javaLib", payload: true}
+	jniLibTag      = dependencyTag{name: "jniLib", payload: true}
+	keyTag         = dependencyTag{name: "key"}
+	prebuiltTag    = dependencyTag{name: "prebuilt", payload: true}
+	rroTag         = dependencyTag{name: "rro", payload: true}
+	sharedLibTag   = dependencyTag{name: "sharedLib", payload: true}
+	testForTag     = dependencyTag{name: "test for"}
+	testTag        = dependencyTag{name: "test", payload: true}
+)
+
+// TODO(jiyong): shorten this function signature
+func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext, nativeModules ApexNativeDependencies, target android.Target, imageVariation string) {
 	binVariations := target.Variations()
-	libVariations := append(target.Variations(),
-		blueprint.Variation{Mutator: "link", Variation: "shared"})
+	libVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
 
 	if ctx.Device() {
-		binVariations = append(binVariations,
-			blueprint.Variation{Mutator: "image", Variation: imageVariation})
+		binVariations = append(binVariations, blueprint.Variation{Mutator: "image", Variation: imageVariation})
 		libVariations = append(libVariations,
 			blueprint.Variation{Mutator: "image", Variation: imageVariation},
-			blueprint.Variation{Mutator: "version", Variation: ""}) // "" is the non-stub variant
+			blueprint.Variation{Mutator: "version", Variation: ""}, // "" is the non-stub variant
+		)
 	}
 
-	ctx.AddFarVariationDependencies(libVariations, sharedLibTag, nativeModules.Native_shared_libs...)
-
-	ctx.AddFarVariationDependencies(libVariations, jniLibTag, nativeModules.Jni_libs...)
-
+	// Use *FarVariation* to be able to depend on modules having conflicting variations with
+	// this module. This is required since arch variant of an APEX bundle is 'common' but it is
+	// 'arm' or 'arm64' for native shared libs.
 	ctx.AddFarVariationDependencies(binVariations, executableTag, nativeModules.Binaries...)
-
 	ctx.AddFarVariationDependencies(binVariations, testTag, nativeModules.Tests...)
+	ctx.AddFarVariationDependencies(libVariations, jniLibTag, nativeModules.Jni_libs...)
+	ctx.AddFarVariationDependencies(libVariations, sharedLibTag, nativeModules.Native_shared_libs...)
 }
 
 func (a *apexBundle) combineProperties(ctx android.BottomUpMutatorContext) {
-	if ctx.Os().Class == android.Device {
+	if ctx.Device() {
 		proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Android.Multilib, nil)
 	} else {
 		proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Host.Multilib, nil)
@@ -483,34 +544,46 @@
 	}
 }
 
-type dependencyTag struct {
-	blueprint.BaseDependencyTag
-	name string
-
-	// determines if the dependent will be part of the APEX payload
-	payload bool
-}
-
-var (
-	sharedLibTag   = dependencyTag{name: "sharedLib", payload: true}
-	jniLibTag      = dependencyTag{name: "jniLib", payload: true}
-	executableTag  = dependencyTag{name: "executable", payload: true}
-	javaLibTag     = dependencyTag{name: "javaLib", payload: true}
-	prebuiltTag    = dependencyTag{name: "prebuilt", payload: true}
-	testTag        = dependencyTag{name: "test", payload: true}
-	keyTag         = dependencyTag{name: "key"}
-	certificateTag = dependencyTag{name: "certificate"}
-	androidAppTag  = dependencyTag{name: "androidApp", payload: true}
-	rroTag         = dependencyTag{name: "rro", payload: true}
-	bpfTag         = dependencyTag{name: "bpf", payload: true}
-	testForTag     = dependencyTag{name: "test for"}
-)
-
-func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
-	if proptools.Bool(a.properties.Use_vendor) && !android.InList(a.Name(), useVendorAllowList(ctx.Config())) {
-		ctx.PropertyErrorf("use_vendor", "not allowed to set use_vendor: true")
+// getImageVariation returns the image variant name for this apexBundle. In most cases, it's simply
+// android.CoreVariation, but gets complicated for the vendor APEXes and the VNDK APEX.
+func (a *apexBundle) getImageVariation(ctx android.BottomUpMutatorContext) string {
+	deviceConfig := ctx.DeviceConfig()
+	if a.vndkApex {
+		return cc.VendorVariationPrefix + a.vndkVersion(deviceConfig)
 	}
 
+	var prefix string
+	var vndkVersion string
+	if deviceConfig.VndkVersion() != "" {
+		if proptools.Bool(a.properties.Use_vendor) {
+			prefix = cc.VendorVariationPrefix
+			vndkVersion = deviceConfig.PlatformVndkVersion()
+		} else if a.SocSpecific() || a.DeviceSpecific() {
+			prefix = cc.VendorVariationPrefix
+			vndkVersion = deviceConfig.VndkVersion()
+		} else if a.ProductSpecific() {
+			prefix = cc.ProductVariationPrefix
+			vndkVersion = deviceConfig.ProductVndkVersion()
+		}
+	}
+	if vndkVersion == "current" {
+		vndkVersion = deviceConfig.PlatformVndkVersion()
+	}
+	if vndkVersion != "" {
+		return prefix + vndkVersion
+	}
+
+	return android.CoreVariation // The usual case
+}
+
+func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
+	// TODO(jiyong): move this kind of checks to GenerateAndroidBuildActions?
+	checkUseVendorProperty(ctx, a)
+
+	// apexBundle is a multi-arch targets module. Arch variant of apexBundle is set to 'common'.
+	// arch-specific targets are enabled by the compile_multilib setting of the apex bundle. For
+	// each target os/architectures, appropriate dependencies are selected by their
+	// target.<os>.multilib.<type> groups and are added as (direct) dependencies.
 	targets := ctx.MultiTargets()
 	config := ctx.DeviceConfig()
 	imageVariation := a.getImageVariation(ctx)
@@ -524,80 +597,56 @@
 		}
 	}
 	for i, target := range targets {
+		// Don't include artifacts for the host cross targets because there is no way for us
+		// to run those artifacts natively on host
 		if target.HostCross {
-			// Don't include artifats for the host cross targets because there is no way
-			// for us to run those artifacts natively on host
 			continue
 		}
 
-		// When multilib.* is omitted for native_shared_libs/jni_libs/tests, it implies
-		// multilib.both
-		addDependenciesForNativeModules(ctx,
-			ApexNativeDependencies{
-				Native_shared_libs: a.properties.Native_shared_libs,
-				Tests:              a.properties.Tests,
-				Jni_libs:           a.properties.Jni_libs,
-				Binaries:           nil,
-			},
-			target, imageVariation)
+		var depsList []ApexNativeDependencies
 
-		// Add native modules targetting both ABIs
-		addDependenciesForNativeModules(ctx,
-			a.properties.Multilib.Both,
-			target,
-			imageVariation)
+		// Add native modules targeting both ABIs. When multilib.* is omitted for
+		// native_shared_libs/jni_libs/tests, it implies multilib.both
+		depsList = append(depsList, a.properties.Multilib.Both)
+		depsList = append(depsList, ApexNativeDependencies{
+			Native_shared_libs: a.properties.Native_shared_libs,
+			Tests:              a.properties.Tests,
+			Jni_libs:           a.properties.Jni_libs,
+			Binaries:           nil,
+		})
 
+		// Add native modules targeting the first ABI When multilib.* is omitted for
+		// binaries, it implies multilib.first
 		isPrimaryAbi := i == 0
 		if isPrimaryAbi {
-			// When multilib.* is omitted for binaries, it implies
-			// multilib.first
-			addDependenciesForNativeModules(ctx,
-				ApexNativeDependencies{
-					Native_shared_libs: nil,
-					Tests:              nil,
-					Jni_libs:           nil,
-					Binaries:           a.properties.Binaries,
-				},
-				target, imageVariation)
-
-			// Add native modules targetting the first ABI
-			addDependenciesForNativeModules(ctx,
-				a.properties.Multilib.First,
-				target,
-				imageVariation)
+			depsList = append(depsList, a.properties.Multilib.First)
+			depsList = append(depsList, ApexNativeDependencies{
+				Native_shared_libs: nil,
+				Tests:              nil,
+				Jni_libs:           nil,
+				Binaries:           a.properties.Binaries,
+			})
 		}
 
+		// Add native modules targeting either 32-bit or 64-bit ABI
 		switch target.Arch.ArchType.Multilib {
 		case "lib32":
-			// Add native modules targetting 32-bit ABI
-			addDependenciesForNativeModules(ctx,
-				a.properties.Multilib.Lib32,
-				target,
-				imageVariation)
-
-			addDependenciesForNativeModules(ctx,
-				a.properties.Multilib.Prefer32,
-				target,
-				imageVariation)
+			depsList = append(depsList, a.properties.Multilib.Lib32)
+			depsList = append(depsList, a.properties.Multilib.Prefer32)
 		case "lib64":
-			// Add native modules targetting 64-bit ABI
-			addDependenciesForNativeModules(ctx,
-				a.properties.Multilib.Lib64,
-				target,
-				imageVariation)
-
+			depsList = append(depsList, a.properties.Multilib.Lib64)
 			if !has32BitTarget {
-				addDependenciesForNativeModules(ctx,
-					a.properties.Multilib.Prefer32,
-					target,
-					imageVariation)
+				depsList = append(depsList, a.properties.Multilib.Prefer32)
 			}
 		}
+
+		for _, d := range depsList {
+			addDependenciesForNativeModules(ctx, d, target, imageVariation)
+		}
 	}
 
-	// For prebuilt_etc, use the first variant (64 on 64/32bit device,
-	// 32 on 32bit device) regardless of the TARGET_PREFER_* setting.
-	// b/144532908
+	// For prebuilt_etc, use the first variant (64 on 64/32bit device, 32 on 32bit device)
+	// regardless of the TARGET_PREFER_* setting. See b/144532908
 	archForPrebuiltEtc := config.Arches()[0]
 	for _, arch := range config.Arches() {
 		// Prefer 64-bit arch if there is any
@@ -611,20 +660,19 @@
 		{Mutator: "arch", Variation: archForPrebuiltEtc.String()},
 	}, prebuiltTag, a.properties.Prebuilts...)
 
-	ctx.AddFarVariationDependencies(ctx.Config().AndroidCommonTarget.Variations(),
-		javaLibTag, a.properties.Java_libs...)
-
-	ctx.AddFarVariationDependencies(ctx.Config().AndroidCommonTarget.Variations(),
-		bpfTag, a.properties.Bpfs...)
+	// Common-arch dependencies come next
+	commonVariation := ctx.Config().AndroidCommonTarget.Variations()
+	ctx.AddFarVariationDependencies(commonVariation, javaLibTag, a.properties.Java_libs...)
+	ctx.AddFarVariationDependencies(commonVariation, bpfTag, a.properties.Bpfs...)
 
 	// With EMMA_INSTRUMENT_FRAMEWORK=true the ART boot image includes jacoco library.
 	if a.artApex && ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
-		ctx.AddFarVariationDependencies(ctx.Config().AndroidCommonTarget.Variations(),
-			javaLibTag, "jacocoagent")
+		ctx.AddFarVariationDependencies(commonVariation, javaLibTag, "jacocoagent")
 	}
 
+	// Dependencies for signing
 	if String(a.properties.Key) == "" {
-		ctx.ModuleErrorf("key is missing")
+		ctx.PropertyErrorf("key", "missing")
 		return
 	}
 	ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
@@ -632,8 +680,13 @@
 	cert := android.SrcIsModule(a.getCertString(ctx))
 	if cert != "" {
 		ctx.AddDependency(ctx.Module(), certificateTag, cert)
+		// empty cert is not an error. Cert and private keys will be directly found under
+		// PRODUCT_DEFAULT_DEV_CERTIFICATE
 	}
 
+	// Marks that this APEX (in fact all the modules in it) has to be built with the given SDKs.
+	// This field currently isn't used.
+	// TODO(jiyong): consider dropping this feature
 	// TODO(jiyong): ensure that all apexes are with non-empty uses_sdks
 	if len(a.properties.Uses_sdks) > 0 {
 		sdkRefs := []android.SdkRef{}
@@ -645,14 +698,15 @@
 	}
 }
 
+// DepsMutator for the overridden properties.
 func (a *apexBundle) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
 	if a.overridableProperties.Allowed_files != nil {
 		android.ExtractSourceDeps(ctx, a.overridableProperties.Allowed_files)
 	}
-	ctx.AddFarVariationDependencies(ctx.Config().AndroidCommonTarget.Variations(),
-		androidAppTag, a.overridableProperties.Apps...)
-	ctx.AddFarVariationDependencies(ctx.Config().AndroidCommonTarget.Variations(),
-		rroTag, a.overridableProperties.Rros...)
+
+	commonVariation := ctx.Config().AndroidCommonTarget.Variations()
+	ctx.AddFarVariationDependencies(commonVariation, androidAppTag, a.overridableProperties.Apps...)
+	ctx.AddFarVariationDependencies(commonVariation, rroTag, a.overridableProperties.Rros...)
 }
 
 type ApexBundleInfo struct {
@@ -661,17 +715,34 @@
 
 var ApexBundleInfoProvider = blueprint.NewMutatorProvider(ApexBundleInfo{}, "apex_deps")
 
-// Mark the direct and transitive dependencies of apex bundles so that they
-// can be built for the apex bundles.
+// apexDepsMutator is responsible for collecting modules that need to have apex variants. They are
+// identified by doing a graph walk starting from an apexBundle. Basically, all the (direct and
+// indirect) dependencies are collected. But a few types of modules that shouldn't be included in
+// the apexBundle (e.g. stub libraries) are not collected. Note that a single module can be depended
+// on by multiple apexBundles. In that case, the module is collected for all of the apexBundles.
 func apexDepsMutator(mctx android.TopDownMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
 	}
+
 	a, ok := mctx.Module().(*apexBundle)
-	if !ok || a.vndkApex {
+	if !ok {
 		return
 	}
 
+	// The VNDK APEX is special. For the APEX, the membership is described in a very different
+	// way. There is no dependency from the VNDK APEX to the VNDK libraries. Instead, VNDK
+	// libraries are self-identified by their vndk.enabled properties. There is no need to run
+	// this mutator for the APEX as nothing will be collected. So, let's return fast.
+	if a.vndkApex {
+		return
+	}
+
+	// Special casing for APEXes on non-system (e.g., vendor, odm, etc.) partitions. They are
+	// provided with a property named use_vndk_as_stable, which when set to true doesn't collect
+	// VNDK libraries as transitive dependencies. This option is useful for reducing the size of
+	// the non-system APEXes because the VNDK libraries won't be included (and duped) in the
+	// APEX, but shared across APEXes via the VNDK APEX.
 	useVndk := a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && mctx.Config().EnforceProductPartitionInterface())
 	excludeVndkLibs := useVndk && proptools.Bool(a.properties.Use_vndk_as_stable)
 	if !useVndk && proptools.Bool(a.properties.Use_vndk_as_stable) {
@@ -679,8 +750,6 @@
 		return
 	}
 
-	contents := make(map[string]android.ApexMembership)
-
 	continueApexDepsWalk := func(child, parent android.Module) bool {
 		am, ok := child.(android.ApexModule)
 		if !ok || !am.CanHaveApexVariants() {
@@ -694,26 +763,33 @@
 				return false
 			}
 		}
+		// By default, all the transitive dependencies are collected, unless filtered out
+		// above.
 		return true
 	}
 
+	// Records whether a certain module is included in this apexBundle via direct dependency or
+	// inndirect dependency.
+	contents := make(map[string]android.ApexMembership)
 	mctx.WalkDeps(func(child, parent android.Module) bool {
 		if !continueApexDepsWalk(child, parent) {
 			return false
 		}
-
-		depName := mctx.OtherModuleName(child)
 		// If the parent is apexBundle, this child is directly depended.
 		_, directDep := parent.(*apexBundle)
+		depName := mctx.OtherModuleName(child)
 		contents[depName] = contents[depName].Add(directDep)
 		return true
 	})
 
-	apexContents := android.NewApexContents(mctx.ModuleName(), contents)
+	// The membership information is saved for later access
+	apexContents := android.NewApexContents(contents)
 	mctx.SetProvider(ApexBundleInfoProvider, ApexBundleInfo{
 		Contents: apexContents,
 	})
 
+	// This is the main part of this mutator. Mark the collected dependencies that they need to
+	// be built for this apexBundle.
 	apexInfo := android.ApexInfo{
 		ApexVariationName: mctx.ModuleName(),
 		MinSdkVersionStr:  a.minSdkVersion(mctx).String(),
@@ -722,34 +798,34 @@
 		InApexes:          []string{mctx.ModuleName()},
 		ApexContents:      []*android.ApexContents{apexContents},
 	}
-
 	mctx.WalkDeps(func(child, parent android.Module) bool {
 		if !continueApexDepsWalk(child, parent) {
 			return false
 		}
-
-		child.(android.ApexModule).BuildForApex(apexInfo)
+		child.(android.ApexModule).BuildForApex(apexInfo) // leave a mark!
 		return true
 	})
 }
 
+// apexUniqueVariationsMutator checks if any dependencies use unique apex variations. If so, use
+// unique apex variations for this module. See android/apex.go for more about unique apex variant.
+// TODO(jiyong): move this to android/apex.go?
 func apexUniqueVariationsMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
 	}
 	if am, ok := mctx.Module().(android.ApexModule); ok {
-		// Check if any dependencies use unique apex variations.  If so, use unique apex variations
-		// for this module.
 		android.UpdateUniqueApexVariationsForDeps(mctx, am)
 	}
 }
 
+// apexTestForDepsMutator checks if this module is a test for an apex. If so, add a dependency on
+// the apex in order to retrieve its contents later.
+// TODO(jiyong): move this to android/apex.go?
 func apexTestForDepsMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
 	}
-	// Check if this module is a test for an apex.  If so, add a dependency on the apex
-	// in order to retrieve its contents later.
 	if am, ok := mctx.Module().(android.ApexModule); ok {
 		if testFor := am.TestFor(); len(testFor) > 0 {
 			mctx.AddFarVariationDependencies([]blueprint.Variation{
@@ -760,11 +836,11 @@
 	}
 }
 
+// TODO(jiyong): move this to android/apex.go?
 func apexTestForMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
 	}
-
 	if _, ok := mctx.Module().(android.ApexModule); ok {
 		var contents []*android.ApexContents
 		for _, testFor := range mctx.GetDirectDepsWithTag(testForTag) {
@@ -777,69 +853,70 @@
 	}
 }
 
-// mark if a module cannot be available to platform. A module cannot be available
-// to platform if 1) it is explicitly marked as not available (i.e. "//apex_available:platform"
-// is absent) or 2) it depends on another module that isn't (or can't be) available to platform
+// markPlatformAvailability marks whether or not a module can be available to platform. A module
+// cannot be available to platform if 1) it is explicitly marked as not available (i.e.
+// "//apex_available:platform" is absent) or 2) it depends on another module that isn't (or can't
+// be) available to platform
+// TODO(jiyong): move this to android/apex.go?
 func markPlatformAvailability(mctx android.BottomUpMutatorContext) {
 	// Host and recovery are not considered as platform
 	if mctx.Host() || mctx.Module().InstallInRecovery() {
 		return
 	}
 
-	if am, ok := mctx.Module().(android.ApexModule); ok {
-		availableToPlatform := am.AvailableFor(android.AvailableToPlatform)
+	am, ok := mctx.Module().(android.ApexModule)
+	if !ok {
+		return
+	}
 
-		// If any of the dep is not available to platform, this module is also considered
-		// as being not available to platform even if it has "//apex_available:platform"
-		mctx.VisitDirectDeps(func(child android.Module) {
-			if !am.DepIsInSameApex(mctx, child) {
-				// if the dependency crosses apex boundary, don't consider it
-				return
-			}
-			if dep, ok := child.(android.ApexModule); ok && dep.NotAvailableForPlatform() {
-				availableToPlatform = false
-				// TODO(b/154889534) trigger an error when 'am' has "//apex_available:platform"
-			}
-		})
+	availableToPlatform := am.AvailableFor(android.AvailableToPlatform)
 
-		// Exception 1: stub libraries and native bridge libraries are always available to platform
-		if cc, ok := mctx.Module().(*cc.Module); ok &&
-			(cc.IsStubs() || cc.Target().NativeBridge == android.NativeBridgeEnabled) {
-			availableToPlatform = true
+	// If any of the dep is not available to platform, this module is also considered as being
+	// not available to platform even if it has "//apex_available:platform"
+	mctx.VisitDirectDeps(func(child android.Module) {
+		if !am.DepIsInSameApex(mctx, child) {
+			// if the dependency crosses apex boundary, don't consider it
+			return
 		}
-
-		// Exception 2: bootstrap bionic libraries are also always available to platform
-		if cc.InstallToBootstrap(mctx.ModuleName(), mctx.Config()) {
-			availableToPlatform = true
+		if dep, ok := child.(android.ApexModule); ok && dep.NotAvailableForPlatform() {
+			availableToPlatform = false
+			// TODO(b/154889534) trigger an error when 'am' has
+			// "//apex_available:platform"
 		}
+	})
 
-		if !availableToPlatform {
-			am.SetNotAvailableForPlatform()
-		}
+	// Exception 1: stub libraries and native bridge libraries are always available to platform
+	if cc, ok := mctx.Module().(*cc.Module); ok &&
+		(cc.IsStubs() || cc.Target().NativeBridge == android.NativeBridgeEnabled) {
+		availableToPlatform = true
+	}
+
+	// Exception 2: bootstrap bionic libraries are also always available to platform
+	if cc.InstallToBootstrap(mctx.ModuleName(), mctx.Config()) {
+		availableToPlatform = true
+	}
+
+	if !availableToPlatform {
+		am.SetNotAvailableForPlatform()
 	}
 }
 
-// If a module in an APEX depends on a module from an SDK then it needs an APEX
-// specific variant created for it. Refer to sdk.sdkDepsReplaceMutator.
-func inAnySdk(module android.Module) bool {
-	if sa, ok := module.(android.SdkAware); ok {
-		return sa.IsInAnySdk()
-	}
-
-	return false
-}
-
-// Create apex variations if a module is included in APEX(s).
+// apexMutator visits each module and creates apex variations if the module was marked in the
+// previous run of apexDepsMutator.
 func apexMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
 	}
 
+	// This is the usual path.
 	if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
 		android.CreateApexVariations(mctx, am)
-	} else if a, ok := mctx.Module().(*apexBundle); ok && !a.vndkApex {
-		// apex bundle itself is mutated so that it and its modules have same
-		// apex variant.
+		return
+	}
+
+	// apexBundle itself is mutated so that it and its dependencies have the same apex variant.
+	// TODO(jiyong): document the reason why the VNDK APEX is an exception here.
+	if a, ok := mctx.Module().(*apexBundle); ok && !a.vndkApex {
 		apexBundleName := mctx.ModuleName()
 		mctx.CreateVariations(apexBundleName)
 	} else if o, ok := mctx.Module().(*OverrideApex); ok {
@@ -850,9 +927,10 @@
 		}
 		mctx.CreateVariations(apexBundleName)
 	}
-
 }
 
+// See android.UpdateDirectlyInAnyApex
+// TODO(jiyong): move this to android/apex.go?
 func apexDirectlyInAnyMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
@@ -862,19 +940,32 @@
 	}
 }
 
+// apexPackaging represents a specific packaging method for an APEX.
 type apexPackaging int
 
 const (
+	// imageApex is a packaging method where contents are included in a filesystem image which
+	// is then included in a zip container. This is the most typical way of packaging.
 	imageApex apexPackaging = iota
+
+	// zipApex is a packaging method where contents are directly included in the zip container.
+	// This is used for host-side testing - because the contents are easily accessible by
+	// unzipping the container.
 	zipApex
+
+	// flattendApex is a packaging method where contents are not included in the APEX file, but
+	// installed to /apex/<apexname> directory on the device. This packaging method is used for
+	// old devices where the filesystem-based APEX file can't be supported.
 	flattenedApex
 )
 
 const (
+	// File extensions of an APEX for different packaging methods
 	imageApexSuffix = ".apex"
 	zipApexSuffix   = ".zipapex"
 	flattenedSuffix = ".flattened"
 
+	// variant names each of which is for a packaging method
 	imageApexType     = "image"
 	zipApexType       = "zip"
 	flattenedApexType = "flattened"
@@ -906,6 +997,8 @@
 	}
 }
 
+// apexFlattenedMutator creates one or more variations each of which is for a packaging method.
+// TODO(jiyong): give a better name to this mutator
 func apexFlattenedMutator(mctx android.BottomUpMutatorContext) {
 	if !mctx.Module().Enabled() {
 		return
@@ -914,13 +1007,21 @@
 		var variants []string
 		switch proptools.StringDefault(ab.properties.Payload_type, "image") {
 		case "image":
+			// This is the normal case. Note that both image and flattend APEXes are
+			// created. The image type is installed to the system partition, while the
+			// flattened APEX is (optionally) installed to the system_ext partition.
+			// This is mostly for GSI which has to support wide range of devices. If GSI
+			// is installed on a newer (APEX-capable) device, the image APEX in the
+			// system will be used. However, if the same GSI is installed on an old
+			// device which can't support image APEX, the flattened APEX in the
+			// system_ext partion (which still is part of GSI) is used instead.
 			variants = append(variants, imageApexType, flattenedApexType)
 		case "zip":
 			variants = append(variants, zipApexType)
 		case "both":
 			variants = append(variants, imageApexType, zipApexType, flattenedApexType)
 		default:
-			mctx.PropertyErrorf("type", "%q is not one of \"image\", \"zip\", or \"both\".", *ab.properties.Payload_type)
+			mctx.PropertyErrorf("payload_type", "%q is not one of \"image\", \"zip\", or \"both\".", *ab.properties.Payload_type)
 			return
 		}
 
@@ -934,26 +1035,35 @@
 				modules[i].(*apexBundle).properties.ApexType = zipApex
 			case flattenedApexType:
 				modules[i].(*apexBundle).properties.ApexType = flattenedApex
+				// See the comment above for why system_ext.
 				if !mctx.Config().FlattenApex() && ab.Platform() {
 					modules[i].(*apexBundle).MakeAsSystemExt()
 				}
 			}
 		}
 	} else if _, ok := mctx.Module().(*OverrideApex); ok {
+		// payload_type is forcibly overridden to "image"
+		// TODO(jiyong): is this the right decision?
 		mctx.CreateVariations(imageApexType, flattenedApexType)
 	}
 }
 
+// checkUseVendorProperty checks if the use of `use_vendor` property is allowed for the given APEX.
+// When use_vendor is used, native modules are built with __ANDROID_VNDK__ and __ANDROID_APEX__,
+// which may cause compatibility issues. (e.g. libbinder) Even though libbinder restricts its
+// availability via 'apex_available' property and relies on yet another macro
+// __ANDROID_APEX_<NAME>__, we restrict usage of "use_vendor:" from other APEX modules to avoid
+// similar problems.
+func checkUseVendorProperty(ctx android.BottomUpMutatorContext, a *apexBundle) {
+	if proptools.Bool(a.properties.Use_vendor) && !android.InList(a.Name(), useVendorAllowList(ctx.Config())) {
+		ctx.PropertyErrorf("use_vendor", "not allowed to set use_vendor: true")
+	}
+}
+
 var (
 	useVendorAllowListKey = android.NewOnceKey("useVendorAllowList")
 )
 
-// useVendorAllowList returns the list of APEXes which are allowed to use_vendor.
-// When use_vendor is used, native modules are built with __ANDROID_VNDK__ and __ANDROID_APEX__,
-// which may cause compatibility issues. (e.g. libbinder)
-// Even though libbinder restricts its availability via 'apex_available' property and relies on
-// yet another macro __ANDROID_APEX_<NAME>__, we restrict usage of "use_vendor:" from other APEX modules
-// to avoid similar problems.
 func useVendorAllowList(config android.Config) []string {
 	return config.Once(useVendorAllowListKey, func() interface{} {
 		return []string{
@@ -964,41 +1074,74 @@
 	}).([]string)
 }
 
-// setUseVendorAllowListForTest overrides useVendorAllowList and must be
-// called before the first call to useVendorAllowList()
+// setUseVendorAllowListForTest overrides useVendorAllowList and must be called before the first
+// call to useVendorAllowList()
 func setUseVendorAllowListForTest(config android.Config, allowList []string) {
 	config.Once(useVendorAllowListKey, func() interface{} {
 		return allowList
 	})
 }
 
-type fsType int
+var _ android.DepIsInSameApex = (*apexBundle)(nil)
 
-const (
-	ext4 fsType = iota
-	f2fs
-)
-
-func (f fsType) string() string {
-	switch f {
-	case ext4:
-		return ext4FsType
-	case f2fs:
-		return f2fsFsType
-	default:
-		panic(fmt.Errorf("unknown APEX payload type %d", f))
-	}
-}
-
+// Implements android.DepInInSameApex
 func (a *apexBundle) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
 	// direct deps of an APEX bundle are all part of the APEX bundle
+	// TODO(jiyong): shouldn't we look into the payload field of the dependencyTag?
 	return true
 }
 
+var _ android.OutputFileProducer = (*apexBundle)(nil)
+
+// Implements android.OutputFileProducer
+func (a *apexBundle) OutputFiles(tag string) (android.Paths, error) {
+	switch tag {
+	case "":
+		return android.Paths{a.outputFile}, nil
+	default:
+		return nil, fmt.Errorf("unsupported module reference tag %q", tag)
+	}
+}
+
+var _ cc.Coverage = (*apexBundle)(nil)
+
+// Implements cc.Coverage
+func (a *apexBundle) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
+	return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
+}
+
+// Implements cc.Coverage
+func (a *apexBundle) PreventInstall() {
+	a.properties.PreventInstall = true
+}
+
+// Implements cc.Coverage
+func (a *apexBundle) HideFromMake() {
+	a.properties.HideFromMake = true
+}
+
+// Implements cc.Coverage
+func (a *apexBundle) MarkAsCoverageVariant(coverage bool) {
+	a.properties.IsCoverageVariant = coverage
+}
+
+// Implements cc.Coverage
+func (a *apexBundle) EnableCoverageIfNeeded() {}
+
+var _ android.ApexBundleDepsInfoIntf = (*apexBundle)(nil)
+
+// Implements android.ApexBudleDepsInfoIntf
+func (a *apexBundle) Updatable() bool {
+	return proptools.Bool(a.properties.Updatable)
+}
+
+// getCertString returns the name of the cert that should be used to sign this APEX. This is
+// basically from the "certificate" property, but could be overridden by the device config.
 func (a *apexBundle) getCertString(ctx android.BaseModuleContext) string {
 	moduleName := ctx.ModuleName()
-	// VNDK APEXes share the same certificate. To avoid adding a new VNDK version to the OVERRIDE_* list,
-	// we check with the pseudo module name to see if its certificate is overridden.
+	// VNDK APEXes share the same certificate. To avoid adding a new VNDK version to the
+	// OVERRIDE_* list, we check with the pseudo module name to see if its certificate is
+	// overridden.
 	if a.vndkApex {
 		moduleName = vndkApexName
 	}
@@ -1009,55 +1152,24 @@
 	return String(a.properties.Certificate)
 }
 
-func (a *apexBundle) OutputFiles(tag string) (android.Paths, error) {
-	switch tag {
-	case "":
-		return android.Paths{a.outputFile}, nil
-	default:
-		return nil, fmt.Errorf("unsupported module reference tag %q", tag)
-	}
-}
-
+// See the installable property
 func (a *apexBundle) installable() bool {
 	return !a.properties.PreventInstall && (a.properties.Installable == nil || proptools.Bool(a.properties.Installable))
 }
 
+// See the test_only_no_hashtree property
 func (a *apexBundle) testOnlyShouldSkipHashtreeGeneration() bool {
 	return proptools.Bool(a.properties.Test_only_no_hashtree)
 }
 
+// See the test_only_unsigned_payload property
 func (a *apexBundle) testOnlyShouldSkipPayloadSign() bool {
 	return proptools.Bool(a.properties.Test_only_unsigned_payload)
 }
 
-func (a *apexBundle) getImageVariation(ctx android.BottomUpMutatorContext) string {
-	deviceConfig := ctx.DeviceConfig()
-	if a.vndkApex {
-		return cc.VendorVariationPrefix + a.vndkVersion(deviceConfig)
-	}
-
-	var prefix string
-	var vndkVersion string
-	if deviceConfig.VndkVersion() != "" {
-		if proptools.Bool(a.properties.Use_vendor) {
-			prefix = cc.VendorVariationPrefix
-			vndkVersion = deviceConfig.PlatformVndkVersion()
-		} else if a.SocSpecific() || a.DeviceSpecific() {
-			prefix = cc.VendorVariationPrefix
-			vndkVersion = deviceConfig.VndkVersion()
-		} else if a.ProductSpecific() {
-			prefix = cc.ProductVariationPrefix
-			vndkVersion = deviceConfig.ProductVndkVersion()
-		}
-	}
-	if vndkVersion == "current" {
-		vndkVersion = deviceConfig.PlatformVndkVersion()
-	}
-	if vndkVersion != "" {
-		return prefix + vndkVersion
-	}
-	return android.CoreVariation
-}
+// These functions are interfacing with cc/sanitizer.go. The entire APEX (along with all of its
+// members) can be sanitized, either forcibly, or by the global configuration. For some of the
+// sanitizers, extra dependencies can be forcibly added as well.
 
 func (a *apexBundle) EnableSanitizer(sanitizerName string) {
 	if !android.InList(sanitizerName, a.properties.SanitizerNames) {
@@ -1084,44 +1196,31 @@
 }
 
 func (a *apexBundle) AddSanitizerDependencies(ctx android.BottomUpMutatorContext, sanitizerName string) {
+	// TODO(jiyong): move this info (the sanitizer name, the lib name, etc.) to cc/sanitize.go
+	// Keep only the mechanism here.
 	if ctx.Device() && sanitizerName == "hwaddress" && strings.HasPrefix(a.Name(), "com.android.runtime") {
+		imageVariation := a.getImageVariation(ctx)
 		for _, target := range ctx.MultiTargets() {
 			if target.Arch.ArchType.Multilib == "lib64" {
-				ctx.AddFarVariationDependencies(append(target.Variations(), []blueprint.Variation{
-					{Mutator: "image", Variation: a.getImageVariation(ctx)},
-					{Mutator: "link", Variation: "shared"},
-					{Mutator: "version", Variation: ""}, // "" is the non-stub variant
-				}...), sharedLibTag, "libclang_rt.hwasan-aarch64-android")
+				addDependenciesForNativeModules(ctx, ApexNativeDependencies{
+					Native_shared_libs: []string{"libclang_rt.hwasan-aarch64-android"},
+					Tests:              nil,
+					Jni_libs:           nil,
+					Binaries:           nil,
+				}, target, imageVariation)
 				break
 			}
 		}
 	}
 }
 
-var _ cc.Coverage = (*apexBundle)(nil)
-
-func (a *apexBundle) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
-	return ctx.Device() && ctx.DeviceConfig().NativeCoverageEnabled()
-}
-
-func (a *apexBundle) PreventInstall() {
-	a.properties.PreventInstall = true
-}
-
-func (a *apexBundle) HideFromMake() {
-	a.properties.HideFromMake = true
-}
-
-func (a *apexBundle) MarkAsCoverageVariant(coverage bool) {
-	a.properties.IsCoverageVariant = coverage
-}
-
-func (a *apexBundle) EnableCoverageIfNeeded() {}
-
-// TODO(jiyong) move apexFileFor* close to the apexFile type definition
+// apexFileFor<Type> functions below create an apexFile struct for a given Soong module. The
+// returned apexFile saves information about the Soong module that will be used for creating the
+// build rules.
 func apexFileForNativeLibrary(ctx android.BaseModuleContext, ccMod *cc.Module, handleSpecialLibs bool) apexFile {
-	// Decide the APEX-local directory by the multilib of the library
-	// In the future, we may query this to the module.
+	// Decide the APEX-local directory by the multilib of the library In the future, we may
+	// query this to the module.
+	// TODO(jiyong): use the new PackagingSpec
 	var dirInApex string
 	switch ccMod.Arch().ArchType.Multilib {
 	case "lib32":
@@ -1134,16 +1233,15 @@
 	}
 	dirInApex = filepath.Join(dirInApex, ccMod.RelativeInstallPath())
 	if handleSpecialLibs && cc.InstallToBootstrap(ccMod.BaseModuleName(), ctx.Config()) {
-		// Special case for Bionic libs and other libs installed with them. This is
-		// to prevent those libs from being included in the search path
-		// /apex/com.android.runtime/${LIB}. This exclusion is required because
-		// those libs in the Runtime APEX are available via the legacy paths in
-		// /system/lib/. By the init process, the libs in the APEX are bind-mounted
-		// to the legacy paths and thus will be loaded into the default linker
-		// namespace (aka "platform" namespace). If the libs are directly in
-		// /apex/com.android.runtime/${LIB} then the same libs will be loaded again
-		// into the runtime linker namespace, which will result in double loading of
-		// them, which isn't supported.
+		// Special case for Bionic libs and other libs installed with them. This is to
+		// prevent those libs from being included in the search path
+		// /apex/com.android.runtime/${LIB}. This exclusion is required because those libs
+		// in the Runtime APEX are available via the legacy paths in /system/lib/. By the
+		// init process, the libs in the APEX are bind-mounted to the legacy paths and thus
+		// will be loaded into the default linker namespace (aka "platform" namespace). If
+		// the libs are directly in /apex/com.android.runtime/${LIB} then the same libs will
+		// be loaded again into the runtime linker namespace, which will result in double
+		// loading of them, which isn't supported.
 		dirInApex = filepath.Join(dirInApex, "bionic")
 	}
 
@@ -1171,6 +1269,7 @@
 	fileToCopy := py.HostToolPath().Path()
 	return newApexFile(ctx, fileToCopy, py.BaseModuleName(), dirInApex, pyBinary, py)
 }
+
 func apexFileForGoBinary(ctx android.BaseModuleContext, depName string, gb bootstrap.GoBinaryTool) apexFile {
 	dirInApex := "bin"
 	s, err := filepath.Rel(android.PathForOutput(ctx).String(), gb.InstallPath())
@@ -1193,31 +1292,6 @@
 	return af
 }
 
-type javaModule interface {
-	android.Module
-	BaseModuleName() string
-	DexJarBuildPath() android.Path
-	JacocoReportClassesFile() android.Path
-	LintDepSets() java.LintDepSets
-
-	Stem() string
-}
-
-var _ javaModule = (*java.Library)(nil)
-var _ javaModule = (*java.SdkLibrary)(nil)
-var _ javaModule = (*java.DexImport)(nil)
-var _ javaModule = (*java.SdkLibraryImport)(nil)
-
-func apexFileForJavaLibrary(ctx android.BaseModuleContext, module javaModule) apexFile {
-	dirInApex := "javalib"
-	fileToCopy := module.DexJarBuildPath()
-	af := newApexFile(ctx, fileToCopy, module.BaseModuleName(), dirInApex, javaSharedLib, module)
-	af.jacocoReportClassesFile = module.JacocoReportClassesFile()
-	af.lintDepSets = module.LintDepSets()
-	af.stem = module.Stem() + ".jar"
-	return af
-}
-
 func apexFileForPrebuiltEtc(ctx android.BaseModuleContext, prebuilt prebuilt_etc.PrebuiltEtcModule, depName string) apexFile {
 	dirInApex := filepath.Join(prebuilt.BaseDir(), prebuilt.SubDir())
 	fileToCopy := prebuilt.OutputFile()
@@ -1230,7 +1304,35 @@
 	return newApexFile(ctx, fileToCopy, depName, dirInApex, etc, config)
 }
 
-func apexFileForAndroidApp(ctx android.BaseModuleContext, aapp interface {
+// javaModule is an interface to handle all Java modules (java_library, dex_import, etc) in the same
+// way.
+type javaModule interface {
+	android.Module
+	BaseModuleName() string
+	DexJarBuildPath() android.Path
+	JacocoReportClassesFile() android.Path
+	LintDepSets() java.LintDepSets
+	Stem() string
+}
+
+var _ javaModule = (*java.Library)(nil)
+var _ javaModule = (*java.SdkLibrary)(nil)
+var _ javaModule = (*java.DexImport)(nil)
+var _ javaModule = (*java.SdkLibraryImport)(nil)
+
+func apexFileForJavaModule(ctx android.BaseModuleContext, module javaModule) apexFile {
+	dirInApex := "javalib"
+	fileToCopy := module.DexJarBuildPath()
+	af := newApexFile(ctx, fileToCopy, module.BaseModuleName(), dirInApex, javaSharedLib, module)
+	af.jacocoReportClassesFile = module.JacocoReportClassesFile()
+	af.lintDepSets = module.LintDepSets()
+	af.customStem = module.Stem() + ".jar"
+	return af
+}
+
+// androidApp is an interface to handle all app modules (android_app, android_app_import, etc.) in
+// the same way.
+type androidApp interface {
 	android.Module
 	Privileged() bool
 	InstallApkName() string
@@ -1238,7 +1340,12 @@
 	JacocoReportClassesFile() android.Path
 	Certificate() java.Certificate
 	BaseModuleName() string
-}) apexFile {
+}
+
+var _ androidApp = (*java.AndroidApp)(nil)
+var _ androidApp = (*java.AndroidAppImport)(nil)
+
+func apexFileForAndroidApp(ctx android.BaseModuleContext, aapp androidApp) apexFile {
 	appDir := "app"
 	if aapp.Privileged() {
 		appDir = "priv-app"
@@ -1277,16 +1384,10 @@
 	return newApexFile(ctx, builtFile, builtFile.Base(), dirInApex, etc, bpfProgram)
 }
 
-// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
-type flattenedApexContext struct {
-	android.ModuleContext
-}
-
-func (c *flattenedApexContext) InstallBypassMake() bool {
-	return true
-}
-
-// Visit dependencies that contributes to the payload of this APEX
+// WalyPayloadDeps visits dependencies that contributes to the payload of this APEX. For each of the
+// visited module, the `do` callback is executed. Returning true in the callback continues the visit
+// to the child modules. Returning false makes the visit to continue in the sibling or the parent
+// modules. This is used in check* functions below.
 func (a *apexBundle) WalkPayloadDeps(ctx android.ModuleContext, do android.PayloadDepsCallback) {
 	ctx.WalkDeps(func(child, parent android.Module) bool {
 		am, ok := child.(android.ApexModule)
@@ -1294,213 +1395,74 @@
 			return false
 		}
 
-		childApexInfo := ctx.OtherModuleProvider(child, android.ApexInfoProvider).(android.ApexInfo)
-
-		dt := ctx.OtherModuleDependencyTag(child)
-
-		if _, ok := dt.(android.ExcludeFromApexContentsTag); ok {
+		// Filter-out unwanted depedendencies
+		depTag := ctx.OtherModuleDependencyTag(child)
+		if _, ok := depTag.(android.ExcludeFromApexContentsTag); ok {
+			return false
+		}
+		if dt, ok := depTag.(dependencyTag); ok && !dt.payload {
 			return false
 		}
 
-		// Check for the direct dependencies that contribute to the payload
-		if adt, ok := dt.(dependencyTag); ok {
-			if adt.payload {
-				return do(ctx, parent, am, false /* externalDep */)
-			}
-			// As soon as the dependency graph crosses the APEX boundary, don't go further.
-			return false
-		}
+		ai := ctx.OtherModuleProvider(child, android.ApexInfoProvider).(android.ApexInfo)
+		externalDep := !android.InList(ctx.ModuleName(), ai.InApexes)
 
-		// Check for the indirect dependencies if it is considered as part of the APEX
-		if android.InList(ctx.ModuleName(), childApexInfo.InApexes) {
-			return do(ctx, parent, am, false /* externalDep */)
-		}
-
-		return do(ctx, parent, am, true /* externalDep */)
+		// Visit actually
+		return do(ctx, parent, am, externalDep)
 	})
 }
 
-func (a *apexBundle) minSdkVersion(ctx android.BaseModuleContext) android.ApiLevel {
-	ver := proptools.String(a.properties.Min_sdk_version)
-	if ver == "" {
-		return android.FutureApiLevel
-	}
-	apiLevel, err := android.ApiLevelFromUser(ctx, ver)
-	if err != nil {
-		ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
-		return android.NoneApiLevel
-	}
-	if apiLevel.IsPreview() {
-		// All codenames should build against "current".
-		return android.FutureApiLevel
-	}
-	return apiLevel
-}
+// filesystem type of the apex_payload.img inside the APEX. Currently, ext4 and f2fs are supported.
+type fsType int
 
-func (a *apexBundle) Updatable() bool {
-	return proptools.Bool(a.properties.Updatable)
-}
+const (
+	ext4 fsType = iota
+	f2fs
+)
 
-var _ android.ApexBundleDepsInfoIntf = (*apexBundle)(nil)
-
-// Ensures that the dependencies are marked as available for this APEX
-func (a *apexBundle) checkApexAvailability(ctx android.ModuleContext) {
-	// Let's be practical. Availability for test, host, and the VNDK apex isn't important
-	if ctx.Host() || a.testApex || a.vndkApex {
-		return
-	}
-
-	// Because APEXes targeting other than system/system_ext partitions
-	// can't set apex_available, we skip checks for these APEXes
-	if a.SocSpecific() || a.DeviceSpecific() ||
-		(a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
-		return
-	}
-
-	// Coverage build adds additional dependencies for the coverage-only runtime libraries.
-	// Requiring them and their transitive depencies with apex_available is not right
-	// because they just add noise.
-	if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") || a.IsNativeCoverageNeeded(ctx) {
-		return
-	}
-
-	a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
-		if externalDep {
-			// As soon as the dependency graph crosses the APEX boundary, don't go further.
-			return false
-		}
-
-		apexName := ctx.ModuleName()
-		fromName := ctx.OtherModuleName(from)
-		toName := ctx.OtherModuleName(to)
-
-		// If `to` is not actually in the same APEX as `from` then it does not need apex_available and neither
-		// do any of its dependencies.
-		if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
-			// As soon as the dependency graph crosses the APEX boundary, don't go further.
-			return false
-		}
-
-		if to.AvailableFor(apexName) || baselineApexAvailable(apexName, toName) {
-			return true
-		}
-		ctx.ModuleErrorf("%q requires %q that doesn't list the APEX under 'apex_available'. Dependency path:%s", fromName, toName, ctx.GetPathString(true))
-		// Visit this module's dependencies to check and report any issues with their availability.
-		return true
-	})
-}
-
-func (a *apexBundle) checkUpdatable(ctx android.ModuleContext) {
-	if a.Updatable() {
-		if String(a.properties.Min_sdk_version) == "" {
-			ctx.PropertyErrorf("updatable", "updatable APEXes should set min_sdk_version as well")
-		}
-
-		a.checkJavaStableSdkVersion(ctx)
+func (f fsType) string() string {
+	switch f {
+	case ext4:
+		return ext4FsType
+	case f2fs:
+		return f2fsFsType
+	default:
+		panic(fmt.Errorf("unknown APEX payload type %d", f))
 	}
 }
 
-func (a *apexBundle) checkMinSdkVersion(ctx android.ModuleContext) {
-	if a.testApex || a.vndkApex {
-		return
-	}
-	// Meaningless to check min_sdk_version when building use_vendor modules against non-Trebleized targets
-	if proptools.Bool(a.properties.Use_vendor) && ctx.DeviceConfig().VndkVersion() == "" {
-		return
-	}
-	// apexBundle::minSdkVersion reports its own errors.
-	minSdkVersion := a.minSdkVersion(ctx)
-	android.CheckMinSdkVersion(a, ctx, minSdkVersion)
-}
-
-// Ensures that a lib providing stub isn't statically linked
-func (a *apexBundle) checkStaticLinkingToStubLibraries(ctx android.ModuleContext) {
-	// Practically, we only care about regular APEXes on the device.
-	if ctx.Host() || a.testApex || a.vndkApex {
-		return
-	}
-
-	abInfo := ctx.Provider(ApexBundleInfoProvider).(ApexBundleInfo)
-
-	a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
-		if ccm, ok := to.(*cc.Module); ok {
-			apexName := ctx.ModuleName()
-			fromName := ctx.OtherModuleName(from)
-			toName := ctx.OtherModuleName(to)
-
-			// If `to` is not actually in the same APEX as `from` then it does not need apex_available and neither
-			// do any of its dependencies.
-			if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
-				// As soon as the dependency graph crosses the APEX boundary, don't go further.
-				return false
-			}
-
-			// The dynamic linker and crash_dump tool in the runtime APEX is the only exception to this rule.
-			// It can't make the static dependencies dynamic because it can't
-			// do the dynamic linking for itself.
-			if apexName == "com.android.runtime" && (fromName == "linker" || fromName == "crash_dump") {
-				return false
-			}
-
-			isStubLibraryFromOtherApex := ccm.HasStubsVariants() && !abInfo.Contents.DirectlyInApex(toName)
-			if isStubLibraryFromOtherApex && !externalDep {
-				ctx.ModuleErrorf("%q required by %q is a native library providing stub. "+
-					"It shouldn't be included in this APEX via static linking. Dependency path: %s", to.String(), fromName, ctx.GetPathString(false))
-			}
-
-		}
-		return true
-	})
-}
-
+// Creates build rules for an APEX. It consists of the following major steps:
+//
+// 1) do some validity checks such as apex_available, min_sdk_version, etc.
+// 2) traverse the dependency tree to collect apexFile structs from them.
+// 3) some fields in apexBundle struct are configured
+// 4) generate the build rules to create the APEX. This is mostly done in builder.go.
 func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	buildFlattenedAsDefault := ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuildApps()
-	switch a.properties.ApexType {
-	case imageApex:
-		if buildFlattenedAsDefault {
-			a.suffix = imageApexSuffix
-		} else {
-			a.suffix = ""
-			a.primaryApexType = true
-
-			if ctx.Config().InstallExtraFlattenedApexes() {
-				a.requiredDeps = append(a.requiredDeps, a.Name()+flattenedSuffix)
-			}
-		}
-	case zipApex:
-		if proptools.String(a.properties.Payload_type) == "zip" {
-			a.suffix = ""
-			a.primaryApexType = true
-		} else {
-			a.suffix = zipApexSuffix
-		}
-	case flattenedApex:
-		if buildFlattenedAsDefault {
-			a.suffix = ""
-			a.primaryApexType = true
-		} else {
-			a.suffix = flattenedSuffix
-		}
-	}
-
-	if len(a.properties.Tests) > 0 && !a.testApex {
-		ctx.PropertyErrorf("tests", "property not allowed in apex module type")
-		return
-	}
-
+	////////////////////////////////////////////////////////////////////////////////////////////
+	// 1) do some validity checks such as apex_available, min_sdk_version, etc.
 	a.checkApexAvailability(ctx)
 	a.checkUpdatable(ctx)
 	a.checkMinSdkVersion(ctx)
 	a.checkStaticLinkingToStubLibraries(ctx)
+	if len(a.properties.Tests) > 0 && !a.testApex {
+		ctx.PropertyErrorf("tests", "property allowed only in apex_test module type")
+		return
+	}
 
-	handleSpecialLibs := !android.Bool(a.properties.Ignore_system_library_special_case)
+	////////////////////////////////////////////////////////////////////////////////////////////
+	// 2) traverse the dependency tree to collect apexFile structs from them.
+
+	// all the files that will be included in this APEX
+	var filesInfo []apexFile
 
 	// native lib dependencies
 	var provideNativeLibs []string
 	var requireNativeLibs []string
 
-	var filesInfo []apexFile
-	// TODO(jiyong) do this using WalkPayloadDeps
+	handleSpecialLibs := !android.Bool(a.properties.Ignore_system_library_special_case)
+
+	// TODO(jiyong): do this using WalkPayloadDeps
+	// TODO(jiyong): make this clean!!!
 	ctx.WalkDepsBlueprint(func(child, parent blueprint.Module) bool {
 		depTag := ctx.OtherModuleDependencyTag(child)
 		if _, ok := depTag.(android.ExcludeFromApexContentsTag); ok {
@@ -1519,7 +1481,7 @@
 					// - VNDK libs are only for vendors
 					// - bootstrap bionic libs are treated as provided by system
 					if c.HasStubsVariants() && !a.vndkApex && !cc.InstallToBootstrap(c.BaseModuleName(), ctx.Config()) {
-						provideNativeLibs = append(provideNativeLibs, fi.Stem())
+						provideNativeLibs = append(provideNativeLibs, fi.stem())
 					}
 					return true // track transitive dependencies
 				} else {
@@ -1545,8 +1507,8 @@
 			case javaLibTag:
 				switch child.(type) {
 				case *java.Library, *java.SdkLibrary, *java.DexImport, *java.SdkLibraryImport:
-					af := apexFileForJavaLibrary(ctx, child.(javaModule))
-					if !af.Ok() {
+					af := apexFileForJavaModule(ctx, child.(javaModule))
+					if !af.ok() {
 						ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
 						return false
 					}
@@ -1674,7 +1636,7 @@
 									a.requiredDeps = append(a.requiredDeps, name)
 								}
 							}
-							requireNativeLibs = append(requireNativeLibs, af.Stem())
+							requireNativeLibs = append(requireNativeLibs, af.stem())
 							// Don't track further
 							return false
 						}
@@ -1710,10 +1672,14 @@
 		}
 		return false
 	})
+	if a.private_key_file == nil {
+		ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
+		return
+	}
 
-	// Specific to the ART apex: dexpreopt artifacts for libcore Java libraries.
-	// Build rules are generated by the dexpreopt singleton, and here we access build artifacts
-	// via the global boot image config.
+	// Specific to the ART apex: dexpreopt artifacts for libcore Java libraries. Build rules are
+	// generated by the dexpreopt singleton, and here we access build artifacts via the global
+	// boot image config.
 	if a.artApex {
 		for arch, files := range java.DexpreoptedArtApexJars(ctx) {
 			dirInApex := filepath.Join("javalib", arch.String())
@@ -1725,12 +1691,7 @@
 		}
 	}
 
-	if a.private_key_file == nil {
-		ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
-		return
-	}
-
-	// remove duplicates in filesInfo
+	// Remove duplicates in filesInfo
 	removeDup := func(filesInfo []apexFile) []apexFile {
 		encountered := make(map[string]apexFile)
 		for _, f := range filesInfo {
@@ -1752,14 +1713,46 @@
 	}
 	filesInfo = removeDup(filesInfo)
 
-	// to have consistent build rules
+	// Sort to have consistent build rules
 	sort.Slice(filesInfo, func(i, j int) bool {
 		return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
 	})
 
+	////////////////////////////////////////////////////////////////////////////////////////////
+	// 3) some fields in apexBundle struct are configured
 	a.installDir = android.PathForModuleInstall(ctx, "apex")
 	a.filesInfo = filesInfo
 
+	// Set suffix and primaryApexType depending on the ApexType
+	buildFlattenedAsDefault := ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuildApps()
+	switch a.properties.ApexType {
+	case imageApex:
+		if buildFlattenedAsDefault {
+			a.suffix = imageApexSuffix
+		} else {
+			a.suffix = ""
+			a.primaryApexType = true
+
+			if ctx.Config().InstallExtraFlattenedApexes() {
+				a.requiredDeps = append(a.requiredDeps, a.Name()+flattenedSuffix)
+			}
+		}
+	case zipApex:
+		if proptools.String(a.properties.Payload_type) == "zip" {
+			a.suffix = ""
+			a.primaryApexType = true
+		} else {
+			a.suffix = zipApexSuffix
+		}
+	case flattenedApex:
+		if buildFlattenedAsDefault {
+			a.suffix = ""
+			a.primaryApexType = true
+		} else {
+			a.suffix = flattenedSuffix
+		}
+	}
+
 	switch proptools.StringDefault(a.properties.Payload_fs_type, ext4FsType) {
 	case ext4FsType:
 		a.payloadFsType = ext4
@@ -1774,14 +1767,11 @@
 	// the same library in the system partition, thus effectively sharing the same libraries
 	// across the APEX boundary. For unbundled APEX, all the gathered files are actually placed
 	// in the APEX.
-	a.linkToSystemLib = !ctx.Config().UnbundledBuild() &&
-		a.installable() &&
-		!proptools.Bool(a.properties.Use_vendor)
+	a.linkToSystemLib = !ctx.Config().UnbundledBuild() && a.installable() && !proptools.Bool(a.properties.Use_vendor)
 
 	// APEXes targeting other than system/system_ext partitions use vendor/product variants.
 	// So we can't link them to /system/lib libs which are core variants.
-	if a.SocSpecific() || a.DeviceSpecific() ||
-		(a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
+	if a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
 		a.linkToSystemLib = false
 	}
 
@@ -1796,31 +1786,201 @@
 		a.linkToSystemLib = false
 	}
 
-	// prepare apex_manifest.json
-	a.buildManifest(ctx, provideNativeLibs, requireNativeLibs)
-
-	a.buildFileContexts(ctx)
-
 	a.setCertificateAndPrivateKey(ctx)
+
+	a.compatSymlinks = makeCompatSymlinks(a.BaseModuleName(), ctx)
+
+	////////////////////////////////////////////////////////////////////////////////////////////
+	// 4) generate the build rules to create the APEX. This is done in builder.go.
+	a.buildManifest(ctx, provideNativeLibs, requireNativeLibs)
+	a.buildFileContexts(ctx)
 	if a.properties.ApexType == flattenedApex {
 		a.buildFlattenedApex(ctx)
 	} else {
 		a.buildUnflattenedApex(ctx)
 	}
-
-	a.compatSymlinks = makeCompatSymlinks(a.BaseModuleName(), ctx)
-
 	a.buildApexDependencyInfo(ctx)
-
 	a.buildLintReports(ctx)
-
 	a.distFiles = a.GenerateTaggedDistFiles(ctx)
 }
 
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Factory functions
+//
+
+func newApexBundle() *apexBundle {
+	module := &apexBundle{}
+
+	module.AddProperties(&module.properties)
+	module.AddProperties(&module.targetProperties)
+	module.AddProperties(&module.overridableProperties)
+
+	android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
+	android.InitDefaultableModule(module)
+	android.InitSdkAwareModule(module)
+	android.InitOverridableModule(module, &module.overridableProperties.Overrides)
+	return module
+}
+
+func ApexBundleFactory(testApex bool, artApex bool) android.Module {
+	bundle := newApexBundle()
+	bundle.testApex = testApex
+	bundle.artApex = artApex
+	return bundle
+}
+
+// apex_test is an APEX for testing. The difference from the ordinary apex module type is that
+// certain compatibility checks such as apex_available are not done for apex_test.
+func testApexBundleFactory() android.Module {
+	bundle := newApexBundle()
+	bundle.testApex = true
+	return bundle
+}
+
+// apex packages other modules into an APEX file which is a packaging format for system-level
+// components like binaries, shared libraries, etc.
+func BundleFactory() android.Module {
+	return newApexBundle()
+}
+
+type Defaults struct {
+	android.ModuleBase
+	android.DefaultsModuleBase
+}
+
+// apex_defaults provides defaultable properties to other apex modules.
+func defaultsFactory() android.Module {
+	return DefaultsFactory()
+}
+
+func DefaultsFactory(props ...interface{}) android.Module {
+	module := &Defaults{}
+
+	module.AddProperties(props...)
+	module.AddProperties(
+		&apexBundleProperties{},
+		&apexTargetBundleProperties{},
+		&overridableProperties{},
+	)
+
+	android.InitDefaultsModule(module)
+	return module
+}
+
+type OverrideApex struct {
+	android.ModuleBase
+	android.OverrideModuleBase
+}
+
+func (o *OverrideApex) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	// All the overrides happen in the base module.
+}
+
+// override_apex is used to create an apex module based on another apex module by overriding some of
+// its properties.
+func overrideApexFactory() android.Module {
+	m := &OverrideApex{}
+
+	m.AddProperties(&overridableProperties{})
+
+	android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
+	android.InitOverrideModule(m)
+	return m
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// Vality check routines
+//
+// These are called in at the very beginning of GenerateAndroidBuildActions to flag an error when
+// certain conditions are not met.
+//
+// TODO(jiyong): move these checks to a separate go file.
+
+// Entures that min_sdk_version of the included modules are equal or less than the min_sdk_version
+// of this apexBundle.
+func (a *apexBundle) checkMinSdkVersion(ctx android.ModuleContext) {
+	if a.testApex || a.vndkApex {
+		return
+	}
+	// Meaningless to check min_sdk_version when building use_vendor modules against non-Trebleized targets
+	if proptools.Bool(a.properties.Use_vendor) && ctx.DeviceConfig().VndkVersion() == "" {
+		return
+	}
+	// apexBundle::minSdkVersion reports its own errors.
+	minSdkVersion := a.minSdkVersion(ctx)
+	android.CheckMinSdkVersion(a, ctx, minSdkVersion)
+}
+
+func (a *apexBundle) minSdkVersion(ctx android.BaseModuleContext) android.ApiLevel {
+	ver := proptools.String(a.properties.Min_sdk_version)
+	if ver == "" {
+		return android.FutureApiLevel
+	}
+	apiLevel, err := android.ApiLevelFromUser(ctx, ver)
+	if err != nil {
+		ctx.PropertyErrorf("min_sdk_version", "%s", err.Error())
+		return android.NoneApiLevel
+	}
+	if apiLevel.IsPreview() {
+		// All codenames should build against "current".
+		return android.FutureApiLevel
+	}
+	return apiLevel
+}
+
+// Ensures that a lib providing stub isn't statically linked
+func (a *apexBundle) checkStaticLinkingToStubLibraries(ctx android.ModuleContext) {
+	// Practically, we only care about regular APEXes on the device.
+	if ctx.Host() || a.testApex || a.vndkApex {
+		return
+	}
+
+	abInfo := ctx.Provider(ApexBundleInfoProvider).(ApexBundleInfo)
+
+	a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
+		if ccm, ok := to.(*cc.Module); ok {
+			apexName := ctx.ModuleName()
+			fromName := ctx.OtherModuleName(from)
+			toName := ctx.OtherModuleName(to)
+
+			// If `to` is not actually in the same APEX as `from` then it does not need
+			// apex_available and neither do any of its dependencies.
+			if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
+				// As soon as the dependency graph crosses the APEX boundary, don't go further.
+				return false
+			}
+
+			// The dynamic linker and crash_dump tool in the runtime APEX is the only
+			// exception to this rule. It can't make the static dependencies dynamic
+			// because it can't do the dynamic linking for itself.
+			if apexName == "com.android.runtime" && (fromName == "linker" || fromName == "crash_dump") {
+				return false
+			}
+
+			isStubLibraryFromOtherApex := ccm.HasStubsVariants() && !abInfo.Contents.DirectlyInApex(toName)
+			if isStubLibraryFromOtherApex && !externalDep {
+				ctx.ModuleErrorf("%q required by %q is a native library providing stub. "+
+					"It shouldn't be included in this APEX via static linking. Dependency path: %s", to.String(), fromName, ctx.GetPathString(false))
+			}
+
+		}
+		return true
+	})
+}
+
 // Enforce that Java deps of the apex are using stable SDKs to compile
+func (a *apexBundle) checkUpdatable(ctx android.ModuleContext) {
+	if a.Updatable() {
+		if String(a.properties.Min_sdk_version) == "" {
+			ctx.PropertyErrorf("updatable", "updatable APEXes should set min_sdk_version as well")
+		}
+		a.checkJavaStableSdkVersion(ctx)
+	}
+}
+
 func (a *apexBundle) checkJavaStableSdkVersion(ctx android.ModuleContext) {
-	// Visit direct deps only. As long as we guarantee top-level deps are using
-	// stable SDKs, java's checkLinkType guarantees correct usage for transitive deps
+	// Visit direct deps only. As long as we guarantee top-level deps are using stable SDKs,
+	// java's checkLinkType guarantees correct usage for transitive deps
 	ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
 		tag := ctx.OtherModuleDependencyTag(module)
 		switch tag {
@@ -1834,6 +1994,59 @@
 	})
 }
 
+// Ensures that the all the dependencies are marked as available for this APEX
+func (a *apexBundle) checkApexAvailability(ctx android.ModuleContext) {
+	// Let's be practical. Availability for test, host, and the VNDK apex isn't important
+	if ctx.Host() || a.testApex || a.vndkApex {
+		return
+	}
+
+	// Because APEXes targeting other than system/system_ext partitions can't set
+	// apex_available, we skip checks for these APEXes
+	if a.SocSpecific() || a.DeviceSpecific() || (a.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface()) {
+		return
+	}
+
+	// Coverage build adds additional dependencies for the coverage-only runtime libraries.
+	// Requiring them and their transitive depencies with apex_available is not right
+	// because they just add noise.
+	if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") || a.IsNativeCoverageNeeded(ctx) {
+		return
+	}
+
+	a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
+		// As soon as the dependency graph crosses the APEX boundary, don't go further.
+		if externalDep {
+			return false
+		}
+
+		apexName := ctx.ModuleName()
+		fromName := ctx.OtherModuleName(from)
+		toName := ctx.OtherModuleName(to)
+
+		// If `to` is not actually in the same APEX as `from` then it does not need
+		// apex_available and neither do any of its dependencies.
+		if am, ok := from.(android.DepIsInSameApex); ok && !am.DepIsInSameApex(ctx, to) {
+			// As soon as the dependency graph crosses the APEX boundary, don't go
+			// further.
+			return false
+		}
+
+		if to.AvailableFor(apexName) || baselineApexAvailable(apexName, toName) {
+			return true
+		}
+		ctx.ModuleErrorf("%q requires %q that doesn't list the APEX under 'apex_available'. Dependency path:%s",
+			fromName, toName, ctx.GetPathString(true))
+		// Visit this module's dependencies to check and report any issues with their availability.
+		return true
+	})
+}
+
+var (
+	apexAvailBaseline        = makeApexAvailableBaseline()
+	inverseApexAvailBaseline = invertApexBaseline(apexAvailBaseline)
+)
+
 func baselineApexAvailable(apex, moduleName string) bool {
 	key := apex
 	moduleName = normalizeModuleName(moduleName)
@@ -1866,93 +2079,6 @@
 	return moduleName
 }
 
-func newApexBundle() *apexBundle {
-	module := &apexBundle{}
-	module.AddProperties(&module.properties)
-	module.AddProperties(&module.targetProperties)
-	module.AddProperties(&module.overridableProperties)
-	android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
-	android.InitDefaultableModule(module)
-	android.InitSdkAwareModule(module)
-	android.InitOverridableModule(module, &module.overridableProperties.Overrides)
-	return module
-}
-
-func ApexBundleFactory(testApex bool, artApex bool) android.Module {
-	bundle := newApexBundle()
-	bundle.testApex = testApex
-	bundle.artApex = artApex
-	return bundle
-}
-
-// apex_test is an APEX for testing. The difference from the ordinary apex module type is that
-// certain compatibility checks such as apex_available are not done for apex_test.
-func testApexBundleFactory() android.Module {
-	bundle := newApexBundle()
-	bundle.testApex = true
-	return bundle
-}
-
-// apex packages other modules into an APEX file which is a packaging format for system-level
-// components like binaries, shared libraries, etc.
-func BundleFactory() android.Module {
-	return newApexBundle()
-}
-
-//
-// Defaults
-//
-type Defaults struct {
-	android.ModuleBase
-	android.DefaultsModuleBase
-}
-
-func defaultsFactory() android.Module {
-	return DefaultsFactory()
-}
-
-func DefaultsFactory(props ...interface{}) android.Module {
-	module := &Defaults{}
-
-	module.AddProperties(props...)
-	module.AddProperties(
-		&apexBundleProperties{},
-		&apexTargetBundleProperties{},
-		&overridableProperties{},
-	)
-
-	android.InitDefaultsModule(module)
-	return module
-}
-
-//
-// OverrideApex
-//
-type OverrideApex struct {
-	android.ModuleBase
-	android.OverrideModuleBase
-}
-
-func (o *OverrideApex) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	// All the overrides happen in the base module.
-}
-
-// override_apex is used to create an apex module based on another apex module
-// by overriding some of its properties.
-func overrideApexFactory() android.Module {
-	m := &OverrideApex{}
-	m.AddProperties(&overridableProperties{})
-
-	android.InitAndroidMultiTargetsArchModule(m, android.DeviceSupported, android.MultilibCommon)
-	android.InitOverrideModule(m)
-	return m
-}
-
-var (
-	apexAvailBaseline        = makeApexAvailableBaseline()
-	inverseApexAvailBaseline = invertApexBaseline(apexAvailBaseline)
-)
-
 // Transform the map of apex -> modules to module -> apexes.
 func invertApexBaseline(m map[string][]string) map[string][]string {
 	r := make(map[string][]string)
@@ -1969,9 +2095,8 @@
 	return inverseApexAvailBaseline[normalizeModuleName(moduleName)]
 }
 
-// This is a map from apex to modules, which overrides the
-// apex_available setting for that particular module to make
-// it available for the apex regardless of its setting.
+// This is a map from apex to modules, which overrides the apex_available setting for that
+// particular module to make it available for the apex regardless of its setting.
 // TODO(b/147364041): remove this
 func makeApexAvailableBaseline() map[string][]string {
 	// The "Module separator"s below are employed to minimize merge conflicts.
diff --git a/apex/builder.go b/apex/builder.go
index acfb8c5..6f27dd1 100644
--- a/apex/builder.go
+++ b/apex/builder.go
@@ -195,8 +195,8 @@
 	// collect jniLibs. Notice that a.filesInfo is already sorted
 	var jniLibs []string
 	for _, fi := range a.filesInfo {
-		if fi.isJniLib && !android.InList(fi.Stem(), jniLibs) {
-			jniLibs = append(jniLibs, fi.Stem())
+		if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
+			jniLibs = append(jniLibs, fi.stem())
 		}
 	}
 	if len(jniLibs) > 0 {
@@ -363,7 +363,7 @@
 				config.Apex_config.Apex_embedded_apk_config,
 				ApkConfig{
 					Package_name: packageName,
-					Apk_path:     fi.Path(),
+					Apk_path:     fi.path(),
 				})
 		}
 	}
@@ -396,15 +396,15 @@
 	// TODO(jiyong): construct the copy rules using RuleBuilder
 	var copyCommands []string
 	for _, fi := range a.filesInfo {
-		destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
+		destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.path()).String()
 		destPathDir := filepath.Dir(destPath)
 		if fi.class == appSet {
 			copyCommands = append(copyCommands, "rm -rf "+destPathDir)
 		}
 		copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
-		if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
+		if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
 			// TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
-			pathOnDevice := filepath.Join("/system", fi.Path())
+			pathOnDevice := filepath.Join("/system", fi.path())
 			copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
 		} else {
 			if fi.class == appSet {
@@ -416,7 +416,7 @@
 			implicitInputs = append(implicitInputs, fi.builtFile)
 		}
 		// create additional symlinks pointing the file inside the APEX
-		for _, symlinkPath := range fi.SymlinkPaths() {
+		for _, symlinkPath := range fi.symlinkPaths() {
 			symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
 			copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
 		}
@@ -444,7 +444,7 @@
 		emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
 	}
 	for _, fi := range a.filesInfo {
-		emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
+		emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
 	}
 	emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
 	implicitInputs = append(implicitInputs, a.manifestPbOut)
@@ -489,7 +489,7 @@
 		var extractedAppSetPaths android.Paths
 		var extractedAppSetDirs []string
 		for _, f := range a.filesInfo {
-			pathInApex := f.Path()
+			pathInApex := f.path()
 			if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
 				executablePaths = append(executablePaths, pathInApex)
 				for _, d := range f.dataPaths {
@@ -697,6 +697,15 @@
 	a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
 }
 
+// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
+type flattenedApexContext struct {
+	android.ModuleContext
+}
+
+func (c *flattenedApexContext) InstallBypassMake() bool {
+	return true
+}
+
 func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
 	// Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
 	// reply true to `InstallBypassMake()` (thus making the call
@@ -742,7 +751,7 @@
 			apexBundleName := a.Name()
 			for _, fi := range a.filesInfo {
 				dir := filepath.Join("apex", apexBundleName, fi.installDir)
-				target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.Stem(), fi.builtFile)
+				target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.stem(), fi.builtFile)
 				for _, sym := range fi.symlinks {
 					ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
 				}
diff --git a/bazel/Android.bp b/bazel/Android.bp
new file mode 100644
index 0000000..0113726
--- /dev/null
+++ b/bazel/Android.bp
@@ -0,0 +1,10 @@
+bootstrap_go_package {
+    name: "soong-bazel",
+    pkgPath: "android/soong/bazel",
+    srcs: [
+        "properties.go",
+    ],
+    pluginFor: [
+        "soong_build",
+    ],
+}
diff --git a/bazel/properties.go b/bazel/properties.go
new file mode 100644
index 0000000..8bb1956
--- /dev/null
+++ b/bazel/properties.go
@@ -0,0 +1,27 @@
+// 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 bazel
+
+type bazelModuleProperties struct {
+	// The label of the Bazel target replacing this Soong module.
+	Label string
+}
+
+// Properties contains common module properties for migration purposes.
+type Properties struct {
+	// In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
+	// this Soong module.
+	Bazel_module bazelModuleProperties
+}
diff --git a/cc/config/x86_darwin_host.go b/cc/config/x86_darwin_host.go
index 81c907d..d7ff580 100644
--- a/cc/config/x86_darwin_host.go
+++ b/cc/config/x86_darwin_host.go
@@ -135,7 +135,7 @@
 
 func getMacTools(ctx android.PackageVarContext) *macPlatformTools {
 	macTools.once.Do(func() {
-		xcrunTool := ctx.Config().HostSystemTool("xcrun")
+		xcrunTool := ctx.Config().NonHermeticHostSystemTool("xcrun")
 
 		xcrun := func(args ...string) string {
 			if macTools.err != nil {
diff --git a/cc/prebuilt_test.go b/cc/prebuilt_test.go
index 5bf334e..ee4de6e 100644
--- a/cc/prebuilt_test.go
+++ b/cc/prebuilt_test.go
@@ -32,7 +32,7 @@
 	// * Configure that we are inside make
 	// * Add CommonOS to ensure that androidmk processing works.
 	android.RegisterAndroidMkBuildComponents(ctx)
-	android.SetInMakeForTests(config)
+	android.SetKatiEnabledForTests(config)
 
 	for _, handler := range handlers {
 		handler(config)
diff --git a/cc/strip.go b/cc/strip.go
index 18150dc..e9aec91 100644
--- a/cc/strip.go
+++ b/cc/strip.go
@@ -20,23 +20,35 @@
 	"android/soong/android"
 )
 
+// StripProperties defines the type of stripping applied to the module.
 type StripProperties struct {
 	Strip struct {
-		None                         *bool    `android:"arch_variant"`
-		All                          *bool    `android:"arch_variant"`
-		Keep_symbols                 *bool    `android:"arch_variant"`
-		Keep_symbols_list            []string `android:"arch_variant"`
-		Keep_symbols_and_debug_frame *bool    `android:"arch_variant"`
+		// whether to disable all stripping.
+		None *bool `android:"arch_variant"`
+
+		// whether to strip everything, including the mini debug info.
+		All *bool `android:"arch_variant"`
+
+		// whether to keep the symbols.
+		Keep_symbols *bool `android:"arch_variant"`
+
+		// keeps only the symbols defined here.
+		Keep_symbols_list []string `android:"arch_variant"`
+
+		// whether to keep the symbols and the debug frames.
+		Keep_symbols_and_debug_frame *bool `android:"arch_variant"`
 	} `android:"arch_variant"`
 }
 
+// Stripper defines the stripping actions and properties for a module.
 type Stripper struct {
 	StripProperties StripProperties
 }
 
+// NeedsStrip determines if stripping is required for a module.
 func (stripper *Stripper) NeedsStrip(actx android.ModuleContext) bool {
-	// TODO(ccross): enable host stripping when embedded in make?  Make never had support for stripping host binaries.
-	return (!actx.Config().EmbeddedInMake() || actx.Device()) && !Bool(stripper.StripProperties.Strip.None)
+	// TODO(ccross): enable host stripping when Kati is enabled? Make never had support for stripping host binaries.
+	return (!actx.Config().KatiEnabled() || actx.Device()) && !Bool(stripper.StripProperties.Strip.None)
 }
 
 func (stripper *Stripper) strip(actx android.ModuleContext, in android.Path, out android.ModuleOutPath,
@@ -60,11 +72,17 @@
 	}
 }
 
+// StripExecutableOrSharedLib strips a binary or shared library from its debug
+// symbols and other debugging information. The helper function
+// flagsToStripFlags may be used to generate the flags argument.
 func (stripper *Stripper) StripExecutableOrSharedLib(actx android.ModuleContext, in android.Path,
 	out android.ModuleOutPath, flags StripFlags) {
 	stripper.strip(actx, in, out, flags, false)
 }
 
+// StripStaticLib strips a static library from its debug symbols and other
+// debugging information. The helper function flagsToStripFlags may be used to
+// generate the flags argument.
 func (stripper *Stripper) StripStaticLib(actx android.ModuleContext, in android.Path, out android.ModuleOutPath,
 	flags StripFlags) {
 	stripper.strip(actx, in, out, flags, true)
diff --git a/cmd/soong_build/Android.bp b/cmd/soong_build/Android.bp
index 680c00a..441ea0d 100644
--- a/cmd/soong_build/Android.bp
+++ b/cmd/soong_build/Android.bp
@@ -27,6 +27,7 @@
         "main.go",
         "writedocs.go",
         "queryview.go",
+        "queryview_templates.go",
     ],
     testSrcs: [
         "queryview_test.go",
diff --git a/cmd/soong_build/queryview.go b/cmd/soong_build/queryview.go
index 27856b5..f5aa685 100644
--- a/cmd/soong_build/queryview.go
+++ b/cmd/soong_build/queryview.go
@@ -28,115 +28,6 @@
 	"github.com/google/blueprint/proptools"
 )
 
-const (
-	// The default `load` preamble for every generated BUILD file.
-	soongModuleLoad = `package(default_visibility = ["//visibility:public"])
-load("//build/bazel/queryview_rules:soong_module.bzl", "soong_module")
-
-`
-
-	// A macro call in the BUILD file representing a Soong module, with space
-	// for expanding more attributes.
-	soongModuleTarget = `soong_module(
-    name = "%s",
-    module_name = "%s",
-    module_type = "%s",
-    module_variant = "%s",
-    module_deps = %s,
-%s)`
-
-	// A simple provider to mark and differentiate Soong module rule shims from
-	// regular Bazel rules. Every Soong module rule shim returns a
-	// SoongModuleInfo provider, and can only depend on rules returning
-	// SoongModuleInfo in the `module_deps` attribute.
-	providersBzl = `SoongModuleInfo = provider(
-    fields = {
-        "name": "Name of module",
-        "type": "Type of module",
-        "variant": "Variant of module",
-    },
-)
-`
-
-	// The soong_module rule implementation in a .bzl file.
-	soongModuleBzl = `
-%s
-
-load("//build/bazel/queryview_rules:providers.bzl", "SoongModuleInfo")
-
-def _generic_soong_module_impl(ctx):
-    return [
-        SoongModuleInfo(
-            name = ctx.attr.module_name,
-            type = ctx.attr.module_type,
-            variant = ctx.attr.module_variant,
-        ),
-    ]
-
-generic_soong_module = rule(
-    implementation = _generic_soong_module_impl,
-    attrs = {
-        "module_name": attr.string(mandatory = True),
-        "module_type": attr.string(mandatory = True),
-        "module_variant": attr.string(),
-        "module_deps": attr.label_list(providers = [SoongModuleInfo]),
-    },
-)
-
-soong_module_rule_map = {
-%s}
-
-_SUPPORTED_TYPES = ["bool", "int", "string"]
-
-def _is_supported_type(value):
-    if type(value) in _SUPPORTED_TYPES:
-        return True
-    elif type(value) == "list":
-        supported = True
-        for v in value:
-            supported = supported and type(v) in _SUPPORTED_TYPES
-        return supported
-    else:
-        return False
-
-# soong_module is a macro that supports arbitrary kwargs, and uses module_type to
-# expand to the right underlying shim.
-def soong_module(name, module_type, **kwargs):
-    soong_module_rule = soong_module_rule_map.get(module_type)
-
-    if soong_module_rule == None:
-        # This module type does not have an existing rule to map to, so use the
-        # generic_soong_module rule instead.
-        generic_soong_module(
-            name = name,
-            module_type = module_type,
-            module_name = kwargs.pop("module_name", ""),
-            module_variant = kwargs.pop("module_variant", ""),
-            module_deps = kwargs.pop("module_deps", []),
-        )
-    else:
-        supported_kwargs = dict()
-        for key, value in kwargs.items():
-            if _is_supported_type(value):
-                supported_kwargs[key] = value
-        soong_module_rule(
-            name = name,
-            **supported_kwargs,
-        )
-`
-
-	// A rule shim for representing a Soong module type and its properties.
-	moduleRuleShim = `
-def _%[1]s_impl(ctx):
-    return [SoongModuleInfo()]
-
-%[1]s = rule(
-    implementation = _%[1]s_impl,
-    attrs = %[2]s
-)
-`
-)
-
 var (
 	// An allowlist of prop types that are surfaced from module props to rule
 	// attributes. (nested) dictionaries are notably absent here, because while
diff --git a/cmd/soong_build/queryview_templates.go b/cmd/soong_build/queryview_templates.go
new file mode 100644
index 0000000..359c0d8
--- /dev/null
+++ b/cmd/soong_build/queryview_templates.go
@@ -0,0 +1,124 @@
+// 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 main
+
+const (
+	// The default `load` preamble for every generated BUILD file.
+	soongModuleLoad = `package(default_visibility = ["//visibility:public"])
+load("//build/bazel/queryview_rules:soong_module.bzl", "soong_module")
+
+`
+
+	// A macro call in the BUILD file representing a Soong module, with space
+	// for expanding more attributes.
+	soongModuleTarget = `soong_module(
+    name = "%s",
+    module_name = "%s",
+    module_type = "%s",
+    module_variant = "%s",
+    module_deps = %s,
+%s)`
+
+	// A simple provider to mark and differentiate Soong module rule shims from
+	// regular Bazel rules. Every Soong module rule shim returns a
+	// SoongModuleInfo provider, and can only depend on rules returning
+	// SoongModuleInfo in the `module_deps` attribute.
+	providersBzl = `SoongModuleInfo = provider(
+    fields = {
+        "name": "Name of module",
+        "type": "Type of module",
+        "variant": "Variant of module",
+    },
+)
+`
+
+	// The soong_module rule implementation in a .bzl file.
+	soongModuleBzl = `
+%s
+
+load("//build/bazel/queryview_rules:providers.bzl", "SoongModuleInfo")
+
+def _generic_soong_module_impl(ctx):
+    return [
+        SoongModuleInfo(
+            name = ctx.attr.module_name,
+            type = ctx.attr.module_type,
+            variant = ctx.attr.module_variant,
+        ),
+    ]
+
+generic_soong_module = rule(
+    implementation = _generic_soong_module_impl,
+    attrs = {
+        "module_name": attr.string(mandatory = True),
+        "module_type": attr.string(mandatory = True),
+        "module_variant": attr.string(),
+        "module_deps": attr.label_list(providers = [SoongModuleInfo]),
+    },
+)
+
+soong_module_rule_map = {
+%s}
+
+_SUPPORTED_TYPES = ["bool", "int", "string"]
+
+def _is_supported_type(value):
+    if type(value) in _SUPPORTED_TYPES:
+        return True
+    elif type(value) == "list":
+        supported = True
+        for v in value:
+            supported = supported and type(v) in _SUPPORTED_TYPES
+        return supported
+    else:
+        return False
+
+# soong_module is a macro that supports arbitrary kwargs, and uses module_type to
+# expand to the right underlying shim.
+def soong_module(name, module_type, **kwargs):
+    soong_module_rule = soong_module_rule_map.get(module_type)
+
+    if soong_module_rule == None:
+        # This module type does not have an existing rule to map to, so use the
+        # generic_soong_module rule instead.
+        generic_soong_module(
+            name = name,
+            module_type = module_type,
+            module_name = kwargs.pop("module_name", ""),
+            module_variant = kwargs.pop("module_variant", ""),
+            module_deps = kwargs.pop("module_deps", []),
+        )
+    else:
+        supported_kwargs = dict()
+        for key, value in kwargs.items():
+            if _is_supported_type(value):
+                supported_kwargs[key] = value
+        soong_module_rule(
+            name = name,
+            **supported_kwargs,
+        )
+`
+
+	// A rule shim for representing a Soong module type and its properties.
+	moduleRuleShim = `
+def _%[1]s_impl(ctx):
+    return [SoongModuleInfo()]
+
+%[1]s = rule(
+    implementation = _%[1]s_impl,
+    attrs = %[2]s
+)
+`
+)
diff --git a/etc/prebuilt_etc.go b/etc/prebuilt_etc.go
index a6d1fcf..850c8f9 100644
--- a/etc/prebuilt_etc.go
+++ b/etc/prebuilt_etc.go
@@ -56,16 +56,19 @@
 	// Source file of this prebuilt. Can reference a genrule type module with the ":module" syntax.
 	Src *string `android:"path,arch_variant"`
 
-	// optional subdirectory under which this file is installed into, cannot be specified with relative_install_path, prefer relative_install_path
+	// Optional subdirectory under which this file is installed into, cannot be specified with
+	// relative_install_path, prefer relative_install_path.
 	Sub_dir *string `android:"arch_variant"`
 
-	// optional subdirectory under which this file is installed into, cannot be specified with sub_dir
+	// Optional subdirectory under which this file is installed into, cannot be specified with
+	// sub_dir.
 	Relative_install_path *string `android:"arch_variant"`
 
-	// optional name for the installed file. If unspecified, name of the module is used as the file name
+	// Optional name for the installed file. If unspecified, name of the module is used as the file
+	// name.
 	Filename *string `android:"arch_variant"`
 
-	// when set to true, and filename property is not set, the name for the installed file
+	// When set to true, and filename property is not set, the name for the installed file
 	// is the same as the file name of the source file.
 	Filename_from_src *bool `android:"arch_variant"`
 
@@ -95,8 +98,15 @@
 
 type PrebuiltEtcModule interface {
 	android.Module
+
+	// Returns the base install directory, such as "etc", "usr/share".
 	BaseDir() string
+
+	// Returns the sub install directory relative to BaseDir().
 	SubDir() string
+
+	// Returns an android.OutputPath to the intermeidate file, which is the renamed prebuilt source
+	// file.
 	OutputFile() android.OutputPath
 }
 
@@ -109,7 +119,8 @@
 	outputFilePath android.OutputPath
 	// The base install location, e.g. "etc" for prebuilt_etc, "usr/share" for prebuilt_usr_share.
 	installDirBase string
-	// The base install location when soc_specific property is set to true, e.g. "firmware" for prebuilt_firmware.
+	// The base install location when soc_specific property is set to true, e.g. "firmware" for
+	// prebuilt_firmware.
 	socInstallDirBase      string
 	installDirPath         android.InstallPath
 	additionalDependencies *android.Paths
@@ -179,14 +190,8 @@
 func (p *PrebuiltEtc) SetImageVariation(ctx android.BaseModuleContext, variation string, module android.Module) {
 }
 
-func (p *PrebuiltEtc) DepsMutator(ctx android.BottomUpMutatorContext) {
-	if p.properties.Src == nil {
-		ctx.PropertyErrorf("src", "missing prebuilt source file")
-	}
-}
-
 func (p *PrebuiltEtc) SourceFilePath(ctx android.ModuleContext) android.Path {
-	return android.PathForModuleSrc(ctx, android.String(p.properties.Src))
+	return android.PathForModuleSrc(ctx, proptools.String(p.properties.Src))
 }
 
 func (p *PrebuiltEtc) InstallDirPath() android.InstallPath {
@@ -215,36 +220,41 @@
 }
 
 func (p *PrebuiltEtc) Installable() bool {
-	return p.properties.Installable == nil || android.Bool(p.properties.Installable)
+	return p.properties.Installable == nil || proptools.Bool(p.properties.Installable)
 }
 
 func (p *PrebuiltEtc) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	p.sourceFilePath = android.PathForModuleSrc(ctx, android.String(p.properties.Src))
+	if p.properties.Src == nil {
+		ctx.PropertyErrorf("src", "missing prebuilt source file")
+		return
+	}
+	p.sourceFilePath = android.PathForModuleSrc(ctx, proptools.String(p.properties.Src))
 
 	// Determine the output file basename.
 	// If Filename is set, use the name specified by the property.
 	// If Filename_from_src is set, use the source file name.
 	// Otherwise use the module name.
-	filename := android.String(p.properties.Filename)
-	filename_from_src := android.Bool(p.properties.Filename_from_src)
-	if filename == "" {
-		if filename_from_src {
-			filename = p.sourceFilePath.Base()
-		} else {
-			filename = ctx.ModuleName()
+	filename := proptools.String(p.properties.Filename)
+	filenameFromSrc := proptools.Bool(p.properties.Filename_from_src)
+	if filename != "" {
+		if filenameFromSrc {
+			ctx.PropertyErrorf("filename_from_src", "filename is set. filename_from_src can't be true")
+			return
 		}
-	} else if filename_from_src {
-		ctx.PropertyErrorf("filename_from_src", "filename is set. filename_from_src can't be true")
-		return
+	} else if filenameFromSrc {
+		filename = p.sourceFilePath.Base()
+	} else {
+		filename = ctx.ModuleName()
 	}
 	p.outputFilePath = android.PathForModuleOut(ctx, filename).OutputPath
 
+	// Check that `sub_dir` and `relative_install_path` are not set at the same time.
 	if p.properties.Sub_dir != nil && p.properties.Relative_install_path != nil {
 		ctx.PropertyErrorf("sub_dir", "relative_install_path is set. Cannot set sub_dir")
 	}
 
-	// If soc install dir was specified and SOC specific is set, set the installDirPath to the specified
-	// socInstallDirBase.
+	// If soc install dir was specified and SOC specific is set, set the installDirPath to the
+	// specified socInstallDirBase.
 	installBaseDir := p.installDirBase
 	if p.SocSpecific() && p.socInstallDirBase != "" {
 		installBaseDir = p.socInstallDirBase
@@ -353,9 +363,10 @@
 	return module
 }
 
-// prebuilt_firmware installs a firmware file to <partition>/etc/firmware directory for system image.
-// If soc_specific property is set to true, the firmware file is installed to the vendor <partition>/firmware
-// directory for vendor image.
+// prebuilt_firmware installs a firmware file to <partition>/etc/firmware directory for system
+// image.
+// If soc_specific property is set to true, the firmware file is installed to the
+// vendor <partition>/firmware directory for vendor image.
 func PrebuiltFirmwareFactory() android.Module {
 	module := &PrebuiltEtc{}
 	module.socInstallDirBase = "firmware"
@@ -366,8 +377,8 @@
 }
 
 // prebuilt_dsp installs a DSP related file to <partition>/etc/dsp directory for system image.
-// If soc_specific property is set to true, the DSP related file is installed to the vendor <partition>/dsp
-// directory for vendor image.
+// If soc_specific property is set to true, the DSP related file is installed to the
+// vendor <partition>/dsp directory for vendor image.
 func PrebuiltDSPFactory() android.Module {
 	module := &PrebuiltEtc{}
 	module.socInstallDirBase = "dsp"
diff --git a/genrule/Android.bp b/genrule/Android.bp
index ff543a6..9690007 100644
--- a/genrule/Android.bp
+++ b/genrule/Android.bp
@@ -6,6 +6,7 @@
         "blueprint-pathtools",
         "soong",
         "soong-android",
+        "soong-bazel",
         "soong-shared",
     ],
     srcs: [
diff --git a/genrule/genrule.go b/genrule/genrule.go
index 25caadf..d5f9c70 100644
--- a/genrule/genrule.go
+++ b/genrule/genrule.go
@@ -26,6 +26,7 @@
 	"github.com/google/blueprint/proptools"
 
 	"android/soong/android"
+	"android/soong/bazel"
 )
 
 func init() {
@@ -78,13 +79,6 @@
 	blueprint.BaseDependencyTag
 	label string
 }
-
-// TODO(cparsons): Move to a common location when there is more than just
-// genrule with a bazel_module property.
-type bazelModuleProperties struct {
-	Label string
-}
-
 type generatorProperties struct {
 	// The command to run on one or more input files. Cmd supports substitution of a few variables
 	//
@@ -118,8 +112,8 @@
 	// input files to exclude
 	Exclude_srcs []string `android:"path,arch_variant"`
 
-	// in bazel-enabled mode, the bazel label to evaluate instead of this module
-	Bazel_module bazelModuleProperties
+	// Properties for Bazel migration purposes.
+	bazel.Properties
 }
 type Module struct {
 	android.ModuleBase
diff --git a/java/aar.go b/java/aar.go
index 051715d..799e763 100644
--- a/java/aar.go
+++ b/java/aar.go
@@ -836,8 +836,8 @@
 	return nil
 }
 
-func (d *AARImport) ExportedPlugins() (android.Paths, []string) {
-	return nil, nil
+func (d *AARImport) ExportedPlugins() (android.Paths, []string, bool) {
+	return nil, nil, false
 }
 
 func (a *AARImport) SrcJarArgs() ([]string, android.Paths) {
diff --git a/java/device_host_converter.go b/java/device_host_converter.go
index cd395b1..4914d74 100644
--- a/java/device_host_converter.go
+++ b/java/device_host_converter.go
@@ -167,8 +167,8 @@
 	return nil
 }
 
-func (d *DeviceHostConverter) ExportedPlugins() (android.Paths, []string) {
-	return nil, nil
+func (d *DeviceHostConverter) ExportedPlugins() (android.Paths, []string, bool) {
+	return nil, nil, false
 }
 
 func (d *DeviceHostConverter) SrcJarArgs() ([]string, android.Paths) {
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index 1f80e77..e57f323 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -255,7 +255,7 @@
 		FlagWithInput("--max-target-p ",
 			android.PathForSource(ctx, "frameworks/base/config/hiddenapi-max-target-p.txt")).
 		FlagWithInput("--max-target-o ", android.PathForSource(
-			ctx, "frameworks/base/config/hiddenapi-max-target-o.txt")).Flag("--ignore-conflicts ").
+			ctx, "frameworks/base/config/hiddenapi-max-target-o.txt")).Flag("--ignore-conflicts ").FlagWithArg("--tag ", "lo-prio").
 		FlagWithInput("--blocked ",
 			android.PathForSource(ctx, "frameworks/base/config/hiddenapi-force-blocked.txt")).
 		FlagWithInput("--blocked ",
diff --git a/java/java.go b/java/java.go
index 72ddfb2..5012279 100644
--- a/java/java.go
+++ b/java/java.go
@@ -201,7 +201,10 @@
 	// List of modules to use as annotation processors
 	Plugins []string
 
-	// List of modules to export to libraries that directly depend on this library as annotation processors
+	// List of modules to export to libraries that directly depend on this library as annotation
+	// processors.  Note that if the plugins set generates_api: true this will disable the turbine
+	// optimization on modules that depend on this module, which will reduce parallelism and cause
+	// more recompilation.
 	Exported_plugins []string
 
 	// The number of Java source entries each Javac instance can process
@@ -428,6 +431,9 @@
 	// list of plugins that this java module is exporting
 	exportedPluginClasses []string
 
+	// if true, the exported plugins generate API and require disabling turbine.
+	exportedDisableTurbine bool
+
 	// list of source files, collected from srcFiles with unique java and all kt files,
 	// will be used by android.IDEInfo struct
 	expandIDEInfoCompiledSrcs []string
@@ -513,7 +519,7 @@
 	ResourceJars() android.Paths
 	AidlIncludeDirs() android.Paths
 	ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
-	ExportedPlugins() (android.Paths, []string)
+	ExportedPlugins() (android.Paths, []string, bool)
 	SrcJarArgs() ([]string, android.Paths)
 	BaseModuleName() string
 	JacocoReportClassesFile() android.Path
@@ -1059,8 +1065,9 @@
 				// sdk lib names from dependencies are re-exported
 				j.classLoaderContexts.AddContextMap(dep.ClassLoaderContexts(), otherName)
 				deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs()...)
-				pluginJars, pluginClasses := dep.ExportedPlugins()
+				pluginJars, pluginClasses, disableTurbine := dep.ExportedPlugins()
 				addPlugins(&deps, pluginJars, pluginClasses...)
+				deps.disableTurbine = deps.disableTurbine || disableTurbine
 			case java9LibTag:
 				deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars()...)
 			case staticLibTag:
@@ -1071,8 +1078,12 @@
 				// sdk lib names from dependencies are re-exported
 				j.classLoaderContexts.AddContextMap(dep.ClassLoaderContexts(), otherName)
 				deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs()...)
-				pluginJars, pluginClasses := dep.ExportedPlugins()
+				pluginJars, pluginClasses, disableTurbine := dep.ExportedPlugins()
 				addPlugins(&deps, pluginJars, pluginClasses...)
+				// Turbine doesn't run annotation processors, so any module that uses an
+				// annotation processor that generates API is incompatible with the turbine
+				// optimization.
+				deps.disableTurbine = deps.disableTurbine || disableTurbine
 			case pluginTag:
 				if plugin, ok := dep.(*Plugin); ok {
 					if plugin.pluginProperties.Processor_class != nil {
@@ -1080,6 +1091,9 @@
 					} else {
 						addPlugins(&deps, plugin.ImplementationAndResourcesJars())
 					}
+					// Turbine doesn't run annotation processors, so any module that uses an
+					// annotation processor that generates API is incompatible with the turbine
+					// optimization.
 					deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
 				} else {
 					ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
@@ -1092,13 +1106,14 @@
 				}
 			case exportedPluginTag:
 				if plugin, ok := dep.(*Plugin); ok {
-					if plugin.pluginProperties.Generates_api != nil && *plugin.pluginProperties.Generates_api {
-						ctx.PropertyErrorf("exported_plugins", "Cannot export plugins with generates_api = true, found %v", otherName)
-					}
 					j.exportedPluginJars = append(j.exportedPluginJars, plugin.ImplementationAndResourcesJars()...)
 					if plugin.pluginProperties.Processor_class != nil {
 						j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
 					}
+					// Turbine doesn't run annotation processors, so any module that uses an
+					// annotation processor that generates API is incompatible with the turbine
+					// optimization.
+					j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
 				} else {
 					ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
 				}
@@ -1932,8 +1947,11 @@
 	return j.classLoaderContexts
 }
 
-func (j *Module) ExportedPlugins() (android.Paths, []string) {
-	return j.exportedPluginJars, j.exportedPluginClasses
+// ExportedPlugins returns the list of jars needed to run the exported plugins, the list of
+// classes for the plugins, and a boolean for whether turbine needs to be disabled due to plugins
+// that generate APIs.
+func (j *Module) ExportedPlugins() (android.Paths, []string, bool) {
+	return j.exportedPluginJars, j.exportedPluginClasses, j.exportedDisableTurbine
 }
 
 func (j *Module) SrcJarArgs() ([]string, android.Paths) {
@@ -2878,8 +2896,8 @@
 	return j.classLoaderContexts
 }
 
-func (j *Import) ExportedPlugins() (android.Paths, []string) {
-	return nil, nil
+func (j *Import) ExportedPlugins() (android.Paths, []string, bool) {
+	return nil, nil, false
 }
 
 func (j *Import) SrcJarArgs() ([]string, android.Paths) {
diff --git a/java/java_test.go b/java/java_test.go
index 27ae80a..83db443 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -313,8 +313,9 @@
 
 func TestExportedPlugins(t *testing.T) {
 	type Result struct {
-		library    string
-		processors string
+		library        string
+		processors     string
+		disableTurbine bool
 	}
 	var tests = []struct {
 		name    string
@@ -373,6 +374,18 @@
 				{library: "foo", processors: "-processor com.android.TestPlugin,com.android.TestPlugin2"},
 			},
 		},
+		{
+			name: "Exports plugin to with generates_api to dependee",
+			extra: `
+				java_library{name: "exports", exported_plugins: ["plugin_generates_api"]}
+				java_library{name: "foo", srcs: ["a.java"], libs: ["exports"]}
+				java_library{name: "bar", srcs: ["a.java"], static_libs: ["exports"]}
+			`,
+			results: []Result{
+				{library: "foo", processors: "-processor com.android.TestPlugin", disableTurbine: true},
+				{library: "bar", processors: "-processor com.android.TestPlugin", disableTurbine: true},
+			},
+		},
 	}
 
 	for _, test := range tests {
@@ -382,6 +395,11 @@
 					name: "plugin",
 					processor_class: "com.android.TestPlugin",
 				}
+				java_plugin {
+					name: "plugin_generates_api",
+					generates_api: true,
+					processor_class: "com.android.TestPlugin",
+				}
 			`+test.extra)
 
 			for _, want := range test.results {
@@ -389,6 +407,11 @@
 				if javac.Args["processor"] != want.processors {
 					t.Errorf("For library %v, expected %v, found %v", want.library, want.processors, javac.Args["processor"])
 				}
+				turbine := ctx.ModuleForTests(want.library, "android_common").MaybeRule("turbine")
+				disableTurbine := turbine.BuildParams.Rule == nil
+				if disableTurbine != want.disableTurbine {
+					t.Errorf("For library %v, expected disableTurbine %v, found %v", want.library, want.disableTurbine, disableTurbine)
+				}
 			}
 		})
 	}
diff --git a/java/lint.go b/java/lint.go
index 3df582f..11f92e5 100644
--- a/java/lint.go
+++ b/java/lint.go
@@ -447,7 +447,7 @@
 	var outputs []*lintOutputs
 	var dirs []string
 	ctx.VisitAllModules(func(m android.Module) {
-		if ctx.Config().EmbeddedInMake() && !m.ExportedToMake() {
+		if ctx.Config().KatiEnabled() && !m.ExportedToMake() {
 			return
 		}
 
diff --git a/java/sdk_library.go b/java/sdk_library.go
index ebf867d..603c808 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -438,6 +438,21 @@
 	// If set to true then don't create dist rules.
 	No_dist *bool
 
+	// The stem for the artifacts that are copied to the dist, if not specified
+	// then defaults to the base module name.
+	//
+	// For each scope the following artifacts are copied to the apistubs/<scope>
+	// directory in the dist.
+	// * stubs impl jar -> <dist-stem>.jar
+	// * API specification file -> api/<dist-stem>.txt
+	// * Removed API specification file -> api/<dist-stem>-removed.txt
+	//
+	// Also used to construct the name of the filegroup (created by prebuilt_apis)
+	// that references the latest released API and remove API specification files.
+	// * API specification filegroup -> <dist-stem>.api.<scope>.latest
+	// * Removed API specification filegroup -> <dist-stem>-removed.api.<scope>.latest
+	Dist_stem *string
+
 	// indicates whether system and test apis should be generated.
 	Generate_system_and_test_apis bool `blueprint:"mutated"`
 
@@ -1117,12 +1132,16 @@
 	}
 }
 
+func (module *SdkLibrary) distStem() string {
+	return proptools.StringDefault(module.sdkLibraryProperties.Dist_stem, module.BaseModuleName())
+}
+
 func (module *SdkLibrary) latestApiFilegroupName(apiScope *apiScope) string {
-	return ":" + module.BaseModuleName() + ".api." + apiScope.name + ".latest"
+	return ":" + module.distStem() + ".api." + apiScope.name + ".latest"
 }
 
 func (module *SdkLibrary) latestRemovedApiFilegroupName(apiScope *apiScope) string {
-	return ":" + module.BaseModuleName() + "-removed.api." + apiScope.name + ".latest"
+	return ":" + module.distStem() + "-removed.api." + apiScope.name + ".latest"
 }
 
 func childModuleVisibility(childVisibility []string) []string {
@@ -1228,7 +1247,7 @@
 	// Dist the class jar artifact for sdk builds.
 	if !Bool(module.sdkLibraryProperties.No_dist) {
 		props.Dist.Targets = []string{"sdk", "win_sdk"}
-		props.Dist.Dest = proptools.StringPtr(fmt.Sprintf("%v.jar", module.BaseModuleName()))
+		props.Dist.Dest = proptools.StringPtr(fmt.Sprintf("%v.jar", module.distStem()))
 		props.Dist.Dir = proptools.StringPtr(module.apiDistPath(apiScope))
 		props.Dist.Tag = proptools.StringPtr(".jar")
 	}
@@ -1377,7 +1396,7 @@
 	// Dist the api txt artifact for sdk builds.
 	if !Bool(module.sdkLibraryProperties.No_dist) {
 		props.Dist.Targets = []string{"sdk", "win_sdk"}
-		props.Dist.Dest = proptools.StringPtr(fmt.Sprintf("%v.txt", module.BaseModuleName()))
+		props.Dist.Dest = proptools.StringPtr(fmt.Sprintf("%v.txt", module.distStem()))
 		props.Dist.Dir = proptools.StringPtr(path.Join(module.apiDistPath(apiScope), "api"))
 	}
 
diff --git a/python/python.go b/python/python.go
index 456e167..c27a096 100644
--- a/python/python.go
+++ b/python/python.go
@@ -34,7 +34,7 @@
 }
 
 func RegisterPythonPreDepsMutators(ctx android.RegisterMutatorsContext) {
-	ctx.BottomUp("version_split", versionSplitMutator()).Parallel()
+	ctx.BottomUp("python_version", versionSplitMutator()).Parallel()
 }
 
 // the version properties that apply to python libraries and binaries.
@@ -86,6 +86,9 @@
 	// the test. the file extension can be arbitrary except for (.py).
 	Data []string `android:"path,arch_variant"`
 
+	// list of java modules that provide data that should be installed alongside the test.
+	Java_data []string
+
 	// list of the Python libraries compatible both with Python2 and Python3.
 	Libs []string `android:"arch_variant"`
 
@@ -222,6 +225,7 @@
 
 var (
 	pythonLibTag         = dependencyTag{name: "pythonLib"}
+	javaDataTag          = dependencyTag{name: "javaData"}
 	launcherTag          = dependencyTag{name: "launcher"}
 	launcherSharedLibTag = installDependencyTag{name: "launcherSharedLib"}
 	pyIdentifierRegexp   = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
@@ -254,7 +258,7 @@
 				versionNames = append(versionNames, pyVersion2)
 				versionProps = append(versionProps, base.properties.Version.Py2)
 			}
-			modules := mctx.CreateVariations(versionNames...)
+			modules := mctx.CreateLocalVariations(versionNames...)
 			if len(versionNames) > 0 {
 				mctx.AliasVariation(versionNames[0])
 			}
@@ -312,16 +316,20 @@
 func (p *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
 	android.ProtoDeps(ctx, &p.protoProperties)
 
-	if p.hasSrcExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
-		ctx.AddVariationDependencies(nil, pythonLibTag, "libprotobuf-python")
+	versionVariation := []blueprint.Variation{
+		{"python_version", p.properties.Actual_version},
 	}
-	ctx.AddVariationDependencies(nil, pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
+
+	if p.hasSrcExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
+		ctx.AddVariationDependencies(versionVariation, pythonLibTag, "libprotobuf-python")
+	}
+	ctx.AddVariationDependencies(versionVariation, pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
 
 	switch p.properties.Actual_version {
 	case pyVersion2:
 
 		if p.bootstrapper != nil && p.isEmbeddedLauncherEnabled() {
-			ctx.AddVariationDependencies(nil, pythonLibTag, "py2-stdlib")
+			ctx.AddVariationDependencies(versionVariation, pythonLibTag, "py2-stdlib")
 
 			launcherModule := "py2-launcher"
 			if p.bootstrapper.autorun() {
@@ -345,7 +353,7 @@
 	case pyVersion3:
 
 		if p.bootstrapper != nil && p.isEmbeddedLauncherEnabled() {
-			ctx.AddVariationDependencies(nil, pythonLibTag, "py3-stdlib")
+			ctx.AddVariationDependencies(versionVariation, pythonLibTag, "py3-stdlib")
 
 			launcherModule := "py3-launcher"
 			if p.bootstrapper.autorun() {
@@ -373,6 +381,11 @@
 		panic(fmt.Errorf("unknown Python Actual_version: %q for module: %q.",
 			p.properties.Actual_version, ctx.ModuleName()))
 	}
+
+	// Emulate the data property for java_data but with the arch variation overridden to "common"
+	// so that it can point to java modules.
+	javaDataVariation := []blueprint.Variation{{"arch", android.Common.String()}}
+	ctx.AddVariationDependencies(javaDataVariation, javaDataTag, p.properties.Java_data...)
 }
 
 func (p *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
@@ -419,6 +432,11 @@
 	// expand data files from "data" property.
 	expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
 
+	// Emulate the data property for java_data dependencies.
+	for _, javaData := range ctx.GetDirectDepsWithTag(javaDataTag) {
+		expandedData = append(expandedData, android.OutputFilesForModule(ctx, javaData, "")...)
+	}
+
 	// sanitize pkg_path.
 	pkgPath := String(p.properties.Pkg_path)
 	if pkgPath != "" {
diff --git a/python/test.go b/python/test.go
index f9baa46..4df71c1 100644
--- a/python/test.go
+++ b/python/test.go
@@ -45,6 +45,9 @@
 	// the test
 	Data []string `android:"path,arch_variant"`
 
+	// list of java modules that provide data that should be installed alongside the test.
+	Java_data []string
+
 	// Test options.
 	Test_options TestOptions
 }
@@ -80,6 +83,13 @@
 	for _, dataSrcPath := range dataSrcPaths {
 		test.data = append(test.data, android.DataPath{SrcPath: dataSrcPath})
 	}
+
+	// Emulate the data property for java_data dependencies.
+	for _, javaData := range ctx.GetDirectDepsWithTag(javaDataTag) {
+		for _, javaDataSrcPath := range android.OutputFilesForModule(ctx, javaData, "") {
+			test.data = append(test.data, android.DataPath{SrcPath: javaDataSrcPath})
+		}
+	}
 }
 
 func NewTest(hod android.HostOrDeviceSupported) *Module {
diff --git a/rust/strip.go b/rust/strip.go
index d1bbba6..110e3cc 100644
--- a/rust/strip.go
+++ b/rust/strip.go
@@ -19,11 +19,14 @@
 	"android/soong/cc"
 )
 
-// Stripper encapsulates cc.Stripper.
+// Stripper defines the stripping actions and properties for a module. The Rust
+// implementation reuses the C++ implementation.
 type Stripper struct {
 	cc.Stripper
 }
 
+// StripExecutableOrSharedLib strips a binary or shared library from its debug
+// symbols and other debug information.
 func (s *Stripper) StripExecutableOrSharedLib(ctx ModuleContext, in android.Path, out android.ModuleOutPath) {
 	ccFlags := cc.StripFlags{Toolchain: ctx.RustModule().ccToolchain(ctx)}
 	s.Stripper.StripExecutableOrSharedLib(ctx, in, out, ccFlags)
diff --git a/scripts/build-aml-prebuilts.sh b/scripts/build-aml-prebuilts.sh
index 89fb1a5..0c868ea 100755
--- a/scripts/build-aml-prebuilts.sh
+++ b/scripts/build-aml-prebuilts.sh
@@ -12,7 +12,7 @@
 
 export OUT_DIR=${OUT_DIR:-out}
 
-if [ -e ${OUT_DIR}/soong/.soong.in_make ]; then
+if [ -e ${OUT_DIR}/soong/.soong.kati_enabled ]; then
   # If ${OUT_DIR} has been created without --skip-make, Soong will create an
   # ${OUT_DIR}/soong/build.ninja that leaves out many targets which are
   # expected to be supplied by the .mk files, and that might cause errors in
@@ -32,8 +32,8 @@
 
 my_get_build_var() {
   # get_build_var will run Soong in normal in-make mode where it creates
-  # .soong.in_make. That would clobber our real out directory, so we need to
-  # run it in a different one.
+  # .soong.kati_enabled. That would clobber our real out directory, so we need
+  # to run it in a different one.
   OUT_DIR=${OUT_DIR}/get_build_var get_build_var "$@"
 }
 
diff --git a/sdk/testing.go b/sdk/testing.go
index 5f520e5..91aa879 100644
--- a/sdk/testing.go
+++ b/sdk/testing.go
@@ -87,7 +87,7 @@
 	// * Configure that we are inside make
 	// * Add CommonOS to ensure that androidmk processing works.
 	android.RegisterAndroidMkBuildComponents(ctx)
-	android.SetInMakeForTests(config)
+	android.SetKatiEnabledForTests(config)
 	config.Targets[android.CommonOS] = []android.Target{
 		{android.CommonOS, android.Arch{ArchType: android.Common}, android.NativeBridgeDisabled, "", "", true},
 	}
diff --git a/ui/build/build.go b/ui/build/build.go
index 1cf2023..e9196a9 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -23,13 +23,20 @@
 	"android/soong/ui/metrics"
 )
 
-// Ensures the out directory exists, and has the proper files to prevent kati
-// from recursing into it.
+// SetupOutDir ensures the out directory exists, and has the proper files to
+// prevent kati from recursing into it.
 func SetupOutDir(ctx Context, config Config) {
 	ensureEmptyFileExists(ctx, filepath.Join(config.OutDir(), "Android.mk"))
 	ensureEmptyFileExists(ctx, filepath.Join(config.OutDir(), "CleanSpec.mk"))
 	if !config.SkipMake() {
-		ensureEmptyFileExists(ctx, filepath.Join(config.SoongOutDir(), ".soong.in_make"))
+		// Run soong_build with Kati for a hybrid build, e.g. running the
+		// AndroidMk singleton and postinstall commands. Communicate this to
+		// soong_build by writing an empty .soong.kati_enabled marker file in the
+		// soong_build output directory for the soong_build primary builder to
+		// know if the user wants to run Kati after.
+		//
+		// This does not preclude running Kati for *product configuration purposes*.
+		ensureEmptyFileExists(ctx, filepath.Join(config.SoongOutDir(), ".soong.kati_enabled"))
 	}
 	// The ninja_build file is used by our buildbots to understand that the output
 	// can be parsed as ninja output.
diff --git a/ui/build/ninja.go b/ui/build/ninja.go
index fa44cb1..ffd1ab9 100644
--- a/ui/build/ninja.go
+++ b/ui/build/ninja.go
@@ -27,10 +27,16 @@
 	"android/soong/ui/status"
 )
 
+// Constructs and runs the Ninja command line with a restricted set of
+// environment variables. It's important to restrict the environment Ninja runs
+// for hermeticity reasons, and to avoid spurious rebuilds.
 func runNinja(ctx Context, config Config) {
 	ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
 	defer ctx.EndTrace()
 
+	// Sets up the FIFO status updater that reads the Ninja protobuf output, and
+	// translates it to the soong_ui status output, displaying real-time
+	// progress of the build.
 	fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
 	nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
 	defer nr.Close()
@@ -64,8 +70,12 @@
 		"-w", "missingdepfile=err")
 
 	cmd := Command(ctx, config, "ninja", executable, args...)
+
+	// Set up the nsjail sandbox Ninja runs in.
 	cmd.Sandbox = ninjaSandbox
 	if config.HasKatiSuffix() {
+		// Reads and executes a shell script from Kati that sets/unsets the
+		// environment Ninja runs in.
 		cmd.Environment.AppendFromKati(config.KatiEnvFile())
 	}
 
@@ -78,8 +88,8 @@
 		cmd.Args = append(cmd.Args, strings.Fields(extra)...)
 	}
 
-	logPath := filepath.Join(config.OutDir(), ".ninja_log")
 	ninjaHeartbeatDuration := time.Minute * 5
+	// Get the ninja heartbeat interval from the environment before it's filtered away later.
 	if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
 		// For example, "1m"
 		overrideDuration, err := time.ParseDuration(overrideText)
@@ -88,18 +98,22 @@
 		}
 	}
 
-	// Filter the environment, as ninja does not rebuild files when environment variables change.
+	// Filter the environment, as ninja does not rebuild files when environment
+	// variables change.
 	//
-	// Anything listed here must not change the output of rules/actions when the value changes,
-	// otherwise incremental builds may be unsafe. Vars explicitly set to stable values
-	// elsewhere in soong_ui are fine.
+	// Anything listed here must not change the output of rules/actions when the
+	// value changes, otherwise incremental builds may be unsafe. Vars
+	// explicitly set to stable values elsewhere in soong_ui are fine.
 	//
-	// For the majority of cases, either Soong or the makefiles should be replicating any
-	// necessary environment variables in the command line of each action that needs it.
+	// For the majority of cases, either Soong or the makefiles should be
+	// replicating any necessary environment variables in the command line of
+	// each action that needs it.
 	if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
 		ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
 	} else {
 		cmd.Environment.Allow(append([]string{
+			// Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
+			// tools can symbolize crashes.
 			"ASAN_SYMBOLIZER_PATH",
 			"HOME",
 			"JAVA_HOME",
@@ -108,14 +122,19 @@
 			"OUT_DIR",
 			"PATH",
 			"PWD",
+			// https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
 			"PYTHONDONTWRITEBYTECODE",
 			"TMPDIR",
 			"USER",
 
 			// TODO: remove these carefully
+			// Options for the address sanitizer.
 			"ASAN_OPTIONS",
+			// The list of Android app modules to be built in an unbundled manner.
 			"TARGET_BUILD_APPS",
+			// The variant of the product being built. e.g. eng, userdebug, debug.
 			"TARGET_BUILD_VARIANT",
+			// The product name of the product being built, e.g. aosp_arm, aosp_flame.
 			"TARGET_PRODUCT",
 			// b/147197813 - used by art-check-debug-apex-gen
 			"EMMA_INSTRUMENT_FRAMEWORK",
@@ -162,6 +181,7 @@
 	cmd.Environment.Set("DIST_DIR", config.DistDir())
 	cmd.Environment.Set("SHELL", "/bin/bash")
 
+	// Print the environment variables that Ninja is operating in.
 	ctx.Verboseln("Ninja environment: ")
 	envVars := cmd.Environment.Environ()
 	sort.Strings(envVars)
@@ -169,17 +189,21 @@
 		ctx.Verbosef("  %s", envVar)
 	}
 
-	// Poll the ninja log for updates; if it isn't updated enough, then we want to show some diagnostics
+	// Poll the Ninja log for updates regularly based on the heartbeat
+	// frequency. If it isn't updated enough, then we want to surface the
+	// possibility that Ninja is stuck, to the user.
 	done := make(chan struct{})
 	defer close(done)
 	ticker := time.NewTicker(ninjaHeartbeatDuration)
 	defer ticker.Stop()
-	checker := &statusChecker{}
+	ninjaChecker := &ninjaStucknessChecker{
+		logPath: filepath.Join(config.OutDir(), ".ninja_log"),
+	}
 	go func() {
 		for {
 			select {
 			case <-ticker.C:
-				checker.check(ctx, config, logPath)
+				ninjaChecker.check(ctx, config)
 			case <-done:
 				return
 			}
@@ -190,37 +214,36 @@
 	cmd.RunAndStreamOrFatal()
 }
 
-type statusChecker struct {
-	prevTime time.Time
+// A simple struct for checking if Ninja gets stuck, using timestamps.
+type ninjaStucknessChecker struct {
+	logPath     string
+	prevModTime time.Time
 }
 
-func (c *statusChecker) check(ctx Context, config Config, pathToCheck string) {
-	info, err := os.Stat(pathToCheck)
-	var newTime time.Time
+// Check that a file has been modified since the last time it was checked. If
+// the mod time hasn't changed, then assume that Ninja got stuck, and print
+// diagnostics for debugging.
+func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
+	info, err := os.Stat(c.logPath)
+	var newModTime time.Time
 	if err == nil {
-		newTime = info.ModTime()
+		newModTime = info.ModTime()
 	}
-	if newTime == c.prevTime {
-		// ninja may be stuck
-		dumpStucknessDiagnostics(ctx, config, pathToCheck, newTime)
+	if newModTime == c.prevModTime {
+		// The Ninja file hasn't been modified since the last time it was
+		// checked, so Ninja could be stuck. Output some diagnostics.
+		ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
+
+		// The "pstree" command doesn't exist on Mac, but "pstree" on Linux
+		// gives more convenient output than "ps" So, we try pstree first, and
+		// ps second
+		commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
+
+		cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
+		output := cmd.CombinedOutputOrFatal()
+		ctx.Verbose(string(output))
+
+		ctx.Verbosef("done\n")
 	}
-	c.prevTime = newTime
-}
-
-// dumpStucknessDiagnostics gets called when it is suspected that Ninja is stuck and we want to output some diagnostics
-func dumpStucknessDiagnostics(ctx Context, config Config, statusPath string, lastUpdated time.Time) {
-
-	ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", statusPath, lastUpdated)
-
-	// The "pstree" command doesn't exist on Mac, but "pstree" on Linux gives more convenient output than "ps"
-	// So, we try pstree first, and ps second
-	pstreeCommandText := fmt.Sprintf("pstree -pal %v", os.Getpid())
-	psCommandText := "ps -ef"
-	commandText := pstreeCommandText + " || " + psCommandText
-
-	cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
-	output := cmd.CombinedOutputOrFatal()
-	ctx.Verbose(string(output))
-
-	ctx.Verbosef("done\n")
+	c.prevModTime = newModTime
 }