diff options
Diffstat (limited to 'java/java.go')
-rw-r--r-- | java/java.go | 928 |
1 files changed, 160 insertions, 768 deletions
diff --git a/java/java.go b/java/java.go index bb9357cc7..1a266b859 100644 --- a/java/java.go +++ b/java/java.go @@ -24,11 +24,8 @@ import ( "sort" "strings" - "android/soong/bazel" - "android/soong/bazel/cquery" "android/soong/remoteexec" "android/soong/testing" - "android/soong/ui/metrics/bp2build_metrics_proto" "github.com/google/blueprint" "github.com/google/blueprint/proptools" @@ -90,6 +87,14 @@ func RegisterJavaSdkMemberTypes() { android.RegisterSdkMemberType(javaTestSdkMemberType) } +type StubsLinkType int + +const ( + Unknown StubsLinkType = iota + Stubs + Implementation +) + var ( // Supports adding java header libraries to module_exports and sdk. javaHeaderLibsSdkMemberType = &librarySdkMemberType{ @@ -243,7 +248,7 @@ type ProguardSpecInfo struct { UnconditionallyExportedProguardFlags *android.DepSet[android.Path] } -var ProguardSpecInfoProvider = blueprint.NewProvider(ProguardSpecInfo{}) +var ProguardSpecInfoProvider = blueprint.NewProvider[ProguardSpecInfo]() // JavaInfo contains information about a java module for use by modules that depend on it. type JavaInfo struct { @@ -251,6 +256,8 @@ type JavaInfo struct { // against this module. If empty, ImplementationJars should be used instead. HeaderJars android.Paths + RepackagedHeaderJars android.Paths + // set of header jars for all transitive libs deps TransitiveLibsHeaderJars *android.DepSet[android.Path] @@ -298,17 +305,13 @@ type JavaInfo struct { // instrumented by jacoco. JacocoReportClassesFile android.Path - // set of aconfig flags for all transitive libs deps - // TODO(joeo): It would be nice if this were over in the aconfig package instead of here. - // In order to do that, generated_java_library would need a way doing - // collectTransitiveAconfigFiles with one of the callbacks, and having that automatically - // propagated. If we were to clean up more of the stuff on JavaInfo that's not part of - // core java rules (e.g. AidlIncludeDirs), then maybe adding more framework to do that would be - // worth it. - TransitiveAconfigFiles *android.DepSet[android.Path] + // StubsLinkType provides information about whether the provided jars are stub jars or + // implementation jars. If the provider is set by java_sdk_library, the link type is "unknown" + // and selection between the stub jar vs implementation jar is deferred to SdkLibrary.sdkJars(...) + StubsLinkType StubsLinkType } -var JavaInfoProvider = blueprint.NewProvider(JavaInfo{}) +var JavaInfoProvider = blueprint.NewProvider[JavaInfo]() // SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to // the sysprop implementation library. @@ -318,7 +321,7 @@ type SyspropPublicStubInfo struct { JavaInfo JavaInfo } -var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{}) +var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]() // Methods that need to be implemented for a module that is added to apex java_libs property. type ApexDependency interface { @@ -328,7 +331,7 @@ type ApexDependency interface { // Provides build path and install path to DEX jars. type UsesLibraryDependency interface { - DexJarBuildPath() OptionalDexJarPath + DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath DexJarInstallPath() android.Path ClassLoaderContexts() dexpreopt.ClassLoaderContextMap } @@ -418,6 +421,7 @@ var ( syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"} javaApiContributionTag = dependencyTag{name: "java-api-contribution"} depApiSrcsTag = dependencyTag{name: "dep-api-srcs"} + aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"} jniInstallTag = installDependencyTag{name: "jni install"} binaryInstallTag = installDependencyTag{name: "binary install"} usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false) @@ -531,6 +535,7 @@ type deps struct { kotlinStdlib android.Paths kotlinAnnotations android.Paths kotlinPlugins android.Paths + aconfigProtoFiles android.Paths disableTurbine bool } @@ -574,9 +579,11 @@ const ( func (v javaVersion) String() string { switch v { case JAVA_VERSION_6: - return "1.6" + // Java version 1.6 no longer supported, bumping to 1.8 + return "1.8" case JAVA_VERSION_7: - return "1.7" + // Java version 1.7 no longer supported, bumping to 1.8 + return "1.8" case JAVA_VERSION_8: return "1.8" case JAVA_VERSION_9: @@ -593,10 +600,12 @@ func (v javaVersion) String() string { func (v javaVersion) StringForKotlinc() string { // $ ./external/kotlinc/bin/kotlinc -jvm-target foo // error: unknown JVM target version: foo - // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17 + // Supported versions: 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17 switch v { + case JAVA_VERSION_6: + return "1.8" case JAVA_VERSION_7: - return "1.6" + return "1.8" case JAVA_VERSION_9: return "9" default: @@ -612,9 +621,11 @@ func (v javaVersion) usesJavaModules() bool { func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion { switch javaVersion { case "1.6", "6": - return JAVA_VERSION_6 + // Java version 1.6 no longer supported, bumping to 1.8 + return JAVA_VERSION_8 case "1.7", "7": - return JAVA_VERSION_7 + // Java version 1.7 no longer supported, bumping to 1.8 + return JAVA_VERSION_8 case "1.8", "8": return JAVA_VERSION_8 case "1.9", "9": @@ -639,7 +650,7 @@ func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) jav type Library struct { Module - exportedProguardFlagFiles android.Paths + combinedExportedProguardFlagsFile android.Path InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths) } @@ -657,9 +668,9 @@ func (j *Library) PermittedPackagesForUpdatableBootJars() []string { return j.properties.Permitted_packages } -func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool { +func shouldUncompressDex(ctx android.ModuleContext, libName string, dexpreopter *dexpreopter) bool { // Store uncompressed (and aligned) any dex files from jars in APEXes. - if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() { + if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() { return true } @@ -669,7 +680,7 @@ func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bo } // Store uncompressed dex files that are preopted on /system. - if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) { + if !dexpreopter.dexpreoptDisabled(ctx, libName) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, libName, dexpreopter.installPath)) { return true } if ctx.Config().UncompressPrivAppDex() && @@ -684,7 +695,7 @@ func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bo func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) { if dexer.dexProperties.Uncompress_dex == nil { // If the value was not force-set by the user, use reasonable default based on the module. - dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter)) + dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexpreopter)) } } @@ -696,14 +707,29 @@ func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.minSdkVersion = j.MinSdkVersion(ctx) j.maxSdkVersion = j.MaxSdkVersion(ctx) + // SdkLibrary.GenerateAndroidBuildActions(ctx) sets the stubsLinkType to Unknown. + // If the stubsLinkType has already been set to Unknown, the stubsLinkType should + // not be overridden. + if j.stubsLinkType != Unknown { + if proptools.Bool(j.properties.Is_stubs_module) { + j.stubsLinkType = Stubs + } else { + j.stubsLinkType = Implementation + } + } + j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName()) proguardSpecInfo := j.collectProguardSpecInfo(ctx) - ctx.SetProvider(ProguardSpecInfoProvider, proguardSpecInfo) - j.exportedProguardFlagFiles = proguardSpecInfo.ProguardFlagsFiles.ToList() - j.extraProguardFlagFiles = append(j.extraProguardFlagFiles, j.exportedProguardFlagFiles...) + android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo) + exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList() + j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...) + + combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags") + writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles) + j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile - apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo) + apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider) if !apexInfo.IsForPlatform() { j.hideApexVariantFromMake = true } @@ -712,7 +738,7 @@ func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.checkHeadersOnly(ctx) if ctx.Device() { j.dexpreopter.installPath = j.dexpreopter.getInstallPath( - ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")) + ctx, j.Name(), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")) j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary setUncompressDex(ctx, &j.dexpreopter, &j.dexer) j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex @@ -913,7 +939,6 @@ func LibraryFactory() android.Module { module.initModuleAndImport(module) android.InitApexModule(module) - android.InitBazelModule(module) InitJavaModule(module, android.HostAndDeviceSupported) return module } @@ -935,7 +960,6 @@ func LibraryHostFactory() android.Module { module.Module.properties.Installable = proptools.BoolPtr(true) android.InitApexModule(module) - android.InitBazelModule(module) InitJavaModule(module, android.HostSupported) return module } @@ -1086,7 +1110,7 @@ func (j *JavaTestImport) InstallInTestcases() bool { return true } -func (j *TestHost) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool { +func (j *TestHost) IsNativeCoverageNeeded(ctx android.IncomingTransitionContext) bool { return ctx.DeviceConfig().NativeCoverageEnabled() } @@ -1226,12 +1250,12 @@ func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) { } j.Test.generateAndroidBuildActionsWithConfig(ctx, configs) - ctx.SetProvider(testing.TestModuleProviderKey, testing.TestModuleProviderData{}) + android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{}) } func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.generateAndroidBuildActionsWithConfig(ctx, nil) - ctx.SetProvider(testing.TestModuleProviderKey, testing.TestModuleProviderData{}) + android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{}) } func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) { @@ -1267,7 +1291,7 @@ func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, }) ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) { - sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo) + sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider) if sharedLibInfo.SharedLibrary != nil { // Copy to an intermediate output directory to append "lib[64]" to the path, // so that it's compatible with the default rpath values. @@ -1445,8 +1469,6 @@ func TestHostFactory() android.Module { nil, nil) - android.InitBazelModule(module) - InitJavaModuleMultiTargets(module, android.HostSupported) return module @@ -1587,7 +1609,6 @@ func BinaryFactory() android.Module { android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst) android.InitDefaultableModule(module) - android.InitBazelModule(module) return module } @@ -1606,7 +1627,6 @@ func BinaryHostFactory() android.Module { android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst) android.InitDefaultableModule(module) - android.InitBazelModule(module) return module } @@ -1638,7 +1658,7 @@ type JavaApiImportInfo struct { ApiSurface string } -var JavaApiImportProvider = blueprint.NewProvider(JavaApiImportInfo{}) +var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]() func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) { var apiFile android.Path = nil @@ -1646,7 +1666,7 @@ func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleCon apiFile = android.PathForModuleSrc(ctx, String(apiFileString)) } - ctx.SetProvider(JavaApiImportProvider, JavaApiImportInfo{ + android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{ ApiFile: apiFile, ApiSurface: proptools.String(ap.properties.Api_surface), }) @@ -1843,6 +1863,7 @@ func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.Ru func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) { apiContributions := al.properties.Api_contributions addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") && + !ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") && proptools.BoolDefault(al.properties.Enable_validation, true) for _, apiContributionName := range apiContributions { ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName) @@ -1916,19 +1937,19 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { tag := ctx.OtherModuleDependencyTag(dep) switch tag { case javaApiContributionTag: - provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo) + provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider) if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() { ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name()) } srcFilesInfo = append(srcFilesInfo, provider) case libTag: - provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo) + provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider) classPaths = append(classPaths, provider.HeaderJars...) case staticLibTag: - provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo) + provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider) staticLibs = append(staticLibs, provider.HeaderJars...) case depApiSrcsTag: - provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo) + provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider) depApiSrcsStubsJar = provider.HeaderJars[0] case systemModulesTag: module := dep.(SystemModulesProvider) @@ -2016,16 +2037,17 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { ctx.Phony(ctx.ModuleName(), al.stubsJar) - ctx.SetProvider(JavaInfoProvider, JavaInfo{ + android.SetProvider(ctx, JavaInfoProvider, JavaInfo{ HeaderJars: android.PathsIfNonNil(al.stubsJar), ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar), ImplementationJars: android.PathsIfNonNil(al.stubsJar), AidlIncludeDirs: android.Paths{}, + StubsLinkType: Stubs, // No aconfig libraries on api libraries }) } -func (al *ApiLibrary) DexJarBuildPath() OptionalDexJarPath { +func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath { return al.dexJarFile } @@ -2095,13 +2117,25 @@ type ImportProperties struct { // that depend on this module, as well as to aidl for this module. Export_include_dirs []string } + + // Name of the source soong module that gets shadowed by this prebuilt + // If unspecified, follows the naming convention that the source module of + // the prebuilt is Name() without "prebuilt_" prefix + Source_module_name *string + + // Non-nil if this java_import module was dynamically created by a java_sdk_library_import + // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file + // (without any prebuilt_ prefix) + Created_by_java_sdk_library_name *string `blueprint:"mutated"` + + // Property signifying whether the module provides stubs jar or not. + Is_stubs_module *bool } type Import struct { android.ModuleBase android.DefaultableModuleBase android.ApexModuleBase - android.BazelModuleBase prebuilt android.Prebuilt // Functionality common to Module and Import. @@ -2115,6 +2149,7 @@ type Import struct { // output file containing classes.dex and resources dexJarFile OptionalDexJarPath + dexJarFileErr error dexJarInstallFile android.Path combinedClasspathFile android.Path @@ -2125,6 +2160,8 @@ type Import struct { sdkVersion android.SdkSpec minSdkVersion android.ApiLevel + + stubsLinkType StubsLinkType } var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil) @@ -2168,12 +2205,20 @@ func (j *Import) PrebuiltSrcs() []string { return j.properties.Jars } +func (j *Import) BaseModuleName() string { + return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name()) +} + func (j *Import) Name() string { return j.prebuilt.Name(j.ModuleBase.Name()) } func (j *Import) Stem() string { - return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name()) + return proptools.StringDefault(j.properties.Stem, j.BaseModuleName()) +} + +func (j *Import) CreatedByJavaSdkLibraryName() *string { + return j.properties.Created_by_java_sdk_library_name } func (a *Import) JacocoReportClassesFile() android.Path { @@ -2200,17 +2245,23 @@ func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) { } func (j *Import) commonBuildActions(ctx android.ModuleContext) { - //TODO(b/231322772) these should come from Bazel once available j.sdkVersion = j.SdkVersion(ctx) j.minSdkVersion = j.MinSdkVersion(ctx) - if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() { + apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider) + if !apexInfo.IsForPlatform() { j.hideApexVariantFromMake = true } if ctx.Windows() { j.HideFromMake() } + + if proptools.Bool(j.properties.Is_stubs_module) { + j.stubsLinkType = Stubs + } else { + j.stubsLinkType = Implementation + } } func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { @@ -2235,8 +2286,7 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.collectTransitiveHeaderJars(ctx) ctx.VisitDirectDeps(func(module android.Module) { tag := ctx.OtherModuleDependencyTag(module) - if ctx.OtherModuleHasProvider(module, JavaInfoProvider) { - dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo) + if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok { switch tag { case libTag, sdkLibTag: flags.classpath = append(flags.classpath, dep.HeaderJars...) @@ -2263,21 +2313,25 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { if ctx.Device() { // If this is a variant created for a prebuilt_apex then use the dex implementation jar // obtained from the associated deapexer module. - ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo) + ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider) if ai.ForPrebuiltApex { // Get the path of the dex implementation jar from the `deapexer` module. - di := android.FindDeapexerProviderForModule(ctx) - if di == nil { - return // An error has been reported by FindDeapexerProviderForModule. + di, err := android.FindDeapexerProviderForModule(ctx) + if err != nil { + // An error was found, possibly due to multiple apexes in the tree that export this library + // Defer the error till a client tries to call DexJarBuildPath + j.dexJarFileErr = err + j.initHiddenAPIError(err) + return } - dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(j.BaseModuleName()) + dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(j.BaseModuleName()) if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil { dexJarFile := makeDexJarPathFromPath(dexOutputPath) j.dexJarFile = dexJarFile - installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName())) + installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, ApexRootRelativePathToJavaLib(j.BaseModuleName())) j.dexJarInstallFile = installPath - j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath) + j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), installPath) setUncompressDex(ctx, &j.dexpreopter, &j.dexer) j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex @@ -2285,8 +2339,6 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.dexpreopter.inputProfilePathOnHost = profilePath } - j.dexpreopt(ctx, dexOutputPath) - // Initialize the hiddenapi structure. j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex) } else { @@ -2307,7 +2359,7 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { // Dex compilation j.dexpreopter.installPath = j.dexpreopter.getInstallPath( - ctx, android.PathForModuleInstall(ctx, "framework", jarName)) + ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", jarName)) setUncompressDex(ctx, &j.dexpreopter, &j.dexer) j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex @@ -2336,13 +2388,14 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { } } - ctx.SetProvider(JavaInfoProvider, JavaInfo{ + android.SetProvider(ctx, JavaInfoProvider, JavaInfo{ HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile), TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars, TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars, ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile), ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile), AidlIncludeDirs: j.exportAidlIncludeDirs, + StubsLinkType: j.stubsLinkType, // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts }) } @@ -2390,7 +2443,10 @@ func (j *Import) ImplementationAndResourcesJars() android.Paths { return android.Paths{j.combinedClasspathFile} } -func (j *Import) DexJarBuildPath() OptionalDexJarPath { +func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath { + if j.dexJarFileErr != nil { + ctx.ModuleErrorf(j.dexJarFileErr.Error()) + } return j.dexJarFile } @@ -2431,7 +2487,7 @@ func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext, // java_sdk_library_import with the specified base module name requires to be exported from a // prebuilt_apex/apex_set. func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string { - dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(name) + dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name) // Add the dex implementation jar to the set of exported files. files := []string{ dexJarFileApexRootRelative, @@ -2442,9 +2498,9 @@ func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []strin return files } -// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for +// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for // the java library with the specified name. -func apexRootRelativePathToJavaLib(name string) string { +func ApexRootRelativePathToJavaLib(name string) string { return filepath.Join("javalib", name+".jar") } @@ -2455,6 +2511,10 @@ func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []st return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter) } +func (j *Import) UseProfileGuidedDexpreopt() bool { + return proptools.Bool(j.importDexpreoptProperties.Dex_preopt.Profile_guided) +} + // Add compile time check for interface implementation var _ android.IDEInfo = (*Import)(nil) var _ android.IDECustomizedModuleName = (*Import)(nil) @@ -2502,7 +2562,6 @@ func ImportFactory() android.Module { android.InitPrebuiltModule(module, &module.properties.Jars) android.InitApexModule(module) - android.InitBazelModule(module) InitJavaModule(module, android.HostAndDeviceSupported) return module } @@ -2519,7 +2578,6 @@ func ImportFactoryHost() android.Module { android.InitPrebuiltModule(module, &module.properties.Jars) android.InitApexModule(module) - android.InitBazelModule(module) InitJavaModule(module, android.HostSupported) return module } @@ -2588,14 +2646,14 @@ func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) { ctx.PropertyErrorf("jars", "exactly one jar must be provided") } - apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo) + apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider) if !apexInfo.IsForPlatform() { j.hideApexVariantFromMake = true } j.dexpreopter.installPath = j.dexpreopter.getInstallPath( - ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")) - j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter) + ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar")) + j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &j.dexpreopter) inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars") dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar") @@ -2634,7 +2692,7 @@ func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.dexJarFile = makeDexJarPathFromPath(dexOutputFile) - j.dexpreopt(ctx, dexOutputFile) + j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile) if apexInfo.IsForPlatform() { ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"), @@ -2642,7 +2700,7 @@ func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) { } } -func (j *DexImport) DexJarBuildPath() OptionalDexJarPath { +func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath { return j.dexJarFile } @@ -2735,6 +2793,8 @@ func DefaultsFactory() android.Module { &LintProperties{}, &appTestHelperAppProperties{}, &JavaApiLibraryProperties{}, + &bootclasspathFragmentProperties{}, + &SourceOnlyBootclasspathProperties{}, ) android.InitDefaultsModule(module) @@ -2810,705 +2870,29 @@ func addCLCFromDep(ctx android.ModuleContext, depModule android.Module, // from its CLC should be added to the current CLC. if sdkLib != nil { clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false, - dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts()) + dep.DexJarBuildPath(ctx).PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts()) } else { clcMap.AddContextMap(dep.ClassLoaderContexts(), depName) } } -type javaResourcesAttributes struct { - Resources bazel.LabelListAttribute - Resource_strip_prefix *string - Additional_resources bazel.LabelListAttribute `blueprint:"mutated"` -} - -func (m *Library) getResourceFilegroupStripPrefix(ctx android.Bp2buildMutatorContext, resourceFilegroup string) (*string, bool) { - if otherM, ok := ctx.ModuleFromName(resourceFilegroup); ok { - if fg, isFilegroup := otherM.(android.FileGroupPath); isFilegroup { - return proptools.StringPtr(filepath.Join(ctx.OtherModuleDir(otherM), fg.GetPath(ctx))), true - } - } - return proptools.StringPtr(""), false -} - -func (m *Library) convertJavaResourcesAttributes(ctx android.Bp2buildMutatorContext) *javaResourcesAttributes { - var resources bazel.LabelList - var resourceStripPrefix *string - - additionalJavaResourcesMap := make(map[string]*javaResourcesAttributes) - - if m.properties.Java_resources != nil { - for _, res := range m.properties.Java_resources { - if prefix, isFilegroup := m.getResourceFilegroupStripPrefix(ctx, res); isFilegroup { - otherM, _ := ctx.ModuleFromName(res) - resourcesTargetName := ctx.ModuleName() + "_filegroup_resources_" + otherM.Name() - additionalJavaResourcesMap[resourcesTargetName] = &javaResourcesAttributes{ - Resources: bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, []string{res})), - Resource_strip_prefix: prefix, - } - } else { - resources.Append(android.BazelLabelForModuleSrc(ctx, []string{res})) - } - } - - if !resources.IsEmpty() { - resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir()) - } - } - - //TODO(b/179889880) handle case where glob includes files outside package - resDeps := ResourceDirsToFiles( - ctx, - m.properties.Java_resource_dirs, - m.properties.Exclude_java_resource_dirs, - m.properties.Exclude_java_resources, - ) - - for _, resDep := range resDeps { - dir, files := resDep.dir, resDep.files - - // Bazel includes the relative path from the WORKSPACE root when placing the resource - // inside the JAR file, so we need to remove that prefix - prefix := proptools.StringPtr(dir.String()) - resourcesTargetName := ctx.ModuleName() + "_resource_dir_" + dir.String() - additionalJavaResourcesMap[resourcesTargetName] = &javaResourcesAttributes{ - Resources: bazel.MakeLabelListAttribute(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files))), - Resource_strip_prefix: prefix, - } - } - - var additionalResourceLabels bazel.LabelList - if len(additionalJavaResourcesMap) > 0 { - var additionalResources []string - for resName, _ := range additionalJavaResourcesMap { - additionalResources = append(additionalResources, resName) - } - sort.Strings(additionalResources) - - for i, resName := range additionalResources { - resAttr := additionalJavaResourcesMap[resName] - if resourceStripPrefix == nil && i == 0 { - resourceStripPrefix = resAttr.Resource_strip_prefix - resources = resAttr.Resources.Value - } else if !resAttr.Resources.IsEmpty() { - ctx.CreateBazelTargetModule( - bazel.BazelTargetModuleProperties{ - Rule_class: "java_resources", - Bzl_load_location: "//build/bazel/rules/java:java_resources.bzl", - }, - android.CommonAttributes{Name: resName}, - resAttr, - ) - additionalResourceLabels.Append(android.BazelLabelForModuleSrc(ctx, []string{resName})) - } - } - - } - - return &javaResourcesAttributes{ - Resources: bazel.MakeLabelListAttribute(resources), - Resource_strip_prefix: resourceStripPrefix, - Additional_resources: bazel.MakeLabelListAttribute(additionalResourceLabels), - } -} - -type javaCommonAttributes struct { - *javaResourcesAttributes - *kotlinAttributes - Srcs bazel.LabelListAttribute - Plugins bazel.LabelListAttribute - Javacopts bazel.StringListAttribute - Sdk_version bazel.StringAttribute - Java_version bazel.StringAttribute - Errorprone_force_enable bazel.BoolAttribute - Javac_shard_size *int64 -} - -type javaDependencyLabels struct { - // Dependencies which DO NOT contribute to the API visible to upstream dependencies. - Deps bazel.LabelListAttribute - // Dependencies which DO contribute to the API visible to upstream dependencies. - StaticDeps bazel.LabelListAttribute -} - -type eventLogTagsAttributes struct { - Srcs bazel.LabelListAttribute -} - -type aidlLibraryAttributes struct { - Srcs bazel.LabelListAttribute - Tags bazel.StringListAttribute -} - -type javaAidlLibraryAttributes struct { - Deps bazel.LabelListAttribute - Tags bazel.StringListAttribute -} - -// bp2BuildJavaInfo has information needed for the conversion of java*_modules -// that is needed bor Bp2Build conversion but that requires different handling -// depending on the module type. -type bp2BuildJavaInfo struct { - // separates dependencies into dynamic dependencies and static dependencies. - DepLabels *javaDependencyLabels - hasKotlin bool -} - -func javaXsdTargetName(xsd android.XsdConfigBp2buildTargets) string { - return xsd.JavaBp2buildTargetName() -} - -// convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with -// converted attributes shared across java_* modules and a bp2BuildJavaInfo struct -// which has other non-attribute information needed for bp2build conversion -// that needs different handling depending on the module types, and thus needs -// to be returned to the calling function. -func (m *Library) convertLibraryAttrsBp2Build(ctx android.Bp2buildMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo, bool) { - var srcs bazel.LabelListAttribute - var deps bazel.LabelListAttribute - var staticDeps bazel.LabelListAttribute - - if proptools.String(m.deviceProperties.Sdk_version) == "" && m.DeviceSupported() { - // TODO(b/297356704): handle platform apis in bp2build - ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "sdk_version unset") - return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false - } else if proptools.String(m.deviceProperties.Sdk_version) == "core_platform" { - // TODO(b/297356582): handle core_platform in bp2build - ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "sdk_version core_platform") - return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false - } - - archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{}) - for axis, configToProps := range archVariantProps { - for config, p := range configToProps { - if archProps, ok := p.(*CommonProperties); ok { - archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs) - srcs.SetSelectValue(axis, config, archSrcs) - if archProps.Jarjar_rules != nil { - ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "jarjar_rules") - return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false - } - } - } - } - srcs.Append( - bazel.MakeLabelListAttribute( - android.BazelLabelForModuleSrcExcludes(ctx, - m.properties.Openjdk9.Srcs, - m.properties.Exclude_srcs))) - srcs.ResolveExcludes() - - javaSrcPartition := "java" - protoSrcPartition := "proto" - xsdSrcPartition := "xsd" - logtagSrcPartition := "logtag" - aidlSrcPartition := "aidl" - kotlinPartition := "kotlin" - srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{ - javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true}, - logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}}, - protoSrcPartition: android.ProtoSrcLabelPartition, - aidlSrcPartition: android.AidlSrcLabelPartition, - xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(javaXsdTargetName)}, - kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}}, - }) - - javaSrcs := srcPartitions[javaSrcPartition] - kotlinSrcs := srcPartitions[kotlinPartition] - javaSrcs.Append(kotlinSrcs) - - staticDeps.Append(srcPartitions[xsdSrcPartition]) - - if !srcPartitions[logtagSrcPartition].IsEmpty() { - logtagsLibName := m.Name() + "_logtags" - ctx.CreateBazelTargetModule( - bazel.BazelTargetModuleProperties{ - Rule_class: "event_log_tags", - Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl", - }, - android.CommonAttributes{Name: logtagsLibName}, - &eventLogTagsAttributes{ - Srcs: srcPartitions[logtagSrcPartition], - }, - ) - - logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}}) - javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs)) - } - - if !srcPartitions[aidlSrcPartition].IsEmpty() { - aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool { - return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName) - }) - - apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx, ctx.Module()) - - if !aidlSrcs.IsEmpty() { - aidlLibName := m.Name() + "_aidl_library" - ctx.CreateBazelTargetModule( - bazel.BazelTargetModuleProperties{ - Rule_class: "aidl_library", - Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl", - }, - android.CommonAttributes{Name: aidlLibName}, - &aidlLibraryAttributes{ - Srcs: aidlSrcs, - Tags: apexAvailableTags, - }, - ) - aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}}) - } - - javaAidlLibName := m.Name() + "_java_aidl_library" - ctx.CreateBazelTargetModule( - bazel.BazelTargetModuleProperties{ - Rule_class: "java_aidl_library", - Bzl_load_location: "//build/bazel/rules/java:java_aidl_library.bzl", - }, - android.CommonAttributes{Name: javaAidlLibName}, - &javaAidlLibraryAttributes{ - Deps: aidlLibs, - Tags: apexAvailableTags, - }, - ) - - staticDeps.Append(bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + javaAidlLibName})) - } - - var javacopts bazel.StringListAttribute //[]string - plugins := bazel.MakeLabelListAttribute( - android.BazelLabelForModuleDeps(ctx, m.properties.Plugins), - ) - if m.properties.Javacflags != nil || m.properties.Openjdk9.Javacflags != nil { - javacopts = bazel.MakeStringListAttribute( - append(append([]string{}, m.properties.Javacflags...), m.properties.Openjdk9.Javacflags...)) - } - - epEnabled := m.properties.Errorprone.Enabled - epJavacflags := m.properties.Errorprone.Javacflags - var errorproneForceEnable bazel.BoolAttribute - if epEnabled == nil { - //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable - } else if *epEnabled { - plugins.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.properties.Errorprone.Extra_check_modules))) - javacopts.Append(bazel.MakeStringListAttribute(epJavacflags)) - errorproneForceEnable.Value = epEnabled - } else { - javacopts.Append(bazel.MakeStringListAttribute([]string{"-XepDisableAllChecks"})) - } - - resourcesAttrs := m.convertJavaResourcesAttributes(ctx) - - commonAttrs := &javaCommonAttributes{ - Srcs: javaSrcs, - javaResourcesAttributes: resourcesAttrs, - Plugins: plugins, - Javacopts: javacopts, - Java_version: bazel.StringAttribute{Value: m.properties.Java_version}, - Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version}, - Errorprone_force_enable: errorproneForceEnable, - Javac_shard_size: m.properties.Javac_shard_size, - } - - for axis, configToProps := range archVariantProps { - for config, _props := range configToProps { - if archProps, ok := _props.(*CommonProperties); ok { - var libLabels []bazel.Label - for _, d := range archProps.Libs { - neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d) - neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink" - libLabels = append(libLabels, neverlinkLabel) - } - deps.SetSelectValue(axis, config, bazel.MakeLabelList(libLabels)) - } - } - } - - depLabels := &javaDependencyLabels{} - deps.Append(resourcesAttrs.Additional_resources) - depLabels.Deps = deps - - for axis, configToProps := range archVariantProps { - for config, _props := range configToProps { - if archProps, ok := _props.(*CommonProperties); ok { - archStaticLibs := android.BazelLabelForModuleDeps( - ctx, - android.LastUniqueStrings(android.CopyOf(archProps.Static_libs))) - depLabels.StaticDeps.SetSelectValue(axis, config, archStaticLibs) - } - } - } - depLabels.StaticDeps.Append(staticDeps) - - var additionalProtoDeps bazel.LabelListAttribute - additionalProtoDeps.Append(depLabels.Deps) - additionalProtoDeps.Append(depLabels.StaticDeps) - protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition], additionalProtoDeps) - // Soong does not differentiate between a java_library and the Bazel equivalent of - // a java_proto_library + proto_library pair. Instead, in Soong proto sources are - // listed directly in the srcs of a java_library, and the classes produced - // by protoc are included directly in the resulting JAR. Thus upstream dependencies - // that depend on a java_library with proto sources can link directly to the protobuf API, - // and so this should be a static dependency. - if protoDepLabel != nil { - depLabels.StaticDeps.Append(bazel.MakeSingleLabelListAttribute(*protoDepLabel)) - } - - hasKotlin := !kotlinSrcs.IsEmpty() - commonAttrs.kotlinAttributes = &kotlinAttributes{ - Kotlincflags: &m.properties.Kotlincflags, - } - if len(m.properties.Common_srcs) != 0 { - hasKotlin = true - commonAttrs.kotlinAttributes.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs)) - } - - bp2BuildInfo := &bp2BuildJavaInfo{ - DepLabels: depLabels, - hasKotlin: hasKotlin, - } - - return commonAttrs, bp2BuildInfo, true -} - -type javaLibraryAttributes struct { - *javaCommonAttributes - Deps bazel.LabelListAttribute - Exports bazel.LabelListAttribute - Neverlink bazel.BoolAttribute -} - -type kotlinAttributes struct { - Common_srcs bazel.LabelListAttribute - Kotlincflags *[]string -} - -func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties { - return bazel.BazelTargetModuleProperties{ - Rule_class: "kt_jvm_library", - Bzl_load_location: "//build/bazel/rules/kotlin:kt_jvm_library.bzl", - } -} - -func javaLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties { - return bazel.BazelTargetModuleProperties{ - Rule_class: "java_library", - Bzl_load_location: "//build/bazel/rules/java:library.bzl", - } -} - -func javaLibraryBp2Build(ctx android.Bp2buildMutatorContext, m *Library) { - commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx) - if !supported { - return - } - depLabels := bp2BuildInfo.DepLabels - - deps := depLabels.Deps - exports := depLabels.StaticDeps - if !commonAttrs.Srcs.IsEmpty() { - deps.Append(exports) // we should only append these if there are sources to use them - } else if !deps.IsEmpty() { - // java_library does not accept deps when there are no srcs because - // there is no compilation happening, but it accepts exports. - // The non-empty deps here are unnecessary as deps on the java_library - // since they aren't being propagated to any dependencies. - // So we can drop deps here. - deps = bazel.LabelListAttribute{} - } - var props bazel.BazelTargetModuleProperties - attrs := &javaLibraryAttributes{ - javaCommonAttributes: commonAttrs, - Deps: deps, - Exports: exports, - } - name := m.Name() - - if !bp2BuildInfo.hasKotlin { - props = javaLibraryBazelTargetModuleProperties() - } else { - props = ktJvmLibraryBazelTargetModuleProperties() - } - - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs) - neverlinkProp := true - neverLinkAttrs := &javaLibraryAttributes{ - Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}), - Neverlink: bazel.BoolAttribute{Value: &neverlinkProp}, - javaCommonAttributes: &javaCommonAttributes{ - Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version}, - Java_version: bazel.StringAttribute{Value: m.properties.Java_version}, - }, - } - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs) - -} - -type javaBinaryHostAttributes struct { - *javaCommonAttributes - Deps bazel.LabelListAttribute - Runtime_deps bazel.LabelListAttribute - Main_class string - Jvm_flags bazel.StringListAttribute -} - -// JavaBinaryHostBp2Build is for java_binary_host bp2build. -func javaBinaryHostBp2Build(ctx android.Bp2buildMutatorContext, m *Binary) { - commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx) - if !supported { - return - } - depLabels := bp2BuildInfo.DepLabels - - deps := depLabels.Deps - deps.Append(depLabels.StaticDeps) - if m.binaryProperties.Jni_libs != nil { - deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs))) - } - - var runtimeDeps bazel.LabelListAttribute - if commonAttrs.Srcs.IsEmpty() { - // if there are no sources, then the dependencies can only be used at runtime - runtimeDeps = deps - deps = bazel.LabelListAttribute{} - } - - mainClass := "" - if m.binaryProperties.Main_class != nil { - mainClass = *m.binaryProperties.Main_class - } - if m.properties.Manifest != nil { - mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String()) - if err != nil { - return - } - mainClass = mainClassInManifest - } - - // Attribute jvm_flags - var jvmFlags bazel.StringListAttribute - if m.binaryProperties.Jni_libs != nil { - jniLibPackages := []string{} - for _, jniLib := range m.binaryProperties.Jni_libs { - if jniLibModule, exists := ctx.ModuleFromName(jniLib); exists { - otherDir := ctx.OtherModuleDir(jniLibModule) - jniLibPackages = append(jniLibPackages, filepath.Join(otherDir, jniLib)) - } - } - jniLibPaths := []string{} - for _, jniLibPackage := range jniLibPackages { - // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH - jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage) - } - jvmFlags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")}) - } - - props := bazel.BazelTargetModuleProperties{ - Rule_class: "java_binary", - Bzl_load_location: "@rules_java//java:defs.bzl", - } - binAttrs := &javaBinaryHostAttributes{ - Runtime_deps: runtimeDeps, - Main_class: mainClass, - Jvm_flags: jvmFlags, - } - - if commonAttrs.Srcs.IsEmpty() { - binAttrs.javaCommonAttributes = commonAttrs - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs) - return - } - - libInfo := libraryCreationInfo{ - deps: deps, - attrs: commonAttrs, - baseName: m.Name(), - hasKotlin: bp2BuildInfo.hasKotlin, - } - libName := createLibraryTarget(ctx, libInfo) - binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}}) - - // Create the BazelTargetModule. - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs) -} - -type javaTestHostAttributes struct { - *javaCommonAttributes - Srcs bazel.LabelListAttribute - Deps bazel.LabelListAttribute - Runtime_deps bazel.LabelListAttribute -} - -// javaTestHostBp2Build is for java_test_host bp2build. -func javaTestHostBp2Build(ctx android.Bp2buildMutatorContext, m *TestHost) { - commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx) - if !supported { - return - } - depLabels := bp2BuildInfo.DepLabels - - deps := depLabels.Deps - deps.Append(depLabels.StaticDeps) - - var runtimeDeps bazel.LabelListAttribute - attrs := &javaTestHostAttributes{ - Runtime_deps: runtimeDeps, - } - props := bazel.BazelTargetModuleProperties{ - Rule_class: "java_test", - Bzl_load_location: "//build/bazel/rules/java:test.bzl", - } - - if commonAttrs.Srcs.IsEmpty() { - // if there are no sources, then the dependencies can only be used at runtime - attrs.Runtime_deps = deps - attrs.javaCommonAttributes = commonAttrs - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs) - return - } - - libInfo := libraryCreationInfo{ - deps: deps, - attrs: commonAttrs, - baseName: m.Name(), - hasKotlin: bp2BuildInfo.hasKotlin, - } - libName := createLibraryTarget(ctx, libInfo) - - attrs.Srcs = commonAttrs.Srcs - attrs.Deps = deps - attrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}}) - // Create the BazelTargetModule. - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs) -} - -// libraryCreationInfo encapsulates the info needed to create java_library target from -// java_binary_host or java_test_host. -type libraryCreationInfo struct { - deps bazel.LabelListAttribute - attrs *javaCommonAttributes - baseName string - hasKotlin bool -} - -// helper function that creates java_library target from java_binary_host or java_test_host, -// and returns the library target name, -func createLibraryTarget(ctx android.Bp2buildMutatorContext, libInfo libraryCreationInfo) string { - libName := libInfo.baseName + "_lib" - var libProps bazel.BazelTargetModuleProperties - if libInfo.hasKotlin { - libProps = ktJvmLibraryBazelTargetModuleProperties() - } else { - libProps = javaLibraryBazelTargetModuleProperties() - } - libAttrs := &javaLibraryAttributes{ - Deps: libInfo.deps, - javaCommonAttributes: libInfo.attrs, - } - - ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs) - return libName -} - -type bazelJavaImportAttributes struct { - Jars bazel.LabelListAttribute - Exports bazel.LabelListAttribute -} - -// java_import bp2Build converter. -func (i *Import) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) { - var jars bazel.LabelListAttribute - archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{}) - for axis, configToProps := range archVariantProps { - for config, _props := range configToProps { - if archProps, ok := _props.(*ImportProperties); ok { - archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil)) - jars.SetSelectValue(axis, config, archJars) - } - } - } - - attrs := &bazelJavaImportAttributes{ - Jars: jars, - } - props := bazel.BazelTargetModuleProperties{ - Rule_class: "java_import", - Bzl_load_location: "//build/bazel/rules/java:import.bzl", - } - - name := android.RemoveOptionalPrebuiltPrefix(i.Name()) - - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs) - - neverlink := true - neverlinkAttrs := &javaLibraryAttributes{ - Neverlink: bazel.BoolAttribute{Value: &neverlink}, - Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}), - javaCommonAttributes: &javaCommonAttributes{ - Sdk_version: bazel.StringAttribute{Value: proptools.StringPtr("none")}, - }, - } - ctx.CreateBazelTargetModule( - javaLibraryBazelTargetModuleProperties(), - android.CommonAttributes{Name: name + "-neverlink"}, - neverlinkAttrs) -} - -var _ android.MixedBuildBuildable = (*Import)(nil) - -func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string { - return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i)) -} - -func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) { - i.commonBuildActions(ctx) - - bazelCtx := ctx.Config().BazelContext - filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx)) - if err != nil { - ctx.ModuleErrorf(err.Error()) - return - } - - bazelJars := android.Paths{} - for _, bazelOutputFile := range filePaths { - bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile)) - } - - jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar" - outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName) - TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars, - android.OptionalPath{}, // manifest - false, // stripDirEntries - []string{}, // filesToStrip - []string{}, // dirsToStrip - ) - i.combinedClasspathFile = outputFile - - ctx.SetProvider(JavaInfoProvider, JavaInfo{ - HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile), - ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile), - ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile), - // TODO(b/240308299) include AIDL information from Bazel - // TODO: aconfig files? - }) - - i.maybeInstall(ctx, jarName, outputFile) -} - -func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) { - bazelCtx := ctx.Config().BazelContext - bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx)) -} +type JavaApiContributionImport struct { + JavaApiContribution -func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool { - return true + prebuilt android.Prebuilt + prebuiltProperties javaApiContributionImportProperties } -type JavaApiContributionImport struct { - JavaApiContribution +type javaApiContributionImportProperties struct { + // Name of the source soong module that gets shadowed by this prebuilt + // If unspecified, follows the naming convention that the source module of + // the prebuilt is Name() without "prebuilt_" prefix + Source_module_name *string - prebuilt android.Prebuilt + // Non-nil if this java_import module was dynamically created by a java_sdk_library_import + // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file + // (without any prebuilt_ prefix) + Created_by_java_sdk_library_name *string `blueprint:"mutated"` } func ApiContributionImportFactory() android.Module { @@ -3516,7 +2900,7 @@ func ApiContributionImportFactory() android.Module { android.InitAndroidModule(module) android.InitDefaultableModule(module) android.InitPrebuiltModule(module, &[]string{""}) - module.AddProperties(&module.properties) + module.AddProperties(&module.properties, &module.prebuiltProperties) module.AddProperties(&module.sdkLibraryComponentProperties) return module } @@ -3529,6 +2913,14 @@ func (module *JavaApiContributionImport) Name() string { return module.prebuilt.Name(module.ModuleBase.Name()) } +func (j *JavaApiContributionImport) BaseModuleName() string { + return proptools.StringDefault(j.prebuiltProperties.Source_module_name, j.ModuleBase.Name()) +} + +func (j *JavaApiContributionImport) CreatedByJavaSdkLibraryName() *string { + return j.prebuiltProperties.Created_by_java_sdk_library_name +} + func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) { ap.JavaApiContribution.GenerateAndroidBuildActions(ctx) } |