diff options
Diffstat (limited to 'java/java.go')
-rw-r--r-- | java/java.go | 349 |
1 files changed, 232 insertions, 117 deletions
diff --git a/java/java.go b/java/java.go index 75c0a5c4b..f29f7383a 100644 --- a/java/java.go +++ b/java/java.go @@ -73,8 +73,8 @@ func registerJavaBuildComponents(ctx android.RegistrationContext) { ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel() }) - ctx.RegisterSingletonType("logtags", LogtagsSingleton) - ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory) + ctx.RegisterParallelSingletonType("logtags", LogtagsSingleton) + ctx.RegisterParallelSingletonType("kythe_java_extract", kytheExtractJavaFactory) } func RegisterJavaSdkMemberTypes() { @@ -231,10 +231,10 @@ type JavaInfo struct { HeaderJars android.Paths // set of header jars for all transitive libs deps - TransitiveLibsHeaderJars *android.DepSet + TransitiveLibsHeaderJars *android.DepSet[android.Path] // set of header jars for all transitive static libs deps - TransitiveStaticLibsHeaderJars *android.DepSet + TransitiveStaticLibsHeaderJars *android.DepSet[android.Path] // ImplementationAndResourceJars is a list of jars that contain the implementations of classes // in the module as well as any resources included in the module. @@ -273,6 +273,15 @@ type JavaInfo struct { // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be // 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] } var JavaInfoProvider = blueprint.NewProvider(JavaInfo{}) @@ -456,7 +465,9 @@ func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...) ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...) if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() { - ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...) + ctx.AddVariationDependencies(nil, proguardRaiseTag, + config.LegacyCorePlatformBootclasspathLibraries..., + ) } if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() { ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...) @@ -672,6 +683,8 @@ func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.minSdkVersion = j.MinSdkVersion(ctx) j.maxSdkVersion = j.MaxSdkVersion(ctx) + j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName()) + apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo) if !apexInfo.IsForPlatform() { j.hideApexVariantFromMake = true @@ -686,7 +699,7 @@ func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) { j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx) } - j.compile(ctx, nil) + j.compile(ctx, nil, nil, nil) // Collect the module directory for IDE info in java/jdeps.go. j.modulePaths = append(j.modulePaths, ctx.ModuleDir()) @@ -724,6 +737,7 @@ func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) { } }) j.exportedProguardFlagFiles = android.FirstUniquePaths(j.exportedProguardFlagFiles) + } func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) { @@ -813,7 +827,10 @@ func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberCo // If the min_sdk_version was set then add the canonical representation of the API level to the // snapshot. if j.deviceProperties.Min_sdk_version != nil { - canonical := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String()) + canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String()) + if err != nil { + ctx.ModuleErrorf("%s", err) + } p.MinSdkVersion = proptools.StringPtr(canonical) } @@ -931,6 +948,10 @@ type TestOptions struct { // Extra <option> tags to add to the auto generated test xml file. The "key" // is optional in each of these. Tradefed_options []tradefed.Option + + // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest. + // The "key" is optional in each of these. + Test_runner_options []tradefed.Option } type testProperties struct { @@ -1213,6 +1234,7 @@ func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, TestSuites: j.testProperties.Test_suites, Config: configs, OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options, + TestRunnerOptions: j.testProperties.Test_options.Test_runner_options, AutoGenConfig: j.testProperties.Auto_gen_config, UnitTest: j.testProperties.Test_options.Unit_test, DeviceTemplate: "${JavaTestConfigTemplate}", @@ -1411,6 +1433,8 @@ func TestHostFactory() android.Module { nil, nil) + android.InitBazelModule(module) + InitJavaModuleMultiTargets(module, android.HostSupported) return module @@ -1454,6 +1478,8 @@ func (j *Binary) HostToolPath() android.OptionalPath { } func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) { + j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName()) + if ctx.Arch().ArchType == android.Common { // Compile the jar if j.binaryProperties.Main_class != nil { @@ -1610,13 +1636,6 @@ func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleCon }) } -type JavaApiLibraryDepsInfo struct { - JavaInfo - StubsSrcJar android.Path -} - -var JavaApiLibraryDepsProvider = blueprint.NewProvider(JavaApiLibraryDepsInfo{}) - type ApiLibrary struct { android.ModuleBase android.DefaultableModuleBase @@ -1645,7 +1664,7 @@ type JavaApiLibraryProperties struct { // list of api.txt files relative to this directory that contribute to the // API surface. // This is a list of relative paths - Api_files []string + Api_files []string `android:"path"` // List of flags to be passed to the javac compiler to generate jar file Javacflags []string @@ -1658,10 +1677,11 @@ type JavaApiLibraryProperties struct { // merge zipped after metalava invocation Static_libs []string - // Java Api library to provide the full API surface text files and jar file. - // If this property is set, the provided full API surface text files and - // jar file are passed to metalava invocation. - Dep_api_srcs *string + // Java Api library to provide the full API surface stub jar file. + // If this property is set, the stub jar of this module is created by + // extracting the compiled class files provided by the + // full_api_surface_stub module. + Full_api_surface_stub *string } func ApiLibraryFactory() android.Module { @@ -1708,8 +1728,7 @@ func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder, FlagWithArg("-encoding ", "UTF-8"). FlagWithInputList("--source-files ", srcs, " ") - cmd.Flag("--no-banner"). - Flag("--color"). + cmd.Flag("--color"). Flag("--quiet"). Flag("--format=v2"). Flag("--include-annotations"). @@ -1748,35 +1767,37 @@ func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBui } } -// This method extracts the stub java files from the srcjar file provided from dep_api_srcs module -// and replaces the java stubs generated by invoking metalava in this module. +// This method extracts the stub class files from the stub jar file provided +// from full_api_surface_stub module instead of compiling the srcjar generated from invoking metalava. // This method is used because metalava can generate compilable from-text stubs only when -// the codebase encompasses all classes listed in the input API text file, but a class can extend +// the codebase encompasses all classes listed in the input API text file, and a class can extend // a class that is not within the same API domain. -func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, depApiSrcsSrcJar android.Path) { - generatedStubsList := android.PathForModuleOut(ctx, "metalava", "sources.txt") +func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, fullApiSurfaceStubJar android.Path) { + classFilesList := android.PathForModuleOut(ctx, "metalava", "classes.txt") unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir") rule.Command(). BuiltTool("list_files"). Text(stubsDir.String()). - FlagWithOutput("--out ", generatedStubsList). + FlagWithOutput("--out ", classFilesList). FlagWithArg("--extensions ", ".java"). - FlagWithArg("--root ", unzippedSrcJarDir.String()) + FlagWithArg("--root ", unzippedSrcJarDir.String()). + Flag("--classes") rule.Command(). Text("unzip"). Flag("-q"). - Input(depApiSrcsSrcJar). + Input(fullApiSurfaceStubJar). FlagWithArg("-d ", unzippedSrcJarDir.String()) rule.Command(). BuiltTool("soong_zip"). - Flag("-srcjar"). + Flag("-jar"). Flag("-write_if_changed"). + Flag("-ignore_missing_files"). FlagWithArg("-C ", unzippedSrcJarDir.String()). - FlagWithInput("-l ", generatedStubsList). - FlagWithOutput("-o ", al.stubsSrcJar) + FlagWithInput("-l ", classFilesList). + FlagWithOutput("-o ", al.stubsJarWithoutStaticLibs) } func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) { @@ -1786,8 +1807,8 @@ func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) { } ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...) ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...) - if al.properties.Dep_api_srcs != nil { - ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Dep_api_srcs)) + if al.properties.Full_api_surface_stub != nil { + ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Full_api_surface_stub)) } } @@ -1809,14 +1830,14 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { var srcFiles android.Paths var classPaths android.Paths var staticLibs android.Paths - var depApiSrcsStubsSrcJar android.Path + var depApiSrcsStubsJar android.Path ctx.VisitDirectDeps(func(dep android.Module) { tag := ctx.OtherModuleDependencyTag(dep) switch tag { case javaApiContributionTag: provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo) providerApiFile := provider.ApiFile - if providerApiFile == nil { + if providerApiFile == nil && !ctx.Config().AllowMissingDependencies() { ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name()) } srcFiles = append(srcFiles, android.PathForSource(ctx, providerApiFile.String())) @@ -1827,20 +1848,17 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo) staticLibs = append(staticLibs, provider.HeaderJars...) case depApiSrcsTag: - provider := ctx.OtherModuleProvider(dep, JavaApiLibraryDepsProvider).(JavaApiLibraryDepsInfo) - classPaths = append(classPaths, provider.HeaderJars...) - depApiSrcsStubsSrcJar = provider.StubsSrcJar + provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo) + depApiSrcsStubsJar = provider.HeaderJars[0] } }) // Add the api_files inputs for _, api := range al.properties.Api_files { - // Use MaybeExistentPathForSource since the api file might not exist during analysis. - // This will be provided by the orchestrator in the combined execution. - srcFiles = append(srcFiles, android.MaybeExistentPathForSource(ctx, ctx.ModuleDir(), api)) + srcFiles = append(srcFiles, android.PathForModuleSrc(ctx, api)) } - if srcFiles == nil { + if srcFiles == nil && !ctx.Config().AllowMissingDependencies() { ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName()) } @@ -1849,31 +1867,33 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { al.stubsFlags(ctx, cmd, stubsDir) al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar") + al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar") + al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName())) - if depApiSrcsStubsSrcJar != nil { - al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsSrcJar) - } else { - rule.Command(). - BuiltTool("soong_zip"). - Flag("-write_if_changed"). - Flag("-jar"). - FlagWithOutput("-o ", al.stubsSrcJar). - FlagWithArg("-C ", stubsDir.String()). - FlagWithArg("-D ", stubsDir.String()) + if depApiSrcsStubsJar != nil { + al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsJar) } + rule.Command(). + BuiltTool("soong_zip"). + Flag("-write_if_changed"). + Flag("-jar"). + FlagWithOutput("-o ", al.stubsSrcJar). + FlagWithArg("-C ", stubsDir.String()). + FlagWithArg("-D ", stubsDir.String()) rule.Build("metalava", "metalava merged") - al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, ctx.ModuleName(), "stubs.jar") - al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName())) + if depApiSrcsStubsJar == nil { + var flags javaBuilderFlags + flags.javaVersion = getStubsJavaVersion() + flags.javacFlags = strings.Join(al.properties.Javacflags, " ") + flags.classpath = classpath(classPaths) - var flags javaBuilderFlags - flags.javaVersion = getStubsJavaVersion() - flags.javacFlags = strings.Join(al.properties.Javacflags, " ") - flags.classpath = classpath(classPaths) + annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar") - TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{}, - android.Paths{al.stubsSrcJar}, flags, android.Paths{}) + TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{}, + android.Paths{al.stubsSrcJar}, annoSrcJar, flags, android.Paths{}) + } builder := android.NewRuleBuilder(pctx, ctx) builder.Command(). @@ -1904,13 +1924,7 @@ func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) { ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar), ImplementationJars: android.PathsIfNonNil(al.stubsJar), AidlIncludeDirs: android.Paths{}, - }) - - ctx.SetProvider(JavaApiLibraryDepsProvider, JavaApiLibraryDepsInfo{ - JavaInfo: JavaInfo{ - HeaderJars: android.PathsIfNonNil(al.stubsJar), - }, - StubsSrcJar: al.stubsSrcJar, + // No aconfig libraries on api libraries }) } @@ -2232,6 +2246,7 @@ func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) { ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile), ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile), AidlIncludeDirs: j.exportAidlIncludeDirs, + // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts }) } @@ -2611,6 +2626,7 @@ func DefaultsFactory() android.Module { &appProperties{}, &appTestProperties{}, &overridableAppProperties{}, + &hostTestProperties{}, &testProperties{}, &ImportProperties{}, &AARImportProperties{}, @@ -2651,7 +2667,7 @@ func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonC var Bool = proptools.Bool var BoolDefault = proptools.BoolDefault var String = proptools.String -var inList = android.InList +var inList = android.InList[string] // Add class loader context (CLC) of a given dependency to the current CLC. func addCLCFromDep(ctx android.ModuleContext, depModule android.Module, @@ -2708,11 +2724,29 @@ type javaResourcesAttributes struct { Resource_strip_prefix *string } +func (m *Library) javaResourcesGetSingleFilegroupStripPrefix(ctx android.TopDownMutatorContext) (string, bool) { + if otherM, ok := ctx.ModuleFromName(m.properties.Java_resources[0]); ok && len(m.properties.Java_resources) == 1 { + if fg, isFilegroup := otherM.(android.FileGroupPath); isFilegroup { + return filepath.Join(ctx.OtherModuleDir(otherM), fg.GetPath(ctx)), true + } + } + return "", false +} + func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes { var resources bazel.LabelList var resourceStripPrefix *string + if m.properties.Java_resources != nil && len(m.properties.Java_resource_dirs) > 0 { + ctx.ModuleErrorf("bp2build doesn't support both java_resources and java_resource_dirs being set on the same module.") + } + if m.properties.Java_resources != nil { + if prefix, ok := m.javaResourcesGetSingleFilegroupStripPrefix(ctx); ok { + resourceStripPrefix = proptools.StringPtr(prefix) + } else { + resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir()) + } resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources)) } @@ -2747,11 +2781,12 @@ func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorConte type javaCommonAttributes struct { *javaResourcesAttributes *kotlinAttributes - Srcs bazel.LabelListAttribute - Plugins bazel.LabelListAttribute - Javacopts bazel.StringListAttribute - Sdk_version bazel.StringAttribute - Java_version bazel.StringAttribute + Srcs bazel.LabelListAttribute + Plugins bazel.LabelListAttribute + Javacopts bazel.StringListAttribute + Sdk_version bazel.StringAttribute + Java_version bazel.StringAttribute + Errorprone_force_enable bazel.BoolAttribute } type javaDependencyLabels struct { @@ -2784,6 +2819,10 @@ type bp2BuildJavaInfo struct { 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 @@ -2792,7 +2831,7 @@ type bp2BuildJavaInfo struct { func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) { var srcs bazel.LabelListAttribute var deps bazel.LabelListAttribute - var staticDeps bazel.LabelList + var staticDeps bazel.LabelListAttribute archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{}) for axis, configToProps := range archVariantProps { @@ -2807,6 +2846,7 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) javaSrcPartition := "java" protoSrcPartition := "proto" + xsdSrcPartition := "xsd" logtagSrcPartition := "logtag" aidlSrcPartition := "aidl" kotlinPartition := "kotlin" @@ -2815,6 +2855,7 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) 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"}}, }) @@ -2822,6 +2863,8 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) kotlinSrcs := srcPartitions[kotlinPartition] javaSrcs.Append(kotlinSrcs) + staticDeps.Append(srcPartitions[xsdSrcPartition]) + if !srcPartitions[logtagSrcPartition].IsEmpty() { logtagsLibName := m.Name() + "_logtags" ctx.CreateBazelTargetModule( @@ -2875,29 +2918,38 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) }, ) - staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName}) + staticDeps.Append(bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + javaAidlLibName})) } - var javacopts []string + var javacopts bazel.StringListAttribute //[]string + plugins := bazel.MakeLabelListAttribute( + android.BazelLabelForModuleDeps(ctx, m.properties.Plugins), + ) if m.properties.Javacflags != nil { - javacopts = append(javacopts, m.properties.Javacflags...) + javacopts = bazel.MakeStringListAttribute(m.properties.Javacflags) } epEnabled := m.properties.Errorprone.Enabled - //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable - if Bool(epEnabled) { - javacopts = append(javacopts, m.properties.Errorprone.Javacflags...) + 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"})) } commonAttrs := &javaCommonAttributes{ Srcs: javaSrcs, javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx), - Plugins: bazel.MakeLabelListAttribute( - android.BazelLabelForModuleDeps(ctx, m.properties.Plugins), - ), - Javacopts: bazel.MakeStringListAttribute(javacopts), - Java_version: bazel.StringAttribute{Value: m.properties.Java_version}, - Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version}, + 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, } for axis, configToProps := range archVariantProps { @@ -2921,7 +2973,9 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) // 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. - staticDeps.Add(protoDepLabel) + if protoDepLabel != nil { + staticDeps.Append(bazel.MakeSingleLabelListAttribute(*protoDepLabel)) + } depLabels := &javaDependencyLabels{} depLabels.Deps = deps @@ -2936,7 +2990,7 @@ func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) } } } - depLabels.StaticDeps.Value.Append(staticDeps) + depLabels.StaticDeps.Append(staticDeps) hasKotlin := !kotlinSrcs.IsEmpty() commonAttrs.kotlinAttributes = &kotlinAttributes{ @@ -2970,14 +3024,14 @@ type kotlinAttributes struct { func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties { return bazel.BazelTargetModuleProperties{ Rule_class: "kt_jvm_library", - Bzl_load_location: "//build/bazel/rules/kotlin:rules.bzl", + 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:rules.bzl", + Bzl_load_location: "//build/bazel/rules/java:library.bzl", } } @@ -3060,24 +3114,15 @@ func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) { // Attribute jvm_flags var jvmFlags bazel.StringListAttribute if m.binaryProperties.Jni_libs != nil { - jniLibPackages := map[string]bool{} - for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes { - jniLibPackage := jniLibLabel.Label - indexOfColon := strings.Index(jniLibLabel.Label, ":") - if indexOfColon > 0 { - // JNI lib from other package - jniLibPackage = jniLibLabel.Label[2:indexOfColon] - } else if indexOfColon == 0 { - // JNI lib in the same package of java_binary - packageOfCurrentModule := m.GetBazelLabel(ctx, m) - jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")] - } - if _, inMap := jniLibPackages[jniLibPackage]; !inMap { - jniLibPackages[jniLibPackage] = true + 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 { + for _, jniLibPackage := range jniLibPackages { // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage) } @@ -3086,7 +3131,7 @@ func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) { props := bazel.BazelTargetModuleProperties{ Rule_class: "java_binary", - Bzl_load_location: "//build/bazel/rules/java:rules.bzl", + Bzl_load_location: "@rules_java//java:defs.bzl", } binAttrs := &javaBinaryHostAttributes{ Runtime_deps: runtimeDeps, @@ -3100,23 +3145,92 @@ func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) { return } - libName := m.Name() + "_lib" + 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.TopDownMutatorContext, m *TestHost) { + commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx) + 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.TopDownMutatorContext, libInfo libraryCreationInfo) string { + libName := libInfo.baseName + "_lib" var libProps bazel.BazelTargetModuleProperties - if bp2BuildInfo.hasKotlin { + if libInfo.hasKotlin { libProps = ktJvmLibraryBazelTargetModuleProperties() } else { libProps = javaLibraryBazelTargetModuleProperties() } libAttrs := &javaLibraryAttributes{ - Deps: deps, - javaCommonAttributes: commonAttrs, + Deps: libInfo.deps, + javaCommonAttributes: libInfo.attrs, } ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs) - binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}}) - - // Create the BazelTargetModule. - ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs) + return libName } type bazelJavaImportAttributes struct { @@ -3142,7 +3256,7 @@ func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) { } props := bazel.BazelTargetModuleProperties{ Rule_class: "java_import", - Bzl_load_location: "//build/bazel/rules/java:rules.bzl", + Bzl_load_location: "//build/bazel/rules/java:import.bzl", } name := android.RemoveOptionalPrebuiltPrefix(i.Name()) @@ -3199,7 +3313,8 @@ func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) { HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile), ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile), ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile), - //TODO(b/240308299) include AIDL information from Bazel + // TODO(b/240308299) include AIDL information from Bazel + // TODO: aconfig files? }) i.maybeInstall(ctx, jarName, outputFile) |