Inherit default_visibility from parent package

Enhances the visibility mechanism to use the default_visibility
property of the closest ancestor package that has the property
specified.

Bug: 133290645
Test: m droid
Change-Id: I7248e9034a73894ac8d514f913316438c4d7c079
diff --git a/android/module.go b/android/module.go
index b912726..43b8763 100644
--- a/android/module.go
+++ b/android/module.go
@@ -226,11 +226,24 @@
 	return "//" + q.pkg + ":" + q.name
 }
 
+func (q qualifiedModuleName) isRootPackage() bool {
+	return q.pkg == "" && q.name == ""
+}
+
 // Get the id for the package containing this module.
 func (q qualifiedModuleName) getContainingPackageId() qualifiedModuleName {
 	pkg := q.pkg
 	if q.name == "" {
-		panic(fmt.Errorf("Cannot get containing package id of package module %s", pkg))
+		if pkg == "" {
+			panic(fmt.Errorf("Cannot get containing package id of root package"))
+		}
+
+		index := strings.LastIndex(pkg, "/")
+		if index == -1 {
+			pkg = ""
+		} else {
+			pkg = pkg[:index]
+		}
 	}
 	return newPackageId(pkg)
 }
@@ -276,8 +289,15 @@
 	// If a module does not specify the `visibility` property then it uses the
 	// `default_visibility` property of the `package` module in the module's package.
 	//
+	// If a module does not specify the `visibility` property then it uses the
+	// `default_visibility` property of the `package` module in the module's package.
+	//
 	// If the `default_visibility` property is not set for the module's package then
-	// the module uses `//visibility:legacy_public`.
+	// it will use the `default_visibility` of its closest ancestor package for which
+	// a `default_visibility` property is specified.
+	//
+	// If no `default_visibility` property can be found then the module uses the
+	// global default of `//visibility:legacy_public`.
 	//
 	// See https://android.googlesource.com/platform/build/soong/+/master/README.md#visibility for
 	// more details.