java_sdk_library: Expose implementation within APEX

Access to the implementation JARs is restricted to avoid code from
depending on implementation details that could change from one release
to the next which could cause compatibility issues. That is not a
problem when referenced from within the APEX that contains the
java_sdk_library.

As references from within the same APEX often need to access
implementation specific details of the java_sdk_library and doing that
from within the same APEX is safe this change all references to a
java_sdk_library made within the same APEX to use the implementation
jars instead of stub jars.

Bug: 155164730
Test: m droid
Change-Id: If239059690de61683c2ad2d8a0ce2e47286a3637
(cherry picked from commit 9b879594ed092b23a3fedfdad2b02e799c3c5dd8)
diff --git a/java/sdk_library.go b/java/sdk_library.go
index 6503e8b..43a340e 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -1295,6 +1295,24 @@
 	return android.Paths{jarPath.Path()}
 }
 
+// Get the apex name for module, "" if it is for platform.
+func getApexNameForModule(module android.Module) string {
+	if apex, ok := module.(android.ApexModule); ok {
+		return apex.ApexName()
+	}
+
+	return ""
+}
+
+// Check to see if the other module is within the same named APEX as this module.
+//
+// If either this or the other module are on the platform then this will return
+// false.
+func (module *SdkLibrary) withinSameApexAs(other android.Module) bool {
+	name := module.ApexName()
+	return name != "" && getApexNameForModule(other) == name
+}
+
 func (module *SdkLibrary) sdkJars(ctx android.BaseModuleContext, sdkVersion sdkSpec, headerJars bool) android.Paths {
 
 	// Only provide access to the implementation library if it is actually built.
@@ -1303,7 +1321,8 @@
 		//
 		// Only allow access to the implementation library in the following condition:
 		// * No sdk_version specified on the referencing module.
-		if sdkVersion.kind == sdkPrivate {
+		// * The referencing module is in the same apex as this.
+		if sdkVersion.kind == sdkPrivate || module.withinSameApexAs(ctx.Module()) {
 			if headerJars {
 				return module.HeaderJars()
 			} else {