blob: c8bb22fee955c5b4d784de8482d1ae18cb4646f0 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17// This file contains the module types for compiling Java for Android, and converts the properties
Colin Cross46c9b8b2017-06-22 16:51:17 -070018// into the flags and filenames necessary to pass to the Module. The final creation of the rules
Colin Cross2fe66872015-03-30 17:20:39 -070019// is handled in builder.go
20
21import (
Colin Crossf19b9bb2018-03-26 14:42:44 -070022 "fmt"
Colin Crossfc3674a2017-09-18 17:41:52 -070023 "path/filepath"
Wei Libafb6d62021-12-10 03:14:59 -080024 "strings"
Colin Cross2fe66872015-03-30 17:20:39 -070025
Wei Libafb6d62021-12-10 03:14:59 -080026 "android/soong/bazel"
Sam Delmerico277795c2022-02-25 17:04:37 +000027 "android/soong/bazel/cquery"
Sam Delmerico4e272292022-01-06 20:03:51 +000028
Colin Cross2fe66872015-03-30 17:20:39 -070029 "github.com/google/blueprint"
Colin Cross76b5f0c2017-08-29 16:02:06 -070030 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080033 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010034 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070035 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070036 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070037)
38
Colin Cross463a90e2015-06-17 14:20:06 -070039func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010040 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000041
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080042 RegisterJavaSdkMemberTypes()
43}
44
Paul Duffin535e0a12021-03-30 23:34:32 +010045func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080046 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
47
48 ctx.RegisterModuleType("java_library", LibraryFactory)
49 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
50 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
51 ctx.RegisterModuleType("java_binary", BinaryFactory)
52 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
53 ctx.RegisterModuleType("java_test", TestFactory)
54 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
55 ctx.RegisterModuleType("java_test_host", TestHostFactory)
56 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
57 ctx.RegisterModuleType("java_import", ImportFactory)
58 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
59 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
60 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
61 ctx.RegisterModuleType("dex_import", DexImportFactory)
62
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010063 // This mutator registers dependencies on dex2oat for modules that should be
64 // dexpreopted. This is done late when the final variants have been
65 // established, to not get the dependencies split into the wrong variants and
66 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080067 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
68 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040069 // needs access to ApexInfoProvider which is available after variant creation
70 ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080071 })
72
73 ctx.RegisterSingletonType("logtags", LogtagsSingleton)
74 ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
75}
76
77func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000078 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000079 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010080 android.RegisterSdkMemberType(javaLibsSdkMemberType)
81 android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
Jiakai Zhangea180332021-09-26 08:58:02 +000082 android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010083 android.RegisterSdkMemberType(javaTestSdkMemberType)
84}
85
86var (
87 // Supports adding java header libraries to module_exports and sdk.
88 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
89 android.SdkMemberTypeBase{
90 PropertyName: "java_header_libs",
91 SupportsSdk: true,
92 },
93 func(_ android.SdkMemberContext, j *Library) android.Path {
94 headerJars := j.HeaderJars()
95 if len(headerJars) != 1 {
96 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
97 }
98
99 return headerJars[0]
100 },
101 sdkSnapshotFilePathForJar,
102 copyEverythingToSnapshot,
103 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000104
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000105 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100106 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000107 implementationJars := j.ImplementationAndResourcesJars()
108 if len(implementationJars) != 1 {
109 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
110 }
111 return implementationJars[0]
112 }
113
Paul Duffin2da04242021-04-23 19:43:28 +0100114 // Supports adding java implementation libraries to module_exports but not sdk.
115 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000116 android.SdkMemberTypeBase{
117 PropertyName: "java_libs",
118 },
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000119 exportImplementationClassesJar,
Paul Duffindb170e42020-12-08 17:48:25 +0000120 sdkSnapshotFilePathForJar,
121 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100122 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000123
Paul Duffin13648912022-07-15 13:12:35 +0000124 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
125 // In the S build the build will break if updatable-media does not provide a full implementation
126 // jar. That issue was fixed in Tiramisu by b/229932396.
127 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
128 return true
129 }
130
131 return false
132 }
133
Paul Duffin2da04242021-04-23 19:43:28 +0100134 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000135 //
136 // The build has some implicit dependencies (via the boot jars configuration) on a number of
137 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
138 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
139 // used outside those mainline modules.
140 //
141 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
142 // either java_libs, or java_header_libs would end up exporting more information than was strictly
143 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
144 // sdk/module_exports without exposing any unnecessary information.
Paul Duffin2da04242021-04-23 19:43:28 +0100145 javaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffindb170e42020-12-08 17:48:25 +0000146 android.SdkMemberTypeBase{
147 PropertyName: "java_boot_libs",
148 SupportsSdk: true,
149 },
Paul Duffin5c211452021-07-15 12:42:44 +0100150 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000151 if snapshotRequiresImplementationJar(ctx) {
152 return exportImplementationClassesJar(ctx, j)
153 }
154
Paul Duffin5c211452021-07-15 12:42:44 +0100155 // Java boot libs are only provided in the SDK to provide access to their dex implementation
156 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
157 // actual implementation jar but the java_import will need a file that exists so just copy an
158 // empty file. Any attempt to use that file as a jar will cause a build error.
159 return ctx.SnapshotBuilder().EmptyFile()
160 },
Paul Duffin13648912022-07-15 13:12:35 +0000161 func(ctx android.SdkMemberContext, osPrefix, name string) string {
162 if snapshotRequiresImplementationJar(ctx) {
163 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
164 }
165
Paul Duffin5c211452021-07-15 12:42:44 +0100166 // Create a special name for the implementation jar to try and provide some useful information
167 // to a developer that attempts to compile against this.
168 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
169 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
170 },
Paul Duffindb170e42020-12-08 17:48:25 +0000171 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100172 }
Paul Duffindb170e42020-12-08 17:48:25 +0000173
Jiakai Zhangea180332021-09-26 08:58:02 +0000174 // Supports adding java systemserver libraries to module_exports and sdk.
175 //
176 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
177 // of modules that are part of the java systemserver classpath and which are provided by mainline
178 // modules but which are not otherwise used outside those mainline modules.
179 //
180 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
181 // either java_libs, or java_header_libs would end up exporting more information than was strictly
182 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
183 // the sdk/module_exports without exposing any unnecessary information.
184 javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
185 android.SdkMemberTypeBase{
186 PropertyName: "java_systemserver_libs",
187 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000188
189 // This was only added in Tiramisu.
190 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000191 },
192 func(ctx android.SdkMemberContext, j *Library) android.Path {
193 // Java systemserver libs are only provided in the SDK to provide access to their dex
194 // implementation jar for use by dexpreopting. They do not need to provide an actual
195 // implementation jar but the java_import will need a file that exists so just copy an empty
196 // file. Any attempt to use that file as a jar will cause a build error.
197 return ctx.SnapshotBuilder().EmptyFile()
198 },
Paul Duffin13648912022-07-15 13:12:35 +0000199 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000200 // Create a special name for the implementation jar to try and provide some useful information
201 // to a developer that attempts to compile against this.
202 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
203 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
204 },
205 onlyCopyJarToSnapshot,
206 }
207
Paul Duffin2da04242021-04-23 19:43:28 +0100208 // Supports adding java test libraries to module_exports but not sdk.
209 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000210 SdkMemberTypeBase: android.SdkMemberTypeBase{
211 PropertyName: "java_tests",
212 },
Paul Duffin2da04242021-04-23 19:43:28 +0100213 }
214)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900215
Colin Crossdcf71b22021-02-01 13:59:03 -0800216// JavaInfo contains information about a java module for use by modules that depend on it.
217type JavaInfo struct {
218 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
219 // against this module. If empty, ImplementationJars should be used instead.
220 HeaderJars android.Paths
221
222 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
223 // in the module as well as any resources included in the module.
224 ImplementationAndResourcesJars android.Paths
225
226 // ImplementationJars is a list of jars that contain the implementations of classes in the
227 //module.
228 ImplementationJars android.Paths
229
230 // ResourceJars is a list of jars that contain the resources included in the module.
231 ResourceJars android.Paths
232
233 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
234 // depending on this module.
235 AidlIncludeDirs android.Paths
236
237 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
238 // module.
239 SrcJarArgs []string
240
241 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
242 SrcJarDeps android.Paths
243
244 // ExportedPlugins is a list of paths that should be used as annotation processors for any
245 // module that depends on this module.
246 ExportedPlugins android.Paths
247
248 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
249 // any module that depends on this module.
250 ExportedPluginClasses []string
251
252 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
253 // requiring disbling turbine for any modules that depend on it.
254 ExportedPluginDisableTurbine bool
255
256 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
257 // instrumented by jacoco.
258 JacocoReportClassesFile android.Path
259}
260
261var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
262
Colin Cross75ce9ec2021-02-26 16:20:32 -0800263// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
264// the sysprop implementation library.
265type SyspropPublicStubInfo struct {
266 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
267 // the sysprop implementation library.
268 JavaInfo JavaInfo
269}
270
271var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
272
Paul Duffin44b481b2020-06-17 16:59:43 +0100273// Methods that need to be implemented for a module that is added to apex java_libs property.
274type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700275 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100276 ImplementationAndResourcesJars() android.Paths
277}
278
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100279// Provides build path and install path to DEX jars.
280type UsesLibraryDependency interface {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100281 DexJarBuildPath() OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100282 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000283 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100284}
285
Jaewoong Jung26342642021-03-17 15:56:23 -0700286// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800287type xref interface {
288 XrefJavaFiles() android.Paths
289}
290
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800291func (j *Module) XrefJavaFiles() android.Paths {
292 return j.kytheFiles
293}
294
Colin Crossbe1da472017-07-07 15:59:46 -0700295type dependencyTag struct {
296 blueprint.BaseDependencyTag
297 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000298
299 // True if the dependency is relinked at runtime.
300 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800301
302 // True if the dependency is a toolchain, for example an annotation processor.
303 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700304}
305
Colin Crosse9fe2942020-11-10 18:12:15 -0800306// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
307// dependency to be installed when the parent module is installed.
308type installDependencyTag struct {
309 blueprint.BaseDependencyTag
310 android.InstallAlwaysNeededDependencyTag
311 name string
312}
313
Colin Cross65cb3142021-12-10 23:05:02 +0000314func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
315 if d.runtimeLinked {
316 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800317 } else if d.toolchain {
318 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000319 }
320 return nil
321}
322
323var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
324
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100325type usesLibraryDependencyTag struct {
326 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100327 sdkVersion int // SDK version in which the library appared as a standalone library.
328 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100329}
330
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100331func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100332 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000333 dependencyTag: dependencyTag{
334 name: fmt.Sprintf("uses-library-%d", sdkVersion),
335 runtimeLinked: true,
336 },
337 sdkVersion: sdkVersion,
338 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100339 }
340}
341
Jiyong Park8be103b2019-11-08 15:53:48 +0900342func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700343 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900344}
345
Colin Crossbe1da472017-07-07 15:59:46 -0700346var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800347 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000348 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800349 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000350 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400351 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000352 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800353 pluginTag = dependencyTag{name: "plugin", toolchain: true}
354 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
355 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000356 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
357 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800358 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000359 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
360 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800361 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800362 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
363 certificateTag = dependencyTag{name: "certificate"}
364 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800365 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000366 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800367 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
368 jniInstallTag = installDependencyTag{name: "jni install"}
369 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100370 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
371 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
372 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
373 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
374 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700375)
Colin Cross2fe66872015-03-30 17:20:39 -0700376
Jiyong Park83dc74b2020-01-14 18:38:44 +0900377func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400378 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900379}
380
381func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
382 return depTag == staticLibTag
383}
384
Colin Crossfc3674a2017-09-18 17:41:52 -0700385type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100386 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700387
Colin Cross6cef4812019-10-17 14:23:50 -0700388 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
389 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100390
391 // The default system modules to use. Will be an empty string if no system
392 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700393 systemModules string
394
Pete Gilline3d44b22020-06-29 11:28:51 +0100395 // The modules that will be added to the classpath regardless of the Java language level targeted
396 classpath []string
397
Colin Cross6cef4812019-10-17 14:23:50 -0700398 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100399 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700400 java9Classpath []string
401
Colin Crossa97c5d32018-03-28 14:58:31 -0700402 frameworkResModule string
403
Colin Cross86a60ae2018-05-29 14:44:55 -0700404 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700405 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100406
407 noStandardLibs, noFrameworksLibs bool
408}
409
410func (s sdkDep) hasStandardLibs() bool {
411 return !s.noStandardLibs
412}
413
414func (s sdkDep) hasFrameworkLibs() bool {
415 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700416}
417
Colin Crossa4f08812018-10-02 22:03:40 -0700418type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700419 name string
420 path android.Path
421 target android.Target
422 coverageFile android.OptionalPath
423 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000424 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700425}
426
Jiyong Parkf1691d22021-03-29 20:11:58 +0900427func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700428 sdkDep := decodeSdkDep(ctx, sdkContext)
429 if sdkDep.useModule {
430 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
431 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400432 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700433 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
434 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
435 }
436 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
437 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
438 }
439 }
440 if sdkDep.systemModules != "" {
441 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
442 }
443}
444
Colin Cross32f676a2017-09-06 13:41:06 -0700445type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700446 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
447 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
448 // systemModules and java9Classpath instead.
449 bootClasspath classpath
450
451 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
452 // contains header jars for all static and non-static dependencies.
453 classpath classpath
454
455 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
456 // header jars for all non-static dependencies. Static dependencies have already been
457 // combined into the program jar.
458 dexClasspath classpath
459
460 // java9Classpath is the list of jars that will be added to the classpath when targeting
461 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
462 // are provided by systemModules.
463 java9Classpath classpath
464
Colin Cross748b2d82020-11-19 13:52:06 -0800465 processorPath classpath
466 errorProneProcessorPath classpath
467 processorClasses []string
468 staticJars android.Paths
469 staticHeaderJars android.Paths
470 staticResourceJars android.Paths
471 aidlIncludeDirs android.Paths
472 srcs android.Paths
473 srcJars android.Paths
474 systemModules *systemModules
475 aidlPreprocess android.OptionalPath
476 kotlinStdlib android.Paths
477 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700478 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800479
480 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700481}
Colin Cross2fe66872015-03-30 17:20:39 -0700482
Colin Cross54250902017-12-05 09:28:08 -0800483func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
484 for _, f := range dep.Srcs() {
485 if f.Ext() != ".jar" {
486 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
487 ctx.OtherModuleName(dep.(blueprint.Module)))
488 }
489 }
490}
491
Jiyong Parkf1691d22021-03-29 20:11:58 +0900492func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700493 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700494 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700495 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900496 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Bascace720c32022-05-24 12:13:50 +0100497 } else if ctx.Config().TargetsJava17() {
498 // Temporary experimental flag to be able to try and build with
499 // java version 17 options. The flag, if used, just sets Java
500 // 17 as the default version, leaving any components that
501 // target an older version intact.
502 return JAVA_VERSION_17
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000503 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000504 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700505 }
Nan Zhang357466b2018-04-17 17:38:36 -0700506}
507
Colin Cross1e743852019-10-28 11:37:20 -0700508type javaVersion int
509
510const (
511 JAVA_VERSION_UNSUPPORTED = 0
512 JAVA_VERSION_6 = 6
513 JAVA_VERSION_7 = 7
514 JAVA_VERSION_8 = 8
515 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000516 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100517 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700518)
519
520func (v javaVersion) String() string {
521 switch v {
522 case JAVA_VERSION_6:
523 return "1.6"
524 case JAVA_VERSION_7:
525 return "1.7"
526 case JAVA_VERSION_8:
527 return "1.8"
528 case JAVA_VERSION_9:
529 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000530 case JAVA_VERSION_11:
531 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100532 case JAVA_VERSION_17:
533 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700534 default:
535 return "unsupported"
536 }
537}
538
Cole Faustd96eebf2022-06-28 14:41:27 -0700539func (v javaVersion) StringForKotlinc() string {
540 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
541 // error: unknown JVM target version: foo
542 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
543 switch v {
544 case JAVA_VERSION_7:
545 return "1.6"
546 case JAVA_VERSION_9:
547 return "9"
548 default:
549 return v.String()
550 }
551}
552
Colin Cross1e743852019-10-28 11:37:20 -0700553// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
554func (v javaVersion) usesJavaModules() bool {
555 return v >= 9
556}
557
558func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100559 switch javaVersion {
560 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700561 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100562 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700563 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100564 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700565 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100566 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700567 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000568 case "11":
569 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100570 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100571 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100572 case "10", "12", "13", "14", "15", "16":
573 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700574 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100575 default:
576 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700577 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100578 }
579}
580
Colin Cross2fe66872015-03-30 17:20:39 -0700581//
582// Java libraries (.jar file)
583//
584
Colin Crossf506d872017-07-19 15:53:04 -0700585type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700586 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700587
588 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700589}
590
Jiyong Park45bf82e2020-12-15 22:29:02 +0900591var _ android.ApexModule = (*Library)(nil)
592
satayevd604b212021-07-21 14:23:52 +0100593// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100594type PermittedPackagesForUpdatableBootJars interface {
595 PermittedPackagesForUpdatableBootJars() []string
596}
597
598var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
599
600func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
601 return j.properties.Permitted_packages
602}
603
Colin Cross42be7612019-02-21 18:12:14 -0800604func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000605 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700606 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000607 return true
608 }
609
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000610 // Store uncompressed (and do not strip) dex files from boot class path jars.
611 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
612 return true
613 }
614
615 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000616 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000617 return true
618 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800619 if ctx.Config().UncompressPrivAppDex() &&
620 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
621 return true
622 }
623
Colin Cross2fc72f62018-12-21 12:59:54 -0800624 return false
625}
626
Jiakai Zhang22450f22021-10-11 03:05:20 +0000627// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
628func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
629 if dexer.dexProperties.Uncompress_dex == nil {
630 // If the value was not force-set by the user, use reasonable default based on the module.
631 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
632 }
633}
634
Colin Crossf506d872017-07-19 15:53:04 -0700635func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000636
637 j.provideHiddenAPIPropertyInfo(ctx)
638
Jiyong Park92315372021-04-02 08:45:46 +0900639 j.sdkVersion = j.SdkVersion(ctx)
640 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000641 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900642
Colin Cross56a83212020-09-15 18:30:11 -0700643 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
644 if !apexInfo.IsForPlatform() {
645 j.hideApexVariantFromMake = true
646 }
647
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100648 j.checkSdkVersions(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800649 if ctx.Device() {
650 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
651 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
652 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
653 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
654 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
655 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
656 }
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700657 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700658
bralee1fbf4402020-05-21 10:11:59 +0800659 // Collect the module directory for IDE info in java/jdeps.go.
660 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
661
Colin Cross56a83212020-09-15 18:30:11 -0700662 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900663 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700664 var extraInstallDeps android.Paths
665 if j.InstallMixin != nil {
666 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
667 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700668 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
669 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800670 j.hostdexInstallFile = ctx.InstallFile(
671 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700672 j.Stem()+"-hostdex.jar", j.outputFile)
673 }
674 var installDir android.InstallPath
675 if ctx.InstallInTestcases() {
676 var archDir string
677 if !ctx.Host() {
678 archDir = ctx.DeviceConfig().DeviceArch()
679 }
680 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
681 } else {
682 installDir = android.PathForModuleInstall(ctx, "framework")
683 }
684 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700685 }
Colin Crossb7a63242015-04-16 14:09:14 -0700686}
687
Colin Crossf506d872017-07-19 15:53:04 -0700688func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700689 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100690 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700691}
692
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000693const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000694 aidlIncludeDir = "aidl"
695 javaDir = "java"
696 jarFileSuffix = ".jar"
697 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000698)
699
Paul Duffina0dbf432019-12-05 11:25:53 +0000700// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000701func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000702 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000703}
704
Paul Duffina04c1072020-03-02 10:16:35 +0000705func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
706 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000707}
708
Paul Duffin13879572019-11-28 14:31:38 +0000709type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000710 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000711
712 // Function to retrieve the appropriate output jar (implementation or header) from
713 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000714 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
715
716 // Function to compute the snapshot relative path to which the named library's
717 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000718 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000719
720 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
721 // files like aidl files should also be copied.
722 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000723}
724
Paul Duffindb170e42020-12-08 17:48:25 +0000725const (
726 onlyCopyJarToSnapshot = true
727 copyEverythingToSnapshot = false
728)
729
Paul Duffin296701e2021-07-14 10:29:36 +0100730func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
731 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000732}
733
734func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
735 _, ok := module.(*Library)
736 return ok
737}
738
Paul Duffin3a4eb502020-03-19 16:11:18 +0000739func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
740 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000741}
Paul Duffina0dbf432019-12-05 11:25:53 +0000742
Paul Duffin14eb4672020-03-02 11:33:02 +0000743func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000744 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000745}
746
747type librarySdkMemberProperties struct {
748 android.SdkMemberPropertiesBase
749
Paul Duffin864e1b42020-05-06 10:23:19 +0100750 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000751 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100752
753 // The list of permitted packages that need to be passed to the prebuilts as they are used to
754 // create the updatable-bcp-packages.txt file.
755 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000756}
757
Paul Duffin3a4eb502020-03-19 16:11:18 +0000758func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000759 j := variant.(*Library)
760
Paul Duffindb170e42020-12-08 17:48:25 +0000761 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
762
Paul Duffina551a1c2020-03-17 21:04:24 +0000763 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100764
765 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000766}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000767
Paul Duffin3a4eb502020-03-19 16:11:18 +0000768func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000769 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000770
Paul Duffindb170e42020-12-08 17:48:25 +0000771 memberType := ctx.MemberType().(*librarySdkMemberType)
772
Paul Duffina551a1c2020-03-17 21:04:24 +0000773 exportedJar := p.JarToExport
774 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000775 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000776 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000777
778 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000779 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
780
Paul Duffina551a1c2020-03-17 21:04:24 +0000781 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
782 }
783
Paul Duffin869de142021-07-15 14:14:41 +0100784 if len(p.PermittedPackages) > 0 {
785 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
786 }
787
Paul Duffindb170e42020-12-08 17:48:25 +0000788 // Do not copy anything else to the snapshot.
789 if memberType.onlyCopyJarToSnapshot {
790 return
791 }
792
Paul Duffina551a1c2020-03-17 21:04:24 +0000793 aidlIncludeDirs := p.AidlIncludeDirs
794 if len(aidlIncludeDirs) != 0 {
795 sdkModuleContext := ctx.SdkModuleContext()
796 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000797 // TODO(jiyong): copy parcelable declarations only
798 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
799 for _, file := range aidlFiles {
800 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
801 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000802 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000803
Paul Duffina551a1c2020-03-17 21:04:24 +0000804 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000805 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000806}
807
Colin Cross1b16b0e2019-02-12 14:41:32 -0800808// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
809//
810// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
811// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
812// as a `static_libs` dependency of another module.
813//
814// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
815// a device.
816//
817// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
818// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700819func LibraryFactory() android.Module {
820 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700821
Colin Crossce6734e2020-06-15 16:09:53 -0700822 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700823
Paul Duffin71b33cc2021-06-23 11:39:47 +0100824 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100825
Jiyong Park7f7766d2019-07-25 22:02:35 +0900826 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900827 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800828 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900829 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700830 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700831}
832
Colin Cross1b16b0e2019-02-12 14:41:32 -0800833// java_library_static is an obsolete alias for java_library.
834func LibraryStaticFactory() android.Module {
835 return LibraryFactory()
836}
837
838// java_library_host builds and links sources into a `.jar` file for the host.
839//
840// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
841// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700842func LibraryHostFactory() android.Module {
843 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700844
Colin Crossce6734e2020-06-15 16:09:53 -0700845 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700846
Colin Cross9ae1b922018-06-26 17:59:05 -0700847 module.Module.properties.Installable = proptools.BoolPtr(true)
848
Jiyong Park7f7766d2019-07-25 22:02:35 +0900849 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100850 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800851 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900852 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700853 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700854}
855
856//
Colin Crossb628ea52018-08-14 16:42:33 -0700857// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700858//
859
Dan Shi95d19422020-08-15 12:24:26 -0700860// Test option struct.
861type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800862 android.CommonTestOptions
863
Dan Shi95d19422020-08-15 12:24:26 -0700864 // a list of extra test configuration files that should be installed with the module.
865 Extra_test_configs []string `android:"path,arch_variant"`
866}
867
Colin Cross05638fc2018-04-09 18:40:24 -0700868type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700869 // list of compatibility suites (for example "cts", "vts") that the module should be
870 // installed into.
871 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700872
873 // the name of the test configuration (for example "AndroidTest.xml") that should be
874 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800875 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700876
Jack He33338892018-09-19 02:21:28 -0700877 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
878 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800879 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700880
Colin Crossd96ca352018-08-10 16:06:24 -0700881 // list of files or filegroup modules that provide data that should be installed alongside
882 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900883 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700884
885 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
886 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
887 // explicitly.
888 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800889
890 // Add parameterized mainline modules to auto generated test config. The options will be
891 // handled by TradeFed to do downloading and installing the specified modules on the device.
892 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700893
894 // Test options.
895 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800896
897 // Names of modules containing JNI libraries that should be installed alongside the test.
898 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700899
900 // Install the test into a folder named for the module in all test suites.
901 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700902}
903
Liz Kammerdd849a82020-06-12 16:38:45 -0700904type hostTestProperties struct {
905 // list of native binary modules that should be installed alongside the test
906 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000907
908 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000909 // This property only adds the first variant of the dependency
910 Data_device_bins_first []string `android:"arch_variant"`
911
912 // list of device binary modules that should be installed alongside the test
913 // This property adds 64bit AND 32bit variants of the dependency
914 Data_device_bins_both []string `android:"arch_variant"`
915
916 // list of device binary modules that should be installed alongside the test
917 // This property only adds 64bit variants of the dependency
918 Data_device_bins_64 []string `android:"arch_variant"`
919
920 // list of device binary modules that should be installed alongside the test
921 // This property adds 32bit variants of the dependency if available, or else
922 // defaults to the 64bit variant
923 Data_device_bins_prefer32 []string `android:"arch_variant"`
924
925 // list of device binary modules that should be installed alongside the test
926 // This property only adds 32bit variants of the dependency
927 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700928}
929
Paul Duffin42df1442019-03-20 12:45:53 +0000930type testHelperLibraryProperties struct {
931 // list of compatibility suites (for example "cts", "vts") that the module should be
932 // installed into.
933 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700934
935 // Install the test into a folder named for the module in all test suites.
936 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000937}
938
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000939type prebuiltTestProperties struct {
940 // list of compatibility suites (for example "cts", "vts") that the module should be
941 // installed into.
942 Test_suites []string `android:"arch_variant"`
943
944 // the name of the test configuration (for example "AndroidTest.xml") that should be
945 // installed with the module.
946 Test_config *string `android:"path,arch_variant"`
947}
948
Colin Cross05638fc2018-04-09 18:40:24 -0700949type Test struct {
950 Library
951
952 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700953
Dan Shi95d19422020-08-15 12:24:26 -0700954 testConfig android.Path
955 extraTestConfigs android.Paths
956 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700957}
958
Liz Kammerdd849a82020-06-12 16:38:45 -0700959type TestHost struct {
960 Test
961
962 testHostProperties hostTestProperties
963}
964
Paul Duffin42df1442019-03-20 12:45:53 +0000965type TestHelperLibrary struct {
966 Library
967
968 testHelperLibraryProperties testHelperLibraryProperties
969}
970
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000971type JavaTestImport struct {
972 Import
973
974 prebuiltTestProperties prebuiltTestProperties
975
976 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700977 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000978}
979
Colin Cross24cc4be62021-11-03 14:09:41 -0700980func (j *Test) InstallInTestcases() bool {
981 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
982 // testcases by base_rules.mk.
983 return !j.Host()
984}
985
986func (j *TestHelperLibrary) InstallInTestcases() bool {
987 return true
988}
989
990func (j *JavaTestImport) InstallInTestcases() bool {
991 return true
992}
993
Sam Delmericocc271e22022-06-01 15:45:02 +0000994func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
995 if len(j.testHostProperties.Data_device_bins_first) > 0 {
996 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
997 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
998 }
999
1000 var maybeAndroid32Target *android.Target
1001 var maybeAndroid64Target *android.Target
1002 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1003 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1004 if len(android32TargetList) > 0 {
1005 maybeAndroid32Target = &android32TargetList[0]
1006 }
1007 if len(android64TargetList) > 0 {
1008 maybeAndroid64Target = &android64TargetList[0]
1009 }
1010
1011 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1012 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1013 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1014 return
1015 }
1016 if maybeAndroid32Target != nil {
1017 ctx.AddFarVariationDependencies(
1018 maybeAndroid32Target.Variations(),
1019 dataDeviceBinsTag,
1020 j.testHostProperties.Data_device_bins_both...,
1021 )
1022 }
1023 if maybeAndroid64Target != nil {
1024 ctx.AddFarVariationDependencies(
1025 maybeAndroid64Target.Variations(),
1026 dataDeviceBinsTag,
1027 j.testHostProperties.Data_device_bins_both...,
1028 )
1029 }
1030 }
1031
1032 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1033 if maybeAndroid32Target != nil {
1034 ctx.AddFarVariationDependencies(
1035 maybeAndroid32Target.Variations(),
1036 dataDeviceBinsTag,
1037 j.testHostProperties.Data_device_bins_prefer32...,
1038 )
1039 } else {
1040 if maybeAndroid64Target == nil {
1041 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1042 return
1043 }
1044 ctx.AddFarVariationDependencies(
1045 maybeAndroid64Target.Variations(),
1046 dataDeviceBinsTag,
1047 j.testHostProperties.Data_device_bins_prefer32...,
1048 )
1049 }
1050 }
1051
1052 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1053 if maybeAndroid32Target == nil {
1054 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1055 return
1056 }
1057 deviceVariations := maybeAndroid32Target.Variations()
1058 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1059 }
1060
1061 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1062 if maybeAndroid64Target == nil {
1063 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1064 return
1065 }
1066 deviceVariations := maybeAndroid64Target.Variations()
1067 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1068 }
1069}
1070
Liz Kammerdd849a82020-06-12 16:38:45 -07001071func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1072 if len(j.testHostProperties.Data_native_bins) > 0 {
1073 for _, target := range ctx.MultiTargets() {
1074 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1075 }
1076 }
1077
Colin Crossf8d9c492021-01-26 11:01:43 -08001078 if len(j.testProperties.Jni_libs) > 0 {
1079 for _, target := range ctx.MultiTargets() {
1080 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1081 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1082 }
1083 }
1084
Sam Delmericocc271e22022-06-01 15:45:02 +00001085 j.addDataDeviceBinsDeps(ctx)
1086
Liz Kammerdd849a82020-06-12 16:38:45 -07001087 j.deps(ctx)
1088}
1089
Yuexi Ma627263f2021-03-04 13:47:56 -08001090func (j *TestHost) AddExtraResource(p android.Path) {
1091 j.extraResources = append(j.extraResources, p)
1092}
1093
Sam Delmericocc271e22022-06-01 15:45:02 +00001094func (j *TestHost) dataDeviceBins() []string {
1095 ret := make([]string, 0,
1096 len(j.testHostProperties.Data_device_bins_first)+
1097 len(j.testHostProperties.Data_device_bins_both)+
1098 len(j.testHostProperties.Data_device_bins_prefer32)+
1099 len(j.testHostProperties.Data_device_bins_32)+
1100 len(j.testHostProperties.Data_device_bins_64),
1101 )
1102
1103 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1104 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1105 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1106 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1107 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1108
1109 return ret
1110}
1111
Sam Delmericob3342ce2022-01-20 21:10:28 +00001112func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1113 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001114 dataDeviceBins := j.dataDeviceBins()
1115 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001116 // add Tradefed configuration to push device bins to device for testing
1117 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1118 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001119 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001120 fullPath := filepath.Join(remoteDir, bin)
1121 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1122 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001123 configs = append(configs, tradefed.Object{
1124 Type: "target_preparer",
1125 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1126 Options: options,
1127 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001128 }
1129
1130 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
1131}
1132
Colin Cross303e21f2018-08-07 16:49:25 -07001133func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001134 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1135}
1136
1137func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001138 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1139 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001140 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001141 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1142 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001143
Dan Shi6ffaaa82019-09-26 11:41:36 -07001144 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001145 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -07001146
Colin Cross8a497952019-03-05 22:25:09 -08001147 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001148
Dan Shi95d19422020-08-15 12:24:26 -07001149 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1150
Liz Kammerdd849a82020-06-12 16:38:45 -07001151 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1152 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1153 })
1154
Sam Delmericob3342ce2022-01-20 21:10:28 +00001155 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1156 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1157 })
1158
Colin Crossf8d9c492021-01-26 11:01:43 -08001159 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1160 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1161 if sharedLibInfo.SharedLibrary != nil {
1162 // Copy to an intermediate output directory to append "lib[64]" to the path,
1163 // so that it's compatible with the default rpath values.
1164 var relPath string
1165 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1166 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1167 } else {
1168 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1169 }
1170 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1171 ctx.Build(pctx, android.BuildParams{
1172 Rule: android.Cp,
1173 Input: sharedLibInfo.SharedLibrary,
1174 Output: relocatedLib,
1175 })
1176 j.data = append(j.data, relocatedLib)
1177 } else {
1178 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1179 }
1180 })
1181
Colin Cross303e21f2018-08-07 16:49:25 -07001182 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001183}
1184
Paul Duffin42df1442019-03-20 12:45:53 +00001185func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1186 j.Library.GenerateAndroidBuildActions(ctx)
1187}
1188
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001189func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1190 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001191 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001192
1193 j.Import.GenerateAndroidBuildActions(ctx)
1194}
1195
1196type testSdkMemberType struct {
1197 android.SdkMemberTypeBase
1198}
1199
Paul Duffin296701e2021-07-14 10:29:36 +01001200func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1201 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001202}
1203
1204func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1205 _, ok := module.(*Test)
1206 return ok
1207}
1208
Paul Duffin3a4eb502020-03-19 16:11:18 +00001209func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1210 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001211}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001212
Paul Duffin14eb4672020-03-02 11:33:02 +00001213func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1214 return &testSdkMemberProperties{}
1215}
1216
1217type testSdkMemberProperties struct {
1218 android.SdkMemberPropertiesBase
1219
Paul Duffina551a1c2020-03-17 21:04:24 +00001220 JarToExport android.Path
1221 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001222}
1223
Paul Duffin3a4eb502020-03-19 16:11:18 +00001224func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001225 test := variant.(*Test)
1226
1227 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001228 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001229 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001230 }
1231
Paul Duffina551a1c2020-03-17 21:04:24 +00001232 p.JarToExport = implementationJars[0]
1233 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001234}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001235
Paul Duffin3a4eb502020-03-19 16:11:18 +00001236func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001237 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001238
Paul Duffina551a1c2020-03-17 21:04:24 +00001239 exportedJar := p.JarToExport
1240 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001241 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001242 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001243
1244 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001245 }
1246
1247 testConfig := p.TestConfig
1248 if testConfig != nil {
1249 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1250 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001251 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1252 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001253}
1254
Colin Cross1b16b0e2019-02-12 14:41:32 -08001255// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1256// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1257//
1258// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1259// compiled against the device bootclasspath.
1260//
1261// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1262// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001263func TestFactory() android.Module {
1264 module := &Test{}
1265
Colin Crossce6734e2020-06-15 16:09:53 -07001266 module.addHostAndDeviceProperties()
1267 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001268
Colin Cross9ae1b922018-06-26 17:59:05 -07001269 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001270 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001271 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001272
Paul Duffinb6b89a42021-05-06 16:33:43 +01001273 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001274 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001275 return module
1276}
1277
Paul Duffin42df1442019-03-20 12:45:53 +00001278// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1279func TestHelperLibraryFactory() android.Module {
1280 module := &TestHelperLibrary{}
1281
Colin Crossce6734e2020-06-15 16:09:53 -07001282 module.addHostAndDeviceProperties()
1283 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001284
Colin Cross9a4abed2019-04-24 13:19:28 -07001285 module.Module.properties.Installable = proptools.BoolPtr(true)
1286 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001287 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001288
Paul Duffin42df1442019-03-20 12:45:53 +00001289 InitJavaModule(module, android.HostAndDeviceSupported)
1290 return module
1291}
1292
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001293// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1294// and makes sure that it is added to the appropriate test suite.
1295//
1296// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1297// compiled against an Android classpath.
1298//
1299// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1300// for host modules.
1301func JavaTestImportFactory() android.Module {
1302 module := &JavaTestImport{}
1303
1304 module.AddProperties(
1305 &module.Import.properties,
1306 &module.prebuiltTestProperties)
1307
1308 module.Import.properties.Installable = proptools.BoolPtr(true)
1309
1310 android.InitPrebuiltModule(module, &module.properties.Jars)
1311 android.InitApexModule(module)
1312 android.InitSdkAwareModule(module)
1313 InitJavaModule(module, android.HostAndDeviceSupported)
1314 return module
1315}
1316
Colin Cross1b16b0e2019-02-12 14:41:32 -08001317// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1318// allow running the test with `atest` or a `TEST_MAPPING` file.
1319//
1320// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1321// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001322func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001323 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001324
Colin Crossce6734e2020-06-15 16:09:53 -07001325 module.addHostProperties()
1326 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001327 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001328
Yuexi Ma627263f2021-03-04 13:47:56 -08001329 InitTestHost(
1330 module,
1331 proptools.BoolPtr(true),
1332 nil,
1333 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001334
Liz Kammerdd849a82020-06-12 16:38:45 -07001335 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001336
Colin Cross05638fc2018-04-09 18:40:24 -07001337 return module
1338}
1339
Yuexi Ma627263f2021-03-04 13:47:56 -08001340func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1341 th.properties.Installable = installable
1342 th.testProperties.Auto_gen_config = autoGenConfig
1343 th.testProperties.Test_suites = testSuites
1344}
1345
Colin Cross05638fc2018-04-09 18:40:24 -07001346//
Colin Cross2fe66872015-03-30 17:20:39 -07001347// Java Binaries (.jar file plus wrapper script)
1348//
1349
Colin Crossf506d872017-07-19 15:53:04 -07001350type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001351 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001352 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001353
1354 // Name of the class containing main to be inserted into the manifest as Main-Class.
1355 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001356
1357 // Names of modules containing JNI libraries that should be installed alongside the host
1358 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001359 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001360}
1361
Colin Crossf506d872017-07-19 15:53:04 -07001362type Binary struct {
1363 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001364
Colin Crossf506d872017-07-19 15:53:04 -07001365 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001366
Colin Cross6b4a32d2017-12-05 13:42:45 -08001367 isWrapperVariant bool
1368
Colin Crossc3315992017-12-08 19:12:36 -08001369 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001370 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001371}
1372
Alex Light24237172017-10-26 09:46:21 -07001373func (j *Binary) HostToolPath() android.OptionalPath {
1374 return android.OptionalPathForPath(j.binaryFile)
1375}
1376
Colin Crossf506d872017-07-19 15:53:04 -07001377func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001378 if ctx.Arch().ArchType == android.Common {
1379 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001380 if j.binaryProperties.Main_class != nil {
1381 if j.properties.Manifest != nil {
1382 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1383 }
1384 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1385 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1386 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1387 }
1388
Colin Cross6b4a32d2017-12-05 13:42:45 -08001389 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001390 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001391 // Handle the binary wrapper
1392 j.isWrapperVariant = true
1393
Colin Cross366938f2017-12-11 16:29:02 -08001394 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001395 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001396 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001397 if ctx.Windows() {
1398 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1399 }
1400
Colin Cross6b4a32d2017-12-05 13:42:45 -08001401 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1402 }
1403
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001404 ext := ""
1405 if ctx.Windows() {
1406 ext = ".bat"
1407 }
1408
Colin Crossc179ea62020-10-09 10:54:15 -07001409 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001410 // of the wrapper variant, which will include the common variant's jar file and any JNI
1411 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001412 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001413 ctx.ModuleName()+ext, j.wrapperFile)
1414 }
Colin Cross2fe66872015-03-30 17:20:39 -07001415}
1416
Colin Crossf506d872017-07-19 15:53:04 -07001417func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001418 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001419 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001420 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001421 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001422 // These dependencies ensure the host installation rules will install the jar file and
1423 // the jni libraries when the wrapper is installed.
1424 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1425 ctx.AddVariationDependencies(
1426 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1427 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001428 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001429}
1430
Colin Cross1b16b0e2019-02-12 14:41:32 -08001431// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1432// as well.
1433//
1434// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1435// compiled against the device bootclasspath.
1436//
1437// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1438// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001439func BinaryFactory() android.Module {
1440 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001441
Colin Crossce6734e2020-06-15 16:09:53 -07001442 module.addHostAndDeviceProperties()
1443 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001444
Colin Cross9ae1b922018-06-26 17:59:05 -07001445 module.Module.properties.Installable = proptools.BoolPtr(true)
1446
Colin Cross6b4a32d2017-12-05 13:42:45 -08001447 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1448 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001449 android.InitBazelModule(module)
1450
Colin Cross36242852017-06-23 15:06:31 -07001451 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001452}
1453
Colin Cross1b16b0e2019-02-12 14:41:32 -08001454// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1455//
1456// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1457// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001458func BinaryHostFactory() android.Module {
1459 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001460
Colin Crossce6734e2020-06-15 16:09:53 -07001461 module.addHostProperties()
1462 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001463
Colin Cross9ae1b922018-06-26 17:59:05 -07001464 module.Module.properties.Installable = proptools.BoolPtr(true)
1465
Colin Cross6b4a32d2017-12-05 13:42:45 -08001466 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1467 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001468 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001469 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001470}
1471
1472//
1473// Java prebuilts
1474//
1475
Colin Cross74d73e22017-08-02 11:05:49 -07001476type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001477 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001478
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001479 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1480 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001481 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001482
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001483 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1484 // specified.
1485 Min_sdk_version *string
1486
William Loh5a082f92022-05-17 20:21:50 +00001487 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
1488 // and uses-permission tags in manifest_fixer.
1489 Replace_max_sdk_version_placeholder *string
1490
Colin Cross535e2cf2017-10-20 17:57:49 -07001491 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001492
Paul Duffin869de142021-07-15 14:14:41 +01001493 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001494 Permitted_packages []string
1495
Jiyong Park1be96912018-05-28 18:02:19 +09001496 // List of shared java libs that this module has dependencies to
1497 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001498
1499 // List of files to remove from the jar file(s)
1500 Exclude_files []string
1501
1502 // List of directories to remove from the jar file(s)
1503 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001504
1505 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001506 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001507
1508 // set the name of the output
1509 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001510
1511 Aidl struct {
1512 // directories that should be added as include directories for any aidl sources of modules
1513 // that depend on this module, as well as to aidl for this module.
1514 Export_include_dirs []string
1515 }
Colin Cross74d73e22017-08-02 11:05:49 -07001516}
1517
1518type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001519 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001520 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001521 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001522 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001523 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001524 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001525
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001526 // Functionality common to Module and Import.
1527 embeddableInModuleAndImport
1528
Liz Kammerd6c31d22020-08-05 15:40:41 -07001529 hiddenAPI
1530 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001531 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001532
Colin Cross74d73e22017-08-02 11:05:49 -07001533 properties ImportProperties
1534
Liz Kammerd6c31d22020-08-05 15:40:41 -07001535 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001536 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001537 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001538
Colin Cross0a6e0072017-08-30 14:24:55 -07001539 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001540 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001541 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001542
1543 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001544
1545 sdkVersion android.SdkSpec
1546 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001547}
1548
Paul Duffin630b11e2021-07-15 13:35:26 +01001549var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1550
1551func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1552 return j.properties.Permitted_packages
1553}
1554
Jiyong Park92315372021-04-02 08:45:46 +09001555func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1556 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001557}
1558
Jiyong Parkf1691d22021-03-29 20:11:58 +09001559func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001560 return "none"
1561}
1562
Jiyong Park92315372021-04-02 08:45:46 +09001563func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001564 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001565 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001566 }
Jiyong Park92315372021-04-02 08:45:46 +09001567 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001568}
1569
William Loh5a082f92022-05-17 20:21:50 +00001570func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
1571 if j.properties.Replace_max_sdk_version_placeholder != nil {
1572 return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
1573 }
1574 return android.SdkSpecFrom(ctx, "")
1575}
1576
Jiyong Park92315372021-04-02 08:45:46 +09001577func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1578 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001579}
1580
Colin Cross74d73e22017-08-02 11:05:49 -07001581func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001582 return &j.prebuilt
1583}
1584
Colin Cross74d73e22017-08-02 11:05:49 -07001585func (j *Import) PrebuiltSrcs() []string {
1586 return j.properties.Jars
1587}
1588
1589func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001590 return j.prebuilt.Name(j.ModuleBase.Name())
1591}
1592
Jiyong Park0b238752019-10-29 11:23:10 +09001593func (j *Import) Stem() string {
1594 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1595}
1596
Jiyong Park618922e2020-01-08 13:35:43 +09001597func (a *Import) JacocoReportClassesFile() android.Path {
1598 return nil
1599}
1600
Bill Peckhama41a6962021-01-11 10:58:54 -08001601func (j *Import) LintDepSets() LintDepSets {
1602 return LintDepSets{}
1603}
1604
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001605func (j *Import) getStrictUpdatabilityLinting() bool {
1606 return false
1607}
1608
1609func (j *Import) setStrictUpdatabilityLinting(bool) {
1610}
1611
Colin Cross74d73e22017-08-02 11:05:49 -07001612func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001613 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001614
1615 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001616 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001617 }
Colin Cross1e676be2016-10-12 14:38:15 -07001618}
1619
Sam Delmerico277795c2022-02-25 17:04:37 +00001620func (j *Import) commonBuildActions(ctx android.ModuleContext) {
1621 //TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09001622 j.sdkVersion = j.SdkVersion(ctx)
1623 j.minSdkVersion = j.MinSdkVersion(ctx)
1624
Colin Cross56a83212020-09-15 18:30:11 -07001625 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1626 j.hideApexVariantFromMake = true
1627 }
1628
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001629 if ctx.Windows() {
1630 j.HideFromMake()
1631 }
Sam Delmerico277795c2022-02-25 17:04:37 +00001632}
1633
1634func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1635 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001636
Colin Cross8a497952019-03-05 22:25:09 -08001637 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001638
Jiyong Park0b238752019-10-29 11:23:10 +09001639 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001640 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001641 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1642 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001643 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001644 inputFile := outputFile
1645 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1646 TransformJetifier(ctx, outputFile, inputFile)
1647 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001648 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001649 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001650
Liz Kammerd6c31d22020-08-05 15:40:41 -07001651 var flags javaBuilderFlags
1652
Jiyong Park1be96912018-05-28 18:02:19 +09001653 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001654 tag := ctx.OtherModuleDependencyTag(module)
1655
Colin Crossdcf71b22021-02-01 13:59:03 -08001656 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1657 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001658 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001659 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001660 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1661 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1662 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001663 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001664 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001665 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001666 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001667 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001668 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001669 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09001670 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001671 }
1672 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001673
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001674 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001675 })
1676
Sam Delmerico277795c2022-02-25 17:04:37 +00001677 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09001678
1679 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001680
Paul Duffin064b70c2020-11-02 17:32:38 +00001681 if ctx.Device() {
1682 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1683 // obtained from the associated deapexer module.
1684 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1685 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001686 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001687 di := android.FindDeapexerProviderForModule(ctx)
1688 if di == nil {
1689 return // An error has been reported by FindDeapexerProviderForModule.
1690 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001691 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001692 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1693 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001694 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1695 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001696
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001697 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001698 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001699 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1700 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001701
1702 // Initialize the hiddenapi structure.
1703 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001704 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001705 // This should never happen as a variant for a prebuilt_apex is only created if the
1706 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001707 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001708 }
1709 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001710 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001711 if sdkDep.invalidVersion {
1712 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1713 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1714 } else if sdkDep.useFiles {
1715 // sdkDep.jar is actually equivalent to turbine header.jar.
1716 flags.classpath = append(flags.classpath, sdkDep.jars...)
1717 }
1718
1719 // Dex compilation
1720
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001721 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1722 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001723 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001724 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1725
Paul Duffin612e6102021-02-02 13:38:13 +00001726 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001727 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001728 if ctx.Failed() {
1729 return
1730 }
1731
Paul Duffin74d18d12021-05-14 14:18:47 +01001732 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001733 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001734
1735 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001736 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001737
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001738 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001739 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001740 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001741 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001742
1743 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1744 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1745 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1746 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1747 AidlIncludeDirs: j.exportAidlIncludeDirs,
1748 })
Colin Cross2fe66872015-03-30 17:20:39 -07001749}
1750
Sam Delmerico277795c2022-02-25 17:04:37 +00001751func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
1752 if !Bool(j.properties.Installable) {
1753 return
1754 }
1755
1756 var installDir android.InstallPath
1757 if ctx.InstallInTestcases() {
1758 var archDir string
1759 if !ctx.Host() {
1760 archDir = ctx.DeviceConfig().DeviceArch()
1761 }
1762 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1763 } else {
1764 installDir = android.PathForModuleInstall(ctx, "framework")
1765 }
1766 ctx.InstallFile(installDir, jarName, outputFile)
1767}
1768
Paul Duffinaa55f742020-10-06 17:20:13 +01001769func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1770 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001771 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001772 return android.Paths{j.combinedClasspathFile}, nil
1773 default:
1774 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1775 }
1776}
1777
1778var _ android.OutputFileProducer = (*Import)(nil)
1779
Nan Zhanged19fc32017-10-19 13:06:22 -07001780func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001781 if j.combinedClasspathFile == nil {
1782 return nil
1783 }
Colin Cross37f6d792018-07-12 12:28:41 -07001784 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001785}
1786
Colin Cross331a1212018-08-15 20:40:52 -07001787func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001788 if j.combinedClasspathFile == nil {
1789 return nil
1790 }
Colin Cross331a1212018-08-15 20:40:52 -07001791 return android.Paths{j.combinedClasspathFile}
1792}
1793
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001794func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001795 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001796}
1797
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001798func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001799 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001800}
1801
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001802func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1803 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001804}
1805
Jiyong Park45bf82e2020-12-15 22:29:02 +09001806var _ android.ApexModule = (*Import)(nil)
1807
1808// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001809func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001810 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001811}
1812
Jiyong Park45bf82e2020-12-15 22:29:02 +09001813// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001814func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1815 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001816 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001817 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001818 return fmt.Errorf("min_sdk_version is not specified")
1819 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001820 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001821 return nil
1822 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001823 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1824 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001825 }
Jooyung Han749dc692020-04-15 11:03:39 +09001826 return nil
1827}
1828
Paul Duffinfef55002021-06-17 14:56:05 +01001829// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1830// java_sdk_library_import with the specified base module name requires to be exported from a
1831// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001832func requiredFilesFromPrebuiltApexForImport(name string) []string {
1833 // Add the dex implementation jar to the set of exported files.
1834 return []string{
1835 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001836 }
1837}
1838
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001839// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1840// the java library with the specified name.
1841func apexRootRelativePathToJavaLib(name string) string {
1842 return filepath.Join("javalib", name+".jar")
1843}
1844
Paul Duffinfef55002021-06-17 14:56:05 +01001845var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1846
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001847func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001848 name := j.BaseModuleName()
1849 return requiredFilesFromPrebuiltApexForImport(name)
1850}
1851
albaltai36ff7dc2018-12-25 14:35:23 +08001852// Add compile time check for interface implementation
1853var _ android.IDEInfo = (*Import)(nil)
1854var _ android.IDECustomizedModuleName = (*Import)(nil)
1855
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001856// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001857
1858func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1859 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1860}
1861
1862func (j *Import) IDECustomizedModuleName() string {
1863 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1864 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1865 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001866 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001867}
1868
Colin Cross74d73e22017-08-02 11:05:49 -07001869var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001870
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001871func (j *Import) IsInstallable() bool {
1872 return Bool(j.properties.Installable)
1873}
1874
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001875var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001876
Colin Cross1b16b0e2019-02-12 14:41:32 -08001877// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1878//
1879// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1880// compiled against an Android classpath.
1881//
1882// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1883// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001884func ImportFactory() android.Module {
1885 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001886
Liz Kammerd6c31d22020-08-05 15:40:41 -07001887 module.AddProperties(
1888 &module.properties,
1889 &module.dexer.dexProperties,
1890 )
Colin Cross74d73e22017-08-02 11:05:49 -07001891
Paul Duffin71b33cc2021-06-23 11:39:47 +01001892 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001893
Liz Kammerd6c31d22020-08-05 15:40:41 -07001894 module.dexProperties.Optimize.EnabledByDefault = false
1895
Colin Cross74d73e22017-08-02 11:05:49 -07001896 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001897 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001898 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001899 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001900 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001901 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001902}
1903
Colin Cross1b16b0e2019-02-12 14:41:32 -08001904// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1905// module.
1906//
1907// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1908// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001909func ImportFactoryHost() android.Module {
1910 module := &Import{}
1911
1912 module.AddProperties(&module.properties)
1913
1914 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001915 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001916 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001917 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001918 return module
1919}
1920
Colin Cross42be7612019-02-21 18:12:14 -08001921// dex_import module
1922
1923type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001924 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001925
1926 // set the name of the output
1927 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001928}
1929
1930type DexImport struct {
1931 android.ModuleBase
1932 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001933 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001934 prebuilt android.Prebuilt
1935
1936 properties DexImportProperties
1937
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001938 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001939
1940 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001941
1942 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001943}
1944
1945func (j *DexImport) Prebuilt() *android.Prebuilt {
1946 return &j.prebuilt
1947}
1948
1949func (j *DexImport) PrebuiltSrcs() []string {
1950 return j.properties.Jars
1951}
1952
1953func (j *DexImport) Name() string {
1954 return j.prebuilt.Name(j.ModuleBase.Name())
1955}
1956
Jiyong Park0b238752019-10-29 11:23:10 +09001957func (j *DexImport) Stem() string {
1958 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1959}
1960
Jiyong Park77acec62020-06-01 21:39:15 +09001961func (a *DexImport) JacocoReportClassesFile() android.Path {
1962 return nil
1963}
1964
Colin Cross08dca382020-07-21 20:31:17 -07001965func (a *DexImport) LintDepSets() LintDepSets {
1966 return LintDepSets{}
1967}
1968
Martin Stjernholm6d415272020-01-31 17:10:36 +00001969func (j *DexImport) IsInstallable() bool {
1970 return true
1971}
1972
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001973func (j *DexImport) getStrictUpdatabilityLinting() bool {
1974 return false
1975}
1976
1977func (j *DexImport) setStrictUpdatabilityLinting(bool) {
1978}
1979
Colin Cross42be7612019-02-21 18:12:14 -08001980func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1981 if len(j.properties.Jars) != 1 {
1982 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
1983 }
1984
Colin Cross56a83212020-09-15 18:30:11 -07001985 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1986 if !apexInfo.IsForPlatform() {
1987 j.hideApexVariantFromMake = true
1988 }
1989
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001990 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1991 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08001992 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
1993
1994 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
1995 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
1996
1997 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08001998 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08001999
2000 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2001 rule.Temporary(temporary)
2002
2003 // use zip2zip to uncompress classes*.dex files
2004 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002005 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002006 FlagWithInput("-i ", inputJar).
2007 FlagWithOutput("-o ", temporary).
2008 FlagWithArg("-0 ", "'classes*.dex'")
2009
2010 // use zipalign to align uncompressed classes*.dex files
2011 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002012 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002013 Flag("-f").
2014 Text("4").
2015 Input(temporary).
2016 Output(dexOutputFile)
2017
2018 rule.DeleteTemporaryFiles()
2019
Colin Crossf1a035e2020-11-16 17:32:30 -08002020 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002021 } else {
2022 ctx.Build(pctx, android.BuildParams{
2023 Rule: android.Cp,
2024 Input: inputJar,
2025 Output: dexOutputFile,
2026 })
2027 }
2028
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002029 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002030
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002031 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002032
Colin Cross56a83212020-09-15 18:30:11 -07002033 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002034 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2035 j.Stem()+".jar", dexOutputFile)
2036 }
Colin Cross42be7612019-02-21 18:12:14 -08002037}
2038
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002039func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002040 return j.dexJarFile
2041}
2042
Jiyong Park45bf82e2020-12-15 22:29:02 +09002043var _ android.ApexModule = (*DexImport)(nil)
2044
2045// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002046func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2047 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002048 // we don't check prebuilt modules for sdk_version
2049 return nil
2050}
2051
Colin Cross42be7612019-02-21 18:12:14 -08002052// dex_import imports a `.jar` file containing classes.dex files.
2053//
2054// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2055// to the device.
2056func DexImportFactory() android.Module {
2057 module := &DexImport{}
2058
2059 module.AddProperties(&module.properties)
2060
2061 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002062 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002063 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002064 return module
2065}
2066
Colin Cross89536d42017-07-07 14:35:50 -07002067// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002068type Defaults struct {
2069 android.ModuleBase
2070 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002071 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002072}
2073
Colin Cross1b16b0e2019-02-12 14:41:32 -08002074// java_defaults provides a set of properties that can be inherited by other java or android modules.
2075//
2076// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2077// property in the defaults module that exists in the depending module will be prepended to the depending module's
2078// value for that property.
2079//
2080// Example:
2081//
Sam Delmerico277795c2022-02-25 17:04:37 +00002082// java_defaults {
2083// name: "example_defaults",
2084// srcs: ["common/**/*.java"],
2085// javacflags: ["-Xlint:all"],
2086// aaptflags: ["--auto-add-overlay"],
2087// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002088//
Sam Delmerico277795c2022-02-25 17:04:37 +00002089// java_library {
2090// name: "example",
2091// defaults: ["example_defaults"],
2092// srcs: ["example/**/*.java"],
2093// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002094//
2095// is functionally identical to:
2096//
Sam Delmerico277795c2022-02-25 17:04:37 +00002097// java_library {
2098// name: "example",
2099// srcs: [
2100// "common/**/*.java",
2101// "example/**/*.java",
2102// ],
2103// javacflags: ["-Xlint:all"],
2104// }
Paul Duffin47357662019-12-05 14:07:14 +00002105func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002106 module := &Defaults{}
2107
Colin Cross89536d42017-07-07 14:35:50 -07002108 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002109 &CommonProperties{},
2110 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002111 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002112 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002113 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002114 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002115 &aaptProperties{},
2116 &androidLibraryProperties{},
2117 &appProperties{},
2118 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002119 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002120 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002121 &ImportProperties{},
2122 &AARImportProperties{},
2123 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002124 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002125 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002126 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002127 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002128 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002129 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002130 )
2131
2132 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002133 return module
2134}
Nan Zhangea568a42017-11-08 21:20:04 -08002135
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002136func kytheExtractJavaFactory() android.Singleton {
2137 return &kytheExtractJavaSingleton{}
2138}
2139
2140type kytheExtractJavaSingleton struct {
2141}
2142
2143func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2144 var xrefTargets android.Paths
2145 ctx.VisitAllModules(func(module android.Module) {
2146 if javaModule, ok := module.(xref); ok {
2147 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2148 }
2149 })
2150 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2151 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002152 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002153 }
2154}
2155
Nan Zhangea568a42017-11-08 21:20:04 -08002156var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002157var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002158var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08002159var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002160
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002161// Add class loader context (CLC) of a given dependency to the current CLC.
2162func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2163 clcMap dexpreopt.ClassLoaderContextMap) {
2164
2165 dep, ok := depModule.(UsesLibraryDependency)
2166 if !ok {
2167 return
2168 }
2169
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002170 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2171
2172 var sdkLib *string
2173 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2174 // A shared SDK library. This should be added as a top-level CLC element.
2175 sdkLib = &depName
2176 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2177 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2178 // property. This should be handled in the same way as a shared SDK library.
2179 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002180 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002181
2182 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002183 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002184 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002185 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2186 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002187 } else if depTag == staticLibTag {
2188 // Propagate <uses-library> through static library dependencies, unless it is a component
2189 // library (such as stubs). Component libraries have a dependency on their SDK library,
2190 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002191 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002192 return
2193 }
2194 } else {
2195 // Don't propagate <uses-library> for other dependency tags.
2196 return
2197 }
2198
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002199 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2200 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2201 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2202 // from its CLC should be added to the current CLC.
2203 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002204 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002205 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002206 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002207 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2208 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002209}
Wei Libafb6d62021-12-10 03:14:59 -08002210
Sam Delmerico79985812022-03-23 20:20:42 +00002211type javaResourcesAttributes struct {
2212 Resources bazel.LabelListAttribute
2213 Resource_strip_prefix *string
2214}
2215
2216func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
2217 var resources bazel.LabelList
2218 var resourceStripPrefix *string
2219
2220 if m.properties.Java_resources != nil {
2221 resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
2222 }
2223
2224 //TODO(b/179889880) handle case where glob includes files outside package
2225 resDeps := ResourceDirsToFiles(
2226 ctx,
2227 m.properties.Java_resource_dirs,
2228 m.properties.Exclude_java_resource_dirs,
2229 m.properties.Exclude_java_resources,
2230 )
2231
2232 for i, resDep := range resDeps {
2233 dir, files := resDep.dir, resDep.files
2234
2235 resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
2236
2237 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2238 // inside the JAR file, so we need to remove that prefix
2239 resourceStripPrefix = proptools.StringPtr(dir.String())
2240 if i > 0 {
2241 // TODO(b/226423379) allow multiple resource prefixes
2242 ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
2243 }
2244 }
2245
2246 return &javaResourcesAttributes{
2247 Resources: bazel.MakeLabelListAttribute(resources),
2248 Resource_strip_prefix: resourceStripPrefix,
2249 }
2250}
2251
Sam Delmericoc0161432022-02-25 21:34:51 +00002252type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002253 *javaResourcesAttributes
Wei Libafb6d62021-12-10 03:14:59 -08002254 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002255 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002256 Javacopts bazel.StringListAttribute
2257}
2258
Sam Delmericoc0161432022-02-25 21:34:51 +00002259type javaDependencyLabels struct {
2260 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2261 Deps bazel.LabelListAttribute
2262 // Dependencies which DO contribute to the API visible to upstream dependencies.
2263 StaticDeps bazel.LabelListAttribute
2264}
2265
Sam Delmerico24da73c2022-03-16 20:36:54 +00002266type eventLogTagsAttributes struct {
2267 Srcs bazel.LabelListAttribute
2268}
2269
Sam Delmerico97bd1272022-08-25 14:45:31 -04002270type aidlLibraryAttributes struct {
2271 Srcs bazel.LabelListAttribute
2272}
2273
2274type javaAidlLibraryAttributes struct {
2275 Deps bazel.LabelListAttribute
2276}
2277
2278// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
2279// and also separates dependencies into dynamic dependencies and static dependencies.
2280// Each corresponding Bazel target type, can have a different method for handling
2281// dynamic vs. static dependencies, and so these are returned to the calling function.
Sam Delmericoc0161432022-02-25 21:34:51 +00002282func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002283 var srcs bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002284 var deps bazel.LabelList
2285 var staticDeps bazel.LabelList
2286
Sam Delmericoe91d0302022-02-23 15:28:33 +00002287 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2288 for axis, configToProps := range archVariantProps {
2289 for config, _props := range configToProps {
2290 if archProps, ok := _props.(*CommonProperties); ok {
2291 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2292 srcs.SetSelectValue(axis, config, archSrcs)
2293 }
2294 }
2295 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002296
2297 javaSrcPartition := "java"
2298 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002299 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002300 aidlSrcPartition := "aidl"
Sam Delmericoc7681022022-02-04 21:01:20 +00002301 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002302 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2303 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2304 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04002305 aidlSrcPartition: android.AidlSrcLabelPartition,
Sam Delmericoc7681022022-02-04 21:01:20 +00002306 })
2307
Sam Delmerico24da73c2022-03-16 20:36:54 +00002308 javaSrcs := srcPartitions[javaSrcPartition]
2309
Sam Delmerico24da73c2022-03-16 20:36:54 +00002310 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2311 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002312 ctx.CreateBazelTargetModule(
2313 bazel.BazelTargetModuleProperties{
2314 Rule_class: "event_log_tags",
2315 Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
2316 },
2317 android.CommonAttributes{Name: logtagsLibName},
2318 &eventLogTagsAttributes{
2319 Srcs: srcPartitions[logtagSrcPartition],
2320 },
2321 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04002322
2323 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2324 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00002325 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002326
2327 if !srcPartitions[aidlSrcPartition].IsEmpty() {
2328 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
2329 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
2330 })
2331
2332 if !aidlSrcs.IsEmpty() {
2333 aidlLibName := m.Name() + "_aidl_library"
2334 ctx.CreateBazelTargetModule(
2335 bazel.BazelTargetModuleProperties{
2336 Rule_class: "aidl_library",
2337 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
2338 },
2339 android.CommonAttributes{Name: aidlLibName},
2340 &aidlLibraryAttributes{
2341 Srcs: aidlSrcs,
2342 },
2343 )
2344 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
2345 }
2346
2347 javaAidlLibName := m.Name() + "_java_aidl_library"
2348 ctx.CreateBazelTargetModule(
2349 bazel.BazelTargetModuleProperties{
2350 Rule_class: "java_aidl_library",
2351 Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
2352 },
2353 android.CommonAttributes{Name: javaAidlLibName},
2354 &javaAidlLibraryAttributes{
2355 Deps: aidlLibs,
2356 },
2357 )
2358
2359 staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
2360 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00002361
Sam Delmerico58614c02022-03-15 21:02:09 +00002362 var javacopts []string
2363 if m.properties.Javacflags != nil {
2364 javacopts = append(javacopts, m.properties.Javacflags...)
2365 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002366 if m.properties.Java_version != nil {
2367 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2368 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2369 }
2370
Sam Delmerico58614c02022-03-15 21:02:09 +00002371 epEnabled := m.properties.Errorprone.Enabled
2372 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
2373 if Bool(epEnabled) {
2374 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2375 }
2376
Sam Delmericoc0161432022-02-25 21:34:51 +00002377 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00002378 Srcs: javaSrcs,
2379 javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
Sam Delmerico77267c72022-03-18 14:11:07 +00002380 Plugins: bazel.MakeLabelListAttribute(
2381 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2382 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002383 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002384 }
2385
2386 if m.properties.Libs != nil {
Alixb4e09a02022-09-27 15:36:01 +00002387
2388 // TODO 244210934 ALIX Check if this else statement breaks presubmits get rid of it if it doesn't
2389 if strings.HasPrefix(ctx.ModuleType(), "java_binary") {
2390 for _, d := range m.properties.Libs {
2391 neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
2392 neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
2393 deps.Add(&neverlinkLabel)
2394 }
2395
2396 } else {
2397 deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
2398 }
Wei Libafb6d62021-12-10 03:14:59 -08002399 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002400
Sam Delmericofde9fb52022-01-28 20:53:38 +00002401 if m.properties.Static_libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002402 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002403 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002404
Sam Delmericoc0161432022-02-25 21:34:51 +00002405 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2406 // Soong does not differentiate between a java_library and the Bazel equivalent of
2407 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2408 // listed directly in the srcs of a java_library, and the classes produced
2409 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2410 // that depend on a java_library with proto sources can link directly to the protobuf API,
2411 // and so this should be a static dependency.
2412 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002413
Sam Delmerico97bd1272022-08-25 14:45:31 -04002414 depLabels := &javaDependencyLabels{}
Sam Delmericoc0161432022-02-25 21:34:51 +00002415 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2416 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002417
Sam Delmericoc0161432022-02-25 21:34:51 +00002418 return commonAttrs, depLabels
2419}
2420
2421type javaLibraryAttributes struct {
2422 *javaCommonAttributes
Alixb4e09a02022-09-27 15:36:01 +00002423 Deps bazel.LabelListAttribute
2424 Exports bazel.LabelListAttribute
2425 Neverlink bazel.BoolAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002426}
2427
2428func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002429 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2430
2431 deps := depLabels.Deps
2432 if !commonAttrs.Srcs.IsEmpty() {
2433 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2434
2435 sdkVersion := m.SdkVersion(ctx)
2436 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2437 // TODO(b/220869005) remove forced dependency on current public android.jar
2438 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2439 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002440 } else if !deps.IsEmpty() {
Sam Delmericoc0161432022-02-25 21:34:51 +00002441 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2442 }
2443
2444 attrs := &javaLibraryAttributes{
2445 javaCommonAttributes: commonAttrs,
2446 Deps: deps,
2447 Exports: depLabels.StaticDeps,
2448 }
Wei Libafb6d62021-12-10 03:14:59 -08002449
2450 props := bazel.BazelTargetModuleProperties{
2451 Rule_class: "java_library",
2452 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2453 }
2454
Alixb4e09a02022-09-27 15:36:01 +00002455 name := m.Name()
2456 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
Wei Libafb6d62021-12-10 03:14:59 -08002457}
2458
2459type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002460 *javaCommonAttributes
2461 Deps bazel.LabelListAttribute
2462 Runtime_deps bazel.LabelListAttribute
2463 Main_class string
2464 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002465}
2466
2467// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2468func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002469 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2470
2471 deps := depLabels.Deps
2472 deps.Append(depLabels.StaticDeps)
2473 if m.binaryProperties.Jni_libs != nil {
2474 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2475 }
2476
2477 var runtimeDeps bazel.LabelListAttribute
2478 if commonAttrs.Srcs.IsEmpty() {
2479 // if there are no sources, then the dependencies can only be used at runtime
2480 runtimeDeps = deps
2481 deps = bazel.LabelListAttribute{}
2482 }
2483
Wei Libafb6d62021-12-10 03:14:59 -08002484 mainClass := ""
2485 if m.binaryProperties.Main_class != nil {
2486 mainClass = *m.binaryProperties.Main_class
2487 }
2488 if m.properties.Manifest != nil {
2489 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2490 if err != nil {
2491 return
2492 }
2493 mainClass = mainClassInManifest
2494 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002495
Wei Libafb6d62021-12-10 03:14:59 -08002496 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002497 javaCommonAttributes: commonAttrs,
2498 Deps: deps,
2499 Runtime_deps: runtimeDeps,
2500 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002501 }
2502
2503 // Attribute jvm_flags
2504 if m.binaryProperties.Jni_libs != nil {
2505 jniLibPackages := map[string]bool{}
2506 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2507 jniLibPackage := jniLibLabel.Label
2508 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2509 if indexOfColon > 0 {
2510 // JNI lib from other package
2511 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2512 } else if indexOfColon == 0 {
2513 // JNI lib in the same package of java_binary
2514 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2515 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2516 }
2517 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2518 jniLibPackages[jniLibPackage] = true
2519 }
2520 }
2521 jniLibPaths := []string{}
2522 for jniLibPackage, _ := range jniLibPackages {
2523 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2524 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2525 }
2526 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2527 }
2528
2529 props := bazel.BazelTargetModuleProperties{
2530 Rule_class: "java_binary",
2531 }
2532
2533 // Create the BazelTargetModule.
2534 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2535}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002536
2537type bazelJavaImportAttributes struct {
Alixb4e09a02022-09-27 15:36:01 +00002538 Jars bazel.LabelListAttribute
2539 Exports bazel.LabelListAttribute
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002540}
2541
2542// java_import bp2Build converter.
2543func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002544 var jars bazel.LabelListAttribute
2545 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2546 for axis, configToProps := range archVariantProps {
2547 for config, _props := range configToProps {
2548 if archProps, ok := _props.(*ImportProperties); ok {
2549 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2550 jars.SetSelectValue(axis, config, archJars)
2551 }
2552 }
2553 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002554
2555 attrs := &bazelJavaImportAttributes{
2556 Jars: jars,
2557 }
2558 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2559
Alixb4e09a02022-09-27 15:36:01 +00002560 name := android.RemoveOptionalPrebuiltPrefix(i.Name())
2561
2562 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
2563
2564 neverlink := true
2565 neverlinkAttrs := &javaLibraryAttributes{
2566 Neverlink: bazel.BoolAttribute{Value: &neverlink},
2567 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
2568 }
2569 ctx.CreateBazelTargetModule(bazel.BazelTargetModuleProperties{Rule_class: "java_library"}, android.CommonAttributes{Name: name + "-neverlink"}, neverlinkAttrs)
2570
Sam Delmerico277795c2022-02-25 17:04:37 +00002571}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002572
Sam Delmerico277795c2022-02-25 17:04:37 +00002573var _ android.MixedBuildBuildable = (*Import)(nil)
2574
2575func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
2576 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
2577}
2578
2579func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
2580 i.commonBuildActions(ctx)
2581
2582 bazelCtx := ctx.Config().BazelContext
2583 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
2584 if err != nil {
2585 ctx.ModuleErrorf(err.Error())
2586 return
2587 }
2588
2589 bazelJars := android.Paths{}
2590 for _, bazelOutputFile := range filePaths {
2591 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
2592 }
2593
2594 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
2595 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
2596 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
2597 android.OptionalPath{}, // manifest
2598 false, // stripDirEntries
2599 []string{}, // filesToStrip
2600 []string{}, // dirsToStrip
2601 )
2602 i.combinedClasspathFile = outputFile
2603
2604 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2605 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
2606 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
2607 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
2608 //TODO(b/240308299) include AIDL information from Bazel
2609 })
2610
2611 i.maybeInstall(ctx, jarName, outputFile)
2612}
2613
2614func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
2615 bazelCtx := ctx.Config().BazelContext
2616 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
2617}
2618
2619func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
2620 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002621}