Documenting apex/apex.go

Mostly documentation changes, but includes a few refactorings like
changing the variable names, reording functions, reordering statements
in logical order, etc.

Bug: 173472337
Test: m

Change-Id: Ie1799c0972d63da823ad375f008018de782529d1
diff --git a/apex/apex.go b/apex/apex.go
index dff0855..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
 	})
 
+	// 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.