blob: fc2af3b173fc6b454bcb8cdb865da2687f962281 [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
Colin Crossa4f08812018-10-02 22:03:40 -0700424}
425
Jiyong Parkf1691d22021-03-29 20:11:58 +0900426func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700427 sdkDep := decodeSdkDep(ctx, sdkContext)
428 if sdkDep.useModule {
429 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
430 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400431 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700432 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
433 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
434 }
435 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
436 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
437 }
438 }
439 if sdkDep.systemModules != "" {
440 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
441 }
442}
443
Colin Cross32f676a2017-09-06 13:41:06 -0700444type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700445 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
446 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
447 // systemModules and java9Classpath instead.
448 bootClasspath classpath
449
450 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
451 // contains header jars for all static and non-static dependencies.
452 classpath classpath
453
454 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
455 // header jars for all non-static dependencies. Static dependencies have already been
456 // combined into the program jar.
457 dexClasspath classpath
458
459 // java9Classpath is the list of jars that will be added to the classpath when targeting
460 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
461 // are provided by systemModules.
462 java9Classpath classpath
463
Colin Cross748b2d82020-11-19 13:52:06 -0800464 processorPath classpath
465 errorProneProcessorPath classpath
466 processorClasses []string
467 staticJars android.Paths
468 staticHeaderJars android.Paths
469 staticResourceJars android.Paths
470 aidlIncludeDirs android.Paths
471 srcs android.Paths
472 srcJars android.Paths
473 systemModules *systemModules
474 aidlPreprocess android.OptionalPath
475 kotlinStdlib android.Paths
476 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700477 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800478
479 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700480}
Colin Cross2fe66872015-03-30 17:20:39 -0700481
Colin Cross54250902017-12-05 09:28:08 -0800482func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
483 for _, f := range dep.Srcs() {
484 if f.Ext() != ".jar" {
485 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
486 ctx.OtherModuleName(dep.(blueprint.Module)))
487 }
488 }
489}
490
Jiyong Parkf1691d22021-03-29 20:11:58 +0900491func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700492 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700493 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700494 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900495 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Bascace720c32022-05-24 12:13:50 +0100496 } else if ctx.Config().TargetsJava17() {
497 // Temporary experimental flag to be able to try and build with
498 // java version 17 options. The flag, if used, just sets Java
499 // 17 as the default version, leaving any components that
500 // target an older version intact.
501 return JAVA_VERSION_17
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000502 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000503 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700504 }
Nan Zhang357466b2018-04-17 17:38:36 -0700505}
506
Colin Cross1e743852019-10-28 11:37:20 -0700507type javaVersion int
508
509const (
510 JAVA_VERSION_UNSUPPORTED = 0
511 JAVA_VERSION_6 = 6
512 JAVA_VERSION_7 = 7
513 JAVA_VERSION_8 = 8
514 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000515 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100516 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700517)
518
519func (v javaVersion) String() string {
520 switch v {
521 case JAVA_VERSION_6:
522 return "1.6"
523 case JAVA_VERSION_7:
524 return "1.7"
525 case JAVA_VERSION_8:
526 return "1.8"
527 case JAVA_VERSION_9:
528 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000529 case JAVA_VERSION_11:
530 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100531 case JAVA_VERSION_17:
532 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700533 default:
534 return "unsupported"
535 }
536}
537
Cole Faustd96eebf2022-06-28 14:41:27 -0700538func (v javaVersion) StringForKotlinc() string {
539 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
540 // error: unknown JVM target version: foo
541 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
542 switch v {
543 case JAVA_VERSION_7:
544 return "1.6"
545 case JAVA_VERSION_9:
546 return "9"
547 default:
548 return v.String()
549 }
550}
551
Colin Cross1e743852019-10-28 11:37:20 -0700552// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
553func (v javaVersion) usesJavaModules() bool {
554 return v >= 9
555}
556
557func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100558 switch javaVersion {
559 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700560 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100561 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700562 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100563 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700564 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100565 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700566 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000567 case "11":
568 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100569 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100570 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100571 case "10", "12", "13", "14", "15", "16":
572 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700573 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100574 default:
575 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700576 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100577 }
578}
579
Colin Cross2fe66872015-03-30 17:20:39 -0700580//
581// Java libraries (.jar file)
582//
583
Colin Crossf506d872017-07-19 15:53:04 -0700584type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700585 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700586
587 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700588}
589
Jiyong Park45bf82e2020-12-15 22:29:02 +0900590var _ android.ApexModule = (*Library)(nil)
591
satayevd604b212021-07-21 14:23:52 +0100592// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100593type PermittedPackagesForUpdatableBootJars interface {
594 PermittedPackagesForUpdatableBootJars() []string
595}
596
597var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
598
599func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
600 return j.properties.Permitted_packages
601}
602
Colin Cross42be7612019-02-21 18:12:14 -0800603func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000604 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700605 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000606 return true
607 }
608
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000609 // Store uncompressed (and do not strip) dex files from boot class path jars.
610 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
611 return true
612 }
613
614 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000615 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000616 return true
617 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800618 if ctx.Config().UncompressPrivAppDex() &&
619 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
620 return true
621 }
622
Colin Cross2fc72f62018-12-21 12:59:54 -0800623 return false
624}
625
Jiakai Zhang22450f22021-10-11 03:05:20 +0000626// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
627func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
628 if dexer.dexProperties.Uncompress_dex == nil {
629 // If the value was not force-set by the user, use reasonable default based on the module.
630 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
631 }
632}
633
Colin Crossf506d872017-07-19 15:53:04 -0700634func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000635
636 j.provideHiddenAPIPropertyInfo(ctx)
637
Jiyong Park92315372021-04-02 08:45:46 +0900638 j.sdkVersion = j.SdkVersion(ctx)
639 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000640 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900641
Colin Cross56a83212020-09-15 18:30:11 -0700642 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
643 if !apexInfo.IsForPlatform() {
644 j.hideApexVariantFromMake = true
645 }
646
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100647 j.checkSdkVersions(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800648 if ctx.Device() {
649 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
650 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
651 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
652 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
653 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
654 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
655 }
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700656 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700657
bralee1fbf4402020-05-21 10:11:59 +0800658 // Collect the module directory for IDE info in java/jdeps.go.
659 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
660
Colin Cross56a83212020-09-15 18:30:11 -0700661 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900662 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700663 var extraInstallDeps android.Paths
664 if j.InstallMixin != nil {
665 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
666 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700667 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
668 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800669 j.hostdexInstallFile = ctx.InstallFile(
670 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700671 j.Stem()+"-hostdex.jar", j.outputFile)
672 }
673 var installDir android.InstallPath
674 if ctx.InstallInTestcases() {
675 var archDir string
676 if !ctx.Host() {
677 archDir = ctx.DeviceConfig().DeviceArch()
678 }
679 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
680 } else {
681 installDir = android.PathForModuleInstall(ctx, "framework")
682 }
683 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700684 }
Colin Crossb7a63242015-04-16 14:09:14 -0700685}
686
Colin Crossf506d872017-07-19 15:53:04 -0700687func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700688 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100689 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700690}
691
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000692const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000693 aidlIncludeDir = "aidl"
694 javaDir = "java"
695 jarFileSuffix = ".jar"
696 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000697)
698
Paul Duffina0dbf432019-12-05 11:25:53 +0000699// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000700func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000701 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000702}
703
Paul Duffina04c1072020-03-02 10:16:35 +0000704func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
705 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000706}
707
Paul Duffin13879572019-11-28 14:31:38 +0000708type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000709 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000710
711 // Function to retrieve the appropriate output jar (implementation or header) from
712 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000713 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
714
715 // Function to compute the snapshot relative path to which the named library's
716 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000717 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000718
719 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
720 // files like aidl files should also be copied.
721 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000722}
723
Paul Duffindb170e42020-12-08 17:48:25 +0000724const (
725 onlyCopyJarToSnapshot = true
726 copyEverythingToSnapshot = false
727)
728
Paul Duffin296701e2021-07-14 10:29:36 +0100729func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
730 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000731}
732
733func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
734 _, ok := module.(*Library)
735 return ok
736}
737
Paul Duffin3a4eb502020-03-19 16:11:18 +0000738func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
739 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000740}
Paul Duffina0dbf432019-12-05 11:25:53 +0000741
Paul Duffin14eb4672020-03-02 11:33:02 +0000742func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000743 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000744}
745
746type librarySdkMemberProperties struct {
747 android.SdkMemberPropertiesBase
748
Paul Duffin864e1b42020-05-06 10:23:19 +0100749 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000750 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100751
752 // The list of permitted packages that need to be passed to the prebuilts as they are used to
753 // create the updatable-bcp-packages.txt file.
754 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000755}
756
Paul Duffin3a4eb502020-03-19 16:11:18 +0000757func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000758 j := variant.(*Library)
759
Paul Duffindb170e42020-12-08 17:48:25 +0000760 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
761
Paul Duffina551a1c2020-03-17 21:04:24 +0000762 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100763
764 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000765}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000766
Paul Duffin3a4eb502020-03-19 16:11:18 +0000767func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000768 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000769
Paul Duffindb170e42020-12-08 17:48:25 +0000770 memberType := ctx.MemberType().(*librarySdkMemberType)
771
Paul Duffina551a1c2020-03-17 21:04:24 +0000772 exportedJar := p.JarToExport
773 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000774 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000775 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000776
777 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000778 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
779
Paul Duffina551a1c2020-03-17 21:04:24 +0000780 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
781 }
782
Paul Duffin869de142021-07-15 14:14:41 +0100783 if len(p.PermittedPackages) > 0 {
784 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
785 }
786
Paul Duffindb170e42020-12-08 17:48:25 +0000787 // Do not copy anything else to the snapshot.
788 if memberType.onlyCopyJarToSnapshot {
789 return
790 }
791
Paul Duffina551a1c2020-03-17 21:04:24 +0000792 aidlIncludeDirs := p.AidlIncludeDirs
793 if len(aidlIncludeDirs) != 0 {
794 sdkModuleContext := ctx.SdkModuleContext()
795 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000796 // TODO(jiyong): copy parcelable declarations only
797 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
798 for _, file := range aidlFiles {
799 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
800 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000801 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000802
Paul Duffina551a1c2020-03-17 21:04:24 +0000803 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000804 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000805}
806
Colin Cross1b16b0e2019-02-12 14:41:32 -0800807// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
808//
809// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
810// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
811// as a `static_libs` dependency of another module.
812//
813// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
814// a device.
815//
816// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
817// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700818func LibraryFactory() android.Module {
819 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700820
Colin Crossce6734e2020-06-15 16:09:53 -0700821 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700822
Paul Duffin71b33cc2021-06-23 11:39:47 +0100823 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100824
Jiyong Park7f7766d2019-07-25 22:02:35 +0900825 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900826 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800827 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900828 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700829 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700830}
831
Colin Cross1b16b0e2019-02-12 14:41:32 -0800832// java_library_static is an obsolete alias for java_library.
833func LibraryStaticFactory() android.Module {
834 return LibraryFactory()
835}
836
837// java_library_host builds and links sources into a `.jar` file for the host.
838//
839// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
840// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700841func LibraryHostFactory() android.Module {
842 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700843
Colin Crossce6734e2020-06-15 16:09:53 -0700844 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700845
Colin Cross9ae1b922018-06-26 17:59:05 -0700846 module.Module.properties.Installable = proptools.BoolPtr(true)
847
Jiyong Park7f7766d2019-07-25 22:02:35 +0900848 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100849 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800850 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900851 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700852 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700853}
854
855//
Colin Crossb628ea52018-08-14 16:42:33 -0700856// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700857//
858
Dan Shi95d19422020-08-15 12:24:26 -0700859// Test option struct.
860type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800861 android.CommonTestOptions
862
Dan Shi95d19422020-08-15 12:24:26 -0700863 // a list of extra test configuration files that should be installed with the module.
864 Extra_test_configs []string `android:"path,arch_variant"`
865}
866
Colin Cross05638fc2018-04-09 18:40:24 -0700867type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700868 // list of compatibility suites (for example "cts", "vts") that the module should be
869 // installed into.
870 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700871
872 // the name of the test configuration (for example "AndroidTest.xml") that should be
873 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800874 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700875
Jack He33338892018-09-19 02:21:28 -0700876 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
877 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800878 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700879
Colin Crossd96ca352018-08-10 16:06:24 -0700880 // list of files or filegroup modules that provide data that should be installed alongside
881 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900882 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700883
884 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
885 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
886 // explicitly.
887 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800888
889 // Add parameterized mainline modules to auto generated test config. The options will be
890 // handled by TradeFed to do downloading and installing the specified modules on the device.
891 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700892
893 // Test options.
894 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800895
896 // Names of modules containing JNI libraries that should be installed alongside the test.
897 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700898
899 // Install the test into a folder named for the module in all test suites.
900 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700901}
902
Liz Kammerdd849a82020-06-12 16:38:45 -0700903type hostTestProperties struct {
904 // list of native binary modules that should be installed alongside the test
905 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000906
907 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000908 // This property only adds the first variant of the dependency
909 Data_device_bins_first []string `android:"arch_variant"`
910
911 // list of device binary modules that should be installed alongside the test
912 // This property adds 64bit AND 32bit variants of the dependency
913 Data_device_bins_both []string `android:"arch_variant"`
914
915 // list of device binary modules that should be installed alongside the test
916 // This property only adds 64bit variants of the dependency
917 Data_device_bins_64 []string `android:"arch_variant"`
918
919 // list of device binary modules that should be installed alongside the test
920 // This property adds 32bit variants of the dependency if available, or else
921 // defaults to the 64bit variant
922 Data_device_bins_prefer32 []string `android:"arch_variant"`
923
924 // list of device binary modules that should be installed alongside the test
925 // This property only adds 32bit variants of the dependency
926 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700927}
928
Paul Duffin42df1442019-03-20 12:45:53 +0000929type testHelperLibraryProperties struct {
930 // list of compatibility suites (for example "cts", "vts") that the module should be
931 // installed into.
932 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700933
934 // Install the test into a folder named for the module in all test suites.
935 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000936}
937
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000938type prebuiltTestProperties struct {
939 // list of compatibility suites (for example "cts", "vts") that the module should be
940 // installed into.
941 Test_suites []string `android:"arch_variant"`
942
943 // the name of the test configuration (for example "AndroidTest.xml") that should be
944 // installed with the module.
945 Test_config *string `android:"path,arch_variant"`
946}
947
Colin Cross05638fc2018-04-09 18:40:24 -0700948type Test struct {
949 Library
950
951 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700952
Dan Shi95d19422020-08-15 12:24:26 -0700953 testConfig android.Path
954 extraTestConfigs android.Paths
955 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700956}
957
Liz Kammerdd849a82020-06-12 16:38:45 -0700958type TestHost struct {
959 Test
960
961 testHostProperties hostTestProperties
962}
963
Paul Duffin42df1442019-03-20 12:45:53 +0000964type TestHelperLibrary struct {
965 Library
966
967 testHelperLibraryProperties testHelperLibraryProperties
968}
969
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000970type JavaTestImport struct {
971 Import
972
973 prebuiltTestProperties prebuiltTestProperties
974
975 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700976 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000977}
978
Colin Cross24cc4be62021-11-03 14:09:41 -0700979func (j *Test) InstallInTestcases() bool {
980 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
981 // testcases by base_rules.mk.
982 return !j.Host()
983}
984
985func (j *TestHelperLibrary) InstallInTestcases() bool {
986 return true
987}
988
989func (j *JavaTestImport) InstallInTestcases() bool {
990 return true
991}
992
Sam Delmericocc271e22022-06-01 15:45:02 +0000993func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
994 if len(j.testHostProperties.Data_device_bins_first) > 0 {
995 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
996 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
997 }
998
999 var maybeAndroid32Target *android.Target
1000 var maybeAndroid64Target *android.Target
1001 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1002 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1003 if len(android32TargetList) > 0 {
1004 maybeAndroid32Target = &android32TargetList[0]
1005 }
1006 if len(android64TargetList) > 0 {
1007 maybeAndroid64Target = &android64TargetList[0]
1008 }
1009
1010 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1011 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1012 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1013 return
1014 }
1015 if maybeAndroid32Target != nil {
1016 ctx.AddFarVariationDependencies(
1017 maybeAndroid32Target.Variations(),
1018 dataDeviceBinsTag,
1019 j.testHostProperties.Data_device_bins_both...,
1020 )
1021 }
1022 if maybeAndroid64Target != nil {
1023 ctx.AddFarVariationDependencies(
1024 maybeAndroid64Target.Variations(),
1025 dataDeviceBinsTag,
1026 j.testHostProperties.Data_device_bins_both...,
1027 )
1028 }
1029 }
1030
1031 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1032 if maybeAndroid32Target != nil {
1033 ctx.AddFarVariationDependencies(
1034 maybeAndroid32Target.Variations(),
1035 dataDeviceBinsTag,
1036 j.testHostProperties.Data_device_bins_prefer32...,
1037 )
1038 } else {
1039 if maybeAndroid64Target == nil {
1040 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1041 return
1042 }
1043 ctx.AddFarVariationDependencies(
1044 maybeAndroid64Target.Variations(),
1045 dataDeviceBinsTag,
1046 j.testHostProperties.Data_device_bins_prefer32...,
1047 )
1048 }
1049 }
1050
1051 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1052 if maybeAndroid32Target == nil {
1053 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1054 return
1055 }
1056 deviceVariations := maybeAndroid32Target.Variations()
1057 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1058 }
1059
1060 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1061 if maybeAndroid64Target == nil {
1062 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1063 return
1064 }
1065 deviceVariations := maybeAndroid64Target.Variations()
1066 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1067 }
1068}
1069
Liz Kammerdd849a82020-06-12 16:38:45 -07001070func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1071 if len(j.testHostProperties.Data_native_bins) > 0 {
1072 for _, target := range ctx.MultiTargets() {
1073 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1074 }
1075 }
1076
Colin Crossf8d9c492021-01-26 11:01:43 -08001077 if len(j.testProperties.Jni_libs) > 0 {
1078 for _, target := range ctx.MultiTargets() {
1079 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1080 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1081 }
1082 }
1083
Sam Delmericocc271e22022-06-01 15:45:02 +00001084 j.addDataDeviceBinsDeps(ctx)
1085
Liz Kammerdd849a82020-06-12 16:38:45 -07001086 j.deps(ctx)
1087}
1088
Yuexi Ma627263f2021-03-04 13:47:56 -08001089func (j *TestHost) AddExtraResource(p android.Path) {
1090 j.extraResources = append(j.extraResources, p)
1091}
1092
Sam Delmericocc271e22022-06-01 15:45:02 +00001093func (j *TestHost) dataDeviceBins() []string {
1094 ret := make([]string, 0,
1095 len(j.testHostProperties.Data_device_bins_first)+
1096 len(j.testHostProperties.Data_device_bins_both)+
1097 len(j.testHostProperties.Data_device_bins_prefer32)+
1098 len(j.testHostProperties.Data_device_bins_32)+
1099 len(j.testHostProperties.Data_device_bins_64),
1100 )
1101
1102 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1103 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1104 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1105 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1106 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1107
1108 return ret
1109}
1110
Sam Delmericob3342ce2022-01-20 21:10:28 +00001111func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1112 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001113 dataDeviceBins := j.dataDeviceBins()
1114 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001115 // add Tradefed configuration to push device bins to device for testing
1116 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1117 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001118 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001119 fullPath := filepath.Join(remoteDir, bin)
1120 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1121 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001122 configs = append(configs, tradefed.Object{
1123 Type: "target_preparer",
1124 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1125 Options: options,
1126 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001127 }
1128
1129 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
1130}
1131
Colin Cross303e21f2018-08-07 16:49:25 -07001132func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001133 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1134}
1135
1136func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001137 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1138 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001139 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001140 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1141 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001142
Dan Shi6ffaaa82019-09-26 11:41:36 -07001143 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001144 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -07001145
Colin Cross8a497952019-03-05 22:25:09 -08001146 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001147
Dan Shi95d19422020-08-15 12:24:26 -07001148 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1149
Liz Kammerdd849a82020-06-12 16:38:45 -07001150 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1151 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1152 })
1153
Sam Delmericob3342ce2022-01-20 21:10:28 +00001154 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1155 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1156 })
1157
Colin Crossf8d9c492021-01-26 11:01:43 -08001158 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1159 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1160 if sharedLibInfo.SharedLibrary != nil {
1161 // Copy to an intermediate output directory to append "lib[64]" to the path,
1162 // so that it's compatible with the default rpath values.
1163 var relPath string
1164 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1165 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1166 } else {
1167 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1168 }
1169 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1170 ctx.Build(pctx, android.BuildParams{
1171 Rule: android.Cp,
1172 Input: sharedLibInfo.SharedLibrary,
1173 Output: relocatedLib,
1174 })
1175 j.data = append(j.data, relocatedLib)
1176 } else {
1177 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1178 }
1179 })
1180
Colin Cross303e21f2018-08-07 16:49:25 -07001181 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001182}
1183
Paul Duffin42df1442019-03-20 12:45:53 +00001184func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1185 j.Library.GenerateAndroidBuildActions(ctx)
1186}
1187
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001188func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1189 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001190 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001191
1192 j.Import.GenerateAndroidBuildActions(ctx)
1193}
1194
1195type testSdkMemberType struct {
1196 android.SdkMemberTypeBase
1197}
1198
Paul Duffin296701e2021-07-14 10:29:36 +01001199func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1200 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001201}
1202
1203func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1204 _, ok := module.(*Test)
1205 return ok
1206}
1207
Paul Duffin3a4eb502020-03-19 16:11:18 +00001208func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1209 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001210}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001211
Paul Duffin14eb4672020-03-02 11:33:02 +00001212func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1213 return &testSdkMemberProperties{}
1214}
1215
1216type testSdkMemberProperties struct {
1217 android.SdkMemberPropertiesBase
1218
Paul Duffina551a1c2020-03-17 21:04:24 +00001219 JarToExport android.Path
1220 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001221}
1222
Paul Duffin3a4eb502020-03-19 16:11:18 +00001223func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001224 test := variant.(*Test)
1225
1226 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001227 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001228 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001229 }
1230
Paul Duffina551a1c2020-03-17 21:04:24 +00001231 p.JarToExport = implementationJars[0]
1232 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001233}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001234
Paul Duffin3a4eb502020-03-19 16:11:18 +00001235func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001236 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001237
Paul Duffina551a1c2020-03-17 21:04:24 +00001238 exportedJar := p.JarToExport
1239 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001240 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001241 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001242
1243 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001244 }
1245
1246 testConfig := p.TestConfig
1247 if testConfig != nil {
1248 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1249 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001250 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1251 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001252}
1253
Colin Cross1b16b0e2019-02-12 14:41:32 -08001254// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1255// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1256//
1257// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1258// compiled against the device bootclasspath.
1259//
1260// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1261// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001262func TestFactory() android.Module {
1263 module := &Test{}
1264
Colin Crossce6734e2020-06-15 16:09:53 -07001265 module.addHostAndDeviceProperties()
1266 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001267
Colin Cross9ae1b922018-06-26 17:59:05 -07001268 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001269 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001270 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001271
Paul Duffinb6b89a42021-05-06 16:33:43 +01001272 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001273 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001274 return module
1275}
1276
Paul Duffin42df1442019-03-20 12:45:53 +00001277// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1278func TestHelperLibraryFactory() android.Module {
1279 module := &TestHelperLibrary{}
1280
Colin Crossce6734e2020-06-15 16:09:53 -07001281 module.addHostAndDeviceProperties()
1282 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001283
Colin Cross9a4abed2019-04-24 13:19:28 -07001284 module.Module.properties.Installable = proptools.BoolPtr(true)
1285 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001286 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001287
Paul Duffin42df1442019-03-20 12:45:53 +00001288 InitJavaModule(module, android.HostAndDeviceSupported)
1289 return module
1290}
1291
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001292// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1293// and makes sure that it is added to the appropriate test suite.
1294//
1295// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1296// compiled against an Android classpath.
1297//
1298// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1299// for host modules.
1300func JavaTestImportFactory() android.Module {
1301 module := &JavaTestImport{}
1302
1303 module.AddProperties(
1304 &module.Import.properties,
1305 &module.prebuiltTestProperties)
1306
1307 module.Import.properties.Installable = proptools.BoolPtr(true)
1308
1309 android.InitPrebuiltModule(module, &module.properties.Jars)
1310 android.InitApexModule(module)
1311 android.InitSdkAwareModule(module)
1312 InitJavaModule(module, android.HostAndDeviceSupported)
1313 return module
1314}
1315
Colin Cross1b16b0e2019-02-12 14:41:32 -08001316// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1317// allow running the test with `atest` or a `TEST_MAPPING` file.
1318//
1319// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1320// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001321func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001322 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001323
Colin Crossce6734e2020-06-15 16:09:53 -07001324 module.addHostProperties()
1325 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001326 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001327
Yuexi Ma627263f2021-03-04 13:47:56 -08001328 InitTestHost(
1329 module,
1330 proptools.BoolPtr(true),
1331 nil,
1332 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001333
Liz Kammerdd849a82020-06-12 16:38:45 -07001334 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001335
Colin Cross05638fc2018-04-09 18:40:24 -07001336 return module
1337}
1338
Yuexi Ma627263f2021-03-04 13:47:56 -08001339func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1340 th.properties.Installable = installable
1341 th.testProperties.Auto_gen_config = autoGenConfig
1342 th.testProperties.Test_suites = testSuites
1343}
1344
Colin Cross05638fc2018-04-09 18:40:24 -07001345//
Colin Cross2fe66872015-03-30 17:20:39 -07001346// Java Binaries (.jar file plus wrapper script)
1347//
1348
Colin Crossf506d872017-07-19 15:53:04 -07001349type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001350 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001351 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001352
1353 // Name of the class containing main to be inserted into the manifest as Main-Class.
1354 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001355
1356 // Names of modules containing JNI libraries that should be installed alongside the host
1357 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001358 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001359}
1360
Colin Crossf506d872017-07-19 15:53:04 -07001361type Binary struct {
1362 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001363
Colin Crossf506d872017-07-19 15:53:04 -07001364 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001365
Colin Cross6b4a32d2017-12-05 13:42:45 -08001366 isWrapperVariant bool
1367
Colin Crossc3315992017-12-08 19:12:36 -08001368 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001369 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001370}
1371
Alex Light24237172017-10-26 09:46:21 -07001372func (j *Binary) HostToolPath() android.OptionalPath {
1373 return android.OptionalPathForPath(j.binaryFile)
1374}
1375
Colin Crossf506d872017-07-19 15:53:04 -07001376func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001377 if ctx.Arch().ArchType == android.Common {
1378 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001379 if j.binaryProperties.Main_class != nil {
1380 if j.properties.Manifest != nil {
1381 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1382 }
1383 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1384 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1385 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1386 }
1387
Colin Cross6b4a32d2017-12-05 13:42:45 -08001388 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001389 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001390 // Handle the binary wrapper
1391 j.isWrapperVariant = true
1392
Colin Cross366938f2017-12-11 16:29:02 -08001393 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001394 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001395 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001396 if ctx.Windows() {
1397 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1398 }
1399
Colin Cross6b4a32d2017-12-05 13:42:45 -08001400 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1401 }
1402
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001403 ext := ""
1404 if ctx.Windows() {
1405 ext = ".bat"
1406 }
1407
Colin Crossc179ea62020-10-09 10:54:15 -07001408 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001409 // of the wrapper variant, which will include the common variant's jar file and any JNI
1410 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001411 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001412 ctx.ModuleName()+ext, j.wrapperFile)
1413 }
Colin Cross2fe66872015-03-30 17:20:39 -07001414}
1415
Colin Crossf506d872017-07-19 15:53:04 -07001416func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001417 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001418 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001419 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001420 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001421 // These dependencies ensure the host installation rules will install the jar file and
1422 // the jni libraries when the wrapper is installed.
1423 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1424 ctx.AddVariationDependencies(
1425 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1426 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001427 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001428}
1429
Colin Cross1b16b0e2019-02-12 14:41:32 -08001430// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1431// as well.
1432//
1433// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1434// compiled against the device bootclasspath.
1435//
1436// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1437// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001438func BinaryFactory() android.Module {
1439 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001440
Colin Crossce6734e2020-06-15 16:09:53 -07001441 module.addHostAndDeviceProperties()
1442 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001443
Colin Cross9ae1b922018-06-26 17:59:05 -07001444 module.Module.properties.Installable = proptools.BoolPtr(true)
1445
Colin Cross6b4a32d2017-12-05 13:42:45 -08001446 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1447 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001448 android.InitBazelModule(module)
1449
Colin Cross36242852017-06-23 15:06:31 -07001450 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001451}
1452
Colin Cross1b16b0e2019-02-12 14:41:32 -08001453// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1454//
1455// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1456// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001457func BinaryHostFactory() android.Module {
1458 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001459
Colin Crossce6734e2020-06-15 16:09:53 -07001460 module.addHostProperties()
1461 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001462
Colin Cross9ae1b922018-06-26 17:59:05 -07001463 module.Module.properties.Installable = proptools.BoolPtr(true)
1464
Colin Cross6b4a32d2017-12-05 13:42:45 -08001465 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1466 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001467 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001468 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001469}
1470
1471//
1472// Java prebuilts
1473//
1474
Colin Cross74d73e22017-08-02 11:05:49 -07001475type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001476 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001477
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001478 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1479 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001480 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001481
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001482 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1483 // specified.
1484 Min_sdk_version *string
1485
William Loh5a082f92022-05-17 20:21:50 +00001486 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
1487 // and uses-permission tags in manifest_fixer.
1488 Replace_max_sdk_version_placeholder *string
1489
Colin Cross535e2cf2017-10-20 17:57:49 -07001490 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001491
Paul Duffin869de142021-07-15 14:14:41 +01001492 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001493 Permitted_packages []string
1494
Jiyong Park1be96912018-05-28 18:02:19 +09001495 // List of shared java libs that this module has dependencies to
1496 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001497
1498 // List of files to remove from the jar file(s)
1499 Exclude_files []string
1500
1501 // List of directories to remove from the jar file(s)
1502 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001503
1504 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001505 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001506
1507 // set the name of the output
1508 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001509
1510 Aidl struct {
1511 // directories that should be added as include directories for any aidl sources of modules
1512 // that depend on this module, as well as to aidl for this module.
1513 Export_include_dirs []string
1514 }
Colin Cross74d73e22017-08-02 11:05:49 -07001515}
1516
1517type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001518 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001519 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001520 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001521 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001522 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001523 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001524
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001525 // Functionality common to Module and Import.
1526 embeddableInModuleAndImport
1527
Liz Kammerd6c31d22020-08-05 15:40:41 -07001528 hiddenAPI
1529 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001530 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001531
Colin Cross74d73e22017-08-02 11:05:49 -07001532 properties ImportProperties
1533
Liz Kammerd6c31d22020-08-05 15:40:41 -07001534 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001535 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001536 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001537
Colin Cross0a6e0072017-08-30 14:24:55 -07001538 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001539 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001540 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001541
1542 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001543
1544 sdkVersion android.SdkSpec
1545 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001546}
1547
Paul Duffin630b11e2021-07-15 13:35:26 +01001548var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1549
1550func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1551 return j.properties.Permitted_packages
1552}
1553
Jiyong Park92315372021-04-02 08:45:46 +09001554func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1555 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001556}
1557
Jiyong Parkf1691d22021-03-29 20:11:58 +09001558func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001559 return "none"
1560}
1561
Jiyong Park92315372021-04-02 08:45:46 +09001562func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001563 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001564 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001565 }
Jiyong Park92315372021-04-02 08:45:46 +09001566 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001567}
1568
William Loh5a082f92022-05-17 20:21:50 +00001569func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
1570 if j.properties.Replace_max_sdk_version_placeholder != nil {
1571 return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
1572 }
1573 return android.SdkSpecFrom(ctx, "")
1574}
1575
Jiyong Park92315372021-04-02 08:45:46 +09001576func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1577 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001578}
1579
Colin Cross74d73e22017-08-02 11:05:49 -07001580func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001581 return &j.prebuilt
1582}
1583
Colin Cross74d73e22017-08-02 11:05:49 -07001584func (j *Import) PrebuiltSrcs() []string {
1585 return j.properties.Jars
1586}
1587
1588func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001589 return j.prebuilt.Name(j.ModuleBase.Name())
1590}
1591
Jiyong Park0b238752019-10-29 11:23:10 +09001592func (j *Import) Stem() string {
1593 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1594}
1595
Jiyong Park618922e2020-01-08 13:35:43 +09001596func (a *Import) JacocoReportClassesFile() android.Path {
1597 return nil
1598}
1599
Bill Peckhama41a6962021-01-11 10:58:54 -08001600func (j *Import) LintDepSets() LintDepSets {
1601 return LintDepSets{}
1602}
1603
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001604func (j *Import) getStrictUpdatabilityLinting() bool {
1605 return false
1606}
1607
1608func (j *Import) setStrictUpdatabilityLinting(bool) {
1609}
1610
Colin Cross74d73e22017-08-02 11:05:49 -07001611func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001612 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001613
1614 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001615 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001616 }
Colin Cross1e676be2016-10-12 14:38:15 -07001617}
1618
Sam Delmerico277795c2022-02-25 17:04:37 +00001619func (j *Import) commonBuildActions(ctx android.ModuleContext) {
1620 //TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09001621 j.sdkVersion = j.SdkVersion(ctx)
1622 j.minSdkVersion = j.MinSdkVersion(ctx)
1623
Colin Cross56a83212020-09-15 18:30:11 -07001624 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1625 j.hideApexVariantFromMake = true
1626 }
1627
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001628 if ctx.Windows() {
1629 j.HideFromMake()
1630 }
Sam Delmerico277795c2022-02-25 17:04:37 +00001631}
1632
1633func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1634 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001635
Colin Cross8a497952019-03-05 22:25:09 -08001636 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001637
Jiyong Park0b238752019-10-29 11:23:10 +09001638 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001639 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001640 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1641 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001642 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001643 inputFile := outputFile
1644 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1645 TransformJetifier(ctx, outputFile, inputFile)
1646 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001647 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001648 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001649
Liz Kammerd6c31d22020-08-05 15:40:41 -07001650 var flags javaBuilderFlags
1651
Jiyong Park1be96912018-05-28 18:02:19 +09001652 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001653 tag := ctx.OtherModuleDependencyTag(module)
1654
Colin Crossdcf71b22021-02-01 13:59:03 -08001655 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1656 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001657 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001658 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001659 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1660 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1661 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001662 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001663 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001664 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001665 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001666 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001667 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001668 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09001669 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001670 }
1671 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001672
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001673 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001674 })
1675
Sam Delmerico277795c2022-02-25 17:04:37 +00001676 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09001677
1678 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001679
Paul Duffin064b70c2020-11-02 17:32:38 +00001680 if ctx.Device() {
1681 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1682 // obtained from the associated deapexer module.
1683 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1684 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001685 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001686 di := android.FindDeapexerProviderForModule(ctx)
1687 if di == nil {
1688 return // An error has been reported by FindDeapexerProviderForModule.
1689 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001690 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001691 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1692 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001693 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1694 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001695
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001696 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001697 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001698 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1699 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001700
1701 // Initialize the hiddenapi structure.
1702 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001703 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001704 // This should never happen as a variant for a prebuilt_apex is only created if the
1705 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001706 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001707 }
1708 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001709 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001710 if sdkDep.invalidVersion {
1711 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1712 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1713 } else if sdkDep.useFiles {
1714 // sdkDep.jar is actually equivalent to turbine header.jar.
1715 flags.classpath = append(flags.classpath, sdkDep.jars...)
1716 }
1717
1718 // Dex compilation
1719
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001720 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1721 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001722 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001723 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1724
Paul Duffin612e6102021-02-02 13:38:13 +00001725 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001726 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001727 if ctx.Failed() {
1728 return
1729 }
1730
Paul Duffin74d18d12021-05-14 14:18:47 +01001731 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001732 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001733
1734 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001735 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001736
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001737 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001738 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001739 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001740 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001741
1742 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1743 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1744 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1745 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1746 AidlIncludeDirs: j.exportAidlIncludeDirs,
1747 })
Colin Cross2fe66872015-03-30 17:20:39 -07001748}
1749
Sam Delmerico277795c2022-02-25 17:04:37 +00001750func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
1751 if !Bool(j.properties.Installable) {
1752 return
1753 }
1754
1755 var installDir android.InstallPath
1756 if ctx.InstallInTestcases() {
1757 var archDir string
1758 if !ctx.Host() {
1759 archDir = ctx.DeviceConfig().DeviceArch()
1760 }
1761 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1762 } else {
1763 installDir = android.PathForModuleInstall(ctx, "framework")
1764 }
1765 ctx.InstallFile(installDir, jarName, outputFile)
1766}
1767
Paul Duffinaa55f742020-10-06 17:20:13 +01001768func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1769 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001770 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001771 return android.Paths{j.combinedClasspathFile}, nil
1772 default:
1773 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1774 }
1775}
1776
1777var _ android.OutputFileProducer = (*Import)(nil)
1778
Nan Zhanged19fc32017-10-19 13:06:22 -07001779func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001780 if j.combinedClasspathFile == nil {
1781 return nil
1782 }
Colin Cross37f6d792018-07-12 12:28:41 -07001783 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001784}
1785
Colin Cross331a1212018-08-15 20:40:52 -07001786func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001787 if j.combinedClasspathFile == nil {
1788 return nil
1789 }
Colin Cross331a1212018-08-15 20:40:52 -07001790 return android.Paths{j.combinedClasspathFile}
1791}
1792
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001793func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001794 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001795}
1796
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001797func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001798 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001799}
1800
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001801func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1802 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001803}
1804
Jiyong Park45bf82e2020-12-15 22:29:02 +09001805var _ android.ApexModule = (*Import)(nil)
1806
1807// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001808func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001809 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001810}
1811
Jiyong Park45bf82e2020-12-15 22:29:02 +09001812// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001813func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1814 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001815 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001816 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001817 return fmt.Errorf("min_sdk_version is not specified")
1818 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001819 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001820 return nil
1821 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001822 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1823 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001824 }
Jooyung Han749dc692020-04-15 11:03:39 +09001825 return nil
1826}
1827
Paul Duffinfef55002021-06-17 14:56:05 +01001828// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1829// java_sdk_library_import with the specified base module name requires to be exported from a
1830// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001831func requiredFilesFromPrebuiltApexForImport(name string) []string {
1832 // Add the dex implementation jar to the set of exported files.
1833 return []string{
1834 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001835 }
1836}
1837
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001838// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1839// the java library with the specified name.
1840func apexRootRelativePathToJavaLib(name string) string {
1841 return filepath.Join("javalib", name+".jar")
1842}
1843
Paul Duffinfef55002021-06-17 14:56:05 +01001844var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1845
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001846func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001847 name := j.BaseModuleName()
1848 return requiredFilesFromPrebuiltApexForImport(name)
1849}
1850
albaltai36ff7dc2018-12-25 14:35:23 +08001851// Add compile time check for interface implementation
1852var _ android.IDEInfo = (*Import)(nil)
1853var _ android.IDECustomizedModuleName = (*Import)(nil)
1854
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001855// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001856
1857func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1858 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1859}
1860
1861func (j *Import) IDECustomizedModuleName() string {
1862 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1863 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1864 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001865 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001866}
1867
Colin Cross74d73e22017-08-02 11:05:49 -07001868var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001869
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001870func (j *Import) IsInstallable() bool {
1871 return Bool(j.properties.Installable)
1872}
1873
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001874var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001875
Colin Cross1b16b0e2019-02-12 14:41:32 -08001876// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1877//
1878// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1879// compiled against an Android classpath.
1880//
1881// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1882// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001883func ImportFactory() android.Module {
1884 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001885
Liz Kammerd6c31d22020-08-05 15:40:41 -07001886 module.AddProperties(
1887 &module.properties,
1888 &module.dexer.dexProperties,
1889 )
Colin Cross74d73e22017-08-02 11:05:49 -07001890
Paul Duffin71b33cc2021-06-23 11:39:47 +01001891 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001892
Liz Kammerd6c31d22020-08-05 15:40:41 -07001893 module.dexProperties.Optimize.EnabledByDefault = false
1894
Colin Cross74d73e22017-08-02 11:05:49 -07001895 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001896 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001897 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001898 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001899 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001900 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001901}
1902
Colin Cross1b16b0e2019-02-12 14:41:32 -08001903// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1904// module.
1905//
1906// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1907// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001908func ImportFactoryHost() android.Module {
1909 module := &Import{}
1910
1911 module.AddProperties(&module.properties)
1912
1913 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001914 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001915 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001916 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001917 return module
1918}
1919
Colin Cross42be7612019-02-21 18:12:14 -08001920// dex_import module
1921
1922type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001923 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001924
1925 // set the name of the output
1926 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001927}
1928
1929type DexImport struct {
1930 android.ModuleBase
1931 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001932 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001933 prebuilt android.Prebuilt
1934
1935 properties DexImportProperties
1936
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001937 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001938
1939 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001940
1941 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001942}
1943
1944func (j *DexImport) Prebuilt() *android.Prebuilt {
1945 return &j.prebuilt
1946}
1947
1948func (j *DexImport) PrebuiltSrcs() []string {
1949 return j.properties.Jars
1950}
1951
1952func (j *DexImport) Name() string {
1953 return j.prebuilt.Name(j.ModuleBase.Name())
1954}
1955
Jiyong Park0b238752019-10-29 11:23:10 +09001956func (j *DexImport) Stem() string {
1957 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1958}
1959
Jiyong Park77acec62020-06-01 21:39:15 +09001960func (a *DexImport) JacocoReportClassesFile() android.Path {
1961 return nil
1962}
1963
Colin Cross08dca382020-07-21 20:31:17 -07001964func (a *DexImport) LintDepSets() LintDepSets {
1965 return LintDepSets{}
1966}
1967
Martin Stjernholm6d415272020-01-31 17:10:36 +00001968func (j *DexImport) IsInstallable() bool {
1969 return true
1970}
1971
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001972func (j *DexImport) getStrictUpdatabilityLinting() bool {
1973 return false
1974}
1975
1976func (j *DexImport) setStrictUpdatabilityLinting(bool) {
1977}
1978
Colin Cross42be7612019-02-21 18:12:14 -08001979func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1980 if len(j.properties.Jars) != 1 {
1981 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
1982 }
1983
Colin Cross56a83212020-09-15 18:30:11 -07001984 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1985 if !apexInfo.IsForPlatform() {
1986 j.hideApexVariantFromMake = true
1987 }
1988
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001989 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1990 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08001991 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
1992
1993 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
1994 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
1995
1996 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08001997 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08001998
1999 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2000 rule.Temporary(temporary)
2001
2002 // use zip2zip to uncompress classes*.dex files
2003 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002004 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002005 FlagWithInput("-i ", inputJar).
2006 FlagWithOutput("-o ", temporary).
2007 FlagWithArg("-0 ", "'classes*.dex'")
2008
2009 // use zipalign to align uncompressed classes*.dex files
2010 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002011 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002012 Flag("-f").
2013 Text("4").
2014 Input(temporary).
2015 Output(dexOutputFile)
2016
2017 rule.DeleteTemporaryFiles()
2018
Colin Crossf1a035e2020-11-16 17:32:30 -08002019 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002020 } else {
2021 ctx.Build(pctx, android.BuildParams{
2022 Rule: android.Cp,
2023 Input: inputJar,
2024 Output: dexOutputFile,
2025 })
2026 }
2027
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002028 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002029
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002030 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002031
Colin Cross56a83212020-09-15 18:30:11 -07002032 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002033 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2034 j.Stem()+".jar", dexOutputFile)
2035 }
Colin Cross42be7612019-02-21 18:12:14 -08002036}
2037
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002038func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002039 return j.dexJarFile
2040}
2041
Jiyong Park45bf82e2020-12-15 22:29:02 +09002042var _ android.ApexModule = (*DexImport)(nil)
2043
2044// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002045func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2046 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002047 // we don't check prebuilt modules for sdk_version
2048 return nil
2049}
2050
Colin Cross42be7612019-02-21 18:12:14 -08002051// dex_import imports a `.jar` file containing classes.dex files.
2052//
2053// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2054// to the device.
2055func DexImportFactory() android.Module {
2056 module := &DexImport{}
2057
2058 module.AddProperties(&module.properties)
2059
2060 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002061 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002062 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002063 return module
2064}
2065
Colin Cross89536d42017-07-07 14:35:50 -07002066// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002067type Defaults struct {
2068 android.ModuleBase
2069 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002070 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002071}
2072
Colin Cross1b16b0e2019-02-12 14:41:32 -08002073// java_defaults provides a set of properties that can be inherited by other java or android modules.
2074//
2075// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2076// property in the defaults module that exists in the depending module will be prepended to the depending module's
2077// value for that property.
2078//
2079// Example:
2080//
Sam Delmerico277795c2022-02-25 17:04:37 +00002081// java_defaults {
2082// name: "example_defaults",
2083// srcs: ["common/**/*.java"],
2084// javacflags: ["-Xlint:all"],
2085// aaptflags: ["--auto-add-overlay"],
2086// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002087//
Sam Delmerico277795c2022-02-25 17:04:37 +00002088// java_library {
2089// name: "example",
2090// defaults: ["example_defaults"],
2091// srcs: ["example/**/*.java"],
2092// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002093//
2094// is functionally identical to:
2095//
Sam Delmerico277795c2022-02-25 17:04:37 +00002096// java_library {
2097// name: "example",
2098// srcs: [
2099// "common/**/*.java",
2100// "example/**/*.java",
2101// ],
2102// javacflags: ["-Xlint:all"],
2103// }
Paul Duffin47357662019-12-05 14:07:14 +00002104func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002105 module := &Defaults{}
2106
Colin Cross89536d42017-07-07 14:35:50 -07002107 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002108 &CommonProperties{},
2109 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002110 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002111 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002112 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002113 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002114 &aaptProperties{},
2115 &androidLibraryProperties{},
2116 &appProperties{},
2117 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002118 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002119 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002120 &ImportProperties{},
2121 &AARImportProperties{},
2122 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002123 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002124 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002125 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002126 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002127 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002128 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002129 )
2130
2131 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002132 return module
2133}
Nan Zhangea568a42017-11-08 21:20:04 -08002134
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002135func kytheExtractJavaFactory() android.Singleton {
2136 return &kytheExtractJavaSingleton{}
2137}
2138
2139type kytheExtractJavaSingleton struct {
2140}
2141
2142func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2143 var xrefTargets android.Paths
2144 ctx.VisitAllModules(func(module android.Module) {
2145 if javaModule, ok := module.(xref); ok {
2146 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2147 }
2148 })
2149 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2150 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002151 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002152 }
2153}
2154
Nan Zhangea568a42017-11-08 21:20:04 -08002155var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002156var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002157var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08002158var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002159
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002160// Add class loader context (CLC) of a given dependency to the current CLC.
2161func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2162 clcMap dexpreopt.ClassLoaderContextMap) {
2163
2164 dep, ok := depModule.(UsesLibraryDependency)
2165 if !ok {
2166 return
2167 }
2168
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002169 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2170
2171 var sdkLib *string
2172 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2173 // A shared SDK library. This should be added as a top-level CLC element.
2174 sdkLib = &depName
2175 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2176 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2177 // property. This should be handled in the same way as a shared SDK library.
2178 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002179 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002180
2181 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002182 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002183 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002184 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2185 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002186 } else if depTag == staticLibTag {
2187 // Propagate <uses-library> through static library dependencies, unless it is a component
2188 // library (such as stubs). Component libraries have a dependency on their SDK library,
2189 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002190 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002191 return
2192 }
2193 } else {
2194 // Don't propagate <uses-library> for other dependency tags.
2195 return
2196 }
2197
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002198 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2199 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2200 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2201 // from its CLC should be added to the current CLC.
2202 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002203 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002204 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002205 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002206 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2207 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002208}
Wei Libafb6d62021-12-10 03:14:59 -08002209
Sam Delmerico79985812022-03-23 20:20:42 +00002210type javaResourcesAttributes struct {
2211 Resources bazel.LabelListAttribute
2212 Resource_strip_prefix *string
2213}
2214
2215func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
2216 var resources bazel.LabelList
2217 var resourceStripPrefix *string
2218
2219 if m.properties.Java_resources != nil {
2220 resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
2221 }
2222
2223 //TODO(b/179889880) handle case where glob includes files outside package
2224 resDeps := ResourceDirsToFiles(
2225 ctx,
2226 m.properties.Java_resource_dirs,
2227 m.properties.Exclude_java_resource_dirs,
2228 m.properties.Exclude_java_resources,
2229 )
2230
2231 for i, resDep := range resDeps {
2232 dir, files := resDep.dir, resDep.files
2233
2234 resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
2235
2236 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2237 // inside the JAR file, so we need to remove that prefix
2238 resourceStripPrefix = proptools.StringPtr(dir.String())
2239 if i > 0 {
2240 // TODO(b/226423379) allow multiple resource prefixes
2241 ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
2242 }
2243 }
2244
2245 return &javaResourcesAttributes{
2246 Resources: bazel.MakeLabelListAttribute(resources),
2247 Resource_strip_prefix: resourceStripPrefix,
2248 }
2249}
2250
Sam Delmericoc0161432022-02-25 21:34:51 +00002251type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002252 *javaResourcesAttributes
Wei Libafb6d62021-12-10 03:14:59 -08002253 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002254 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002255 Javacopts bazel.StringListAttribute
2256}
2257
Sam Delmericoc0161432022-02-25 21:34:51 +00002258type javaDependencyLabels struct {
2259 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2260 Deps bazel.LabelListAttribute
2261 // Dependencies which DO contribute to the API visible to upstream dependencies.
2262 StaticDeps bazel.LabelListAttribute
2263}
2264
Sam Delmerico24da73c2022-03-16 20:36:54 +00002265type eventLogTagsAttributes struct {
2266 Srcs bazel.LabelListAttribute
2267}
2268
Sam Delmerico97bd1272022-08-25 14:45:31 -04002269type aidlLibraryAttributes struct {
2270 Srcs bazel.LabelListAttribute
2271}
2272
2273type javaAidlLibraryAttributes struct {
2274 Deps bazel.LabelListAttribute
2275}
2276
2277// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
2278// and also separates dependencies into dynamic dependencies and static dependencies.
2279// Each corresponding Bazel target type, can have a different method for handling
2280// dynamic vs. static dependencies, and so these are returned to the calling function.
Sam Delmericoc0161432022-02-25 21:34:51 +00002281func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002282 var srcs bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002283 var deps bazel.LabelList
2284 var staticDeps bazel.LabelList
2285
Sam Delmericoe91d0302022-02-23 15:28:33 +00002286 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2287 for axis, configToProps := range archVariantProps {
2288 for config, _props := range configToProps {
2289 if archProps, ok := _props.(*CommonProperties); ok {
2290 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2291 srcs.SetSelectValue(axis, config, archSrcs)
2292 }
2293 }
2294 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002295
2296 javaSrcPartition := "java"
2297 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002298 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002299 aidlSrcPartition := "aidl"
Sam Delmericoc7681022022-02-04 21:01:20 +00002300 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002301 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2302 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2303 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04002304 aidlSrcPartition: android.AidlSrcLabelPartition,
Sam Delmericoc7681022022-02-04 21:01:20 +00002305 })
2306
Sam Delmerico24da73c2022-03-16 20:36:54 +00002307 javaSrcs := srcPartitions[javaSrcPartition]
2308
Sam Delmerico24da73c2022-03-16 20:36:54 +00002309 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2310 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002311 ctx.CreateBazelTargetModule(
2312 bazel.BazelTargetModuleProperties{
2313 Rule_class: "event_log_tags",
2314 Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
2315 },
2316 android.CommonAttributes{Name: logtagsLibName},
2317 &eventLogTagsAttributes{
2318 Srcs: srcPartitions[logtagSrcPartition],
2319 },
2320 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04002321
2322 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2323 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00002324 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002325
2326 if !srcPartitions[aidlSrcPartition].IsEmpty() {
2327 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
2328 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
2329 })
2330
2331 if !aidlSrcs.IsEmpty() {
2332 aidlLibName := m.Name() + "_aidl_library"
2333 ctx.CreateBazelTargetModule(
2334 bazel.BazelTargetModuleProperties{
2335 Rule_class: "aidl_library",
2336 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
2337 },
2338 android.CommonAttributes{Name: aidlLibName},
2339 &aidlLibraryAttributes{
2340 Srcs: aidlSrcs,
2341 },
2342 )
2343 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
2344 }
2345
2346 javaAidlLibName := m.Name() + "_java_aidl_library"
2347 ctx.CreateBazelTargetModule(
2348 bazel.BazelTargetModuleProperties{
2349 Rule_class: "java_aidl_library",
2350 Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
2351 },
2352 android.CommonAttributes{Name: javaAidlLibName},
2353 &javaAidlLibraryAttributes{
2354 Deps: aidlLibs,
2355 },
2356 )
2357
2358 staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
2359 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00002360
Sam Delmerico58614c02022-03-15 21:02:09 +00002361 var javacopts []string
2362 if m.properties.Javacflags != nil {
2363 javacopts = append(javacopts, m.properties.Javacflags...)
2364 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002365 if m.properties.Java_version != nil {
2366 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2367 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2368 }
2369
Sam Delmerico58614c02022-03-15 21:02:09 +00002370 epEnabled := m.properties.Errorprone.Enabled
2371 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
2372 if Bool(epEnabled) {
2373 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2374 }
2375
Sam Delmericoc0161432022-02-25 21:34:51 +00002376 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00002377 Srcs: javaSrcs,
2378 javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
Sam Delmerico77267c72022-03-18 14:11:07 +00002379 Plugins: bazel.MakeLabelListAttribute(
2380 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2381 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002382 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002383 }
2384
2385 if m.properties.Libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002386 deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
Wei Libafb6d62021-12-10 03:14:59 -08002387 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002388
Sam Delmericofde9fb52022-01-28 20:53:38 +00002389 if m.properties.Static_libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002390 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002391 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002392
Sam Delmericoc0161432022-02-25 21:34:51 +00002393 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2394 // Soong does not differentiate between a java_library and the Bazel equivalent of
2395 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2396 // listed directly in the srcs of a java_library, and the classes produced
2397 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2398 // that depend on a java_library with proto sources can link directly to the protobuf API,
2399 // and so this should be a static dependency.
2400 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002401
Sam Delmerico97bd1272022-08-25 14:45:31 -04002402 depLabels := &javaDependencyLabels{}
Sam Delmericoc0161432022-02-25 21:34:51 +00002403 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2404 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002405
Sam Delmericoc0161432022-02-25 21:34:51 +00002406 return commonAttrs, depLabels
2407}
2408
2409type javaLibraryAttributes struct {
2410 *javaCommonAttributes
2411 Deps bazel.LabelListAttribute
2412 Exports bazel.LabelListAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002413}
2414
2415func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002416 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2417
2418 deps := depLabels.Deps
2419 if !commonAttrs.Srcs.IsEmpty() {
2420 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2421
2422 sdkVersion := m.SdkVersion(ctx)
2423 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2424 // TODO(b/220869005) remove forced dependency on current public android.jar
2425 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2426 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002427 } else if !deps.IsEmpty() {
Sam Delmericoc0161432022-02-25 21:34:51 +00002428 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2429 }
2430
2431 attrs := &javaLibraryAttributes{
2432 javaCommonAttributes: commonAttrs,
2433 Deps: deps,
2434 Exports: depLabels.StaticDeps,
2435 }
Wei Libafb6d62021-12-10 03:14:59 -08002436
2437 props := bazel.BazelTargetModuleProperties{
2438 Rule_class: "java_library",
2439 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2440 }
2441
2442 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2443}
2444
2445type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002446 *javaCommonAttributes
2447 Deps bazel.LabelListAttribute
2448 Runtime_deps bazel.LabelListAttribute
2449 Main_class string
2450 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002451}
2452
2453// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2454func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002455 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2456
2457 deps := depLabels.Deps
2458 deps.Append(depLabels.StaticDeps)
2459 if m.binaryProperties.Jni_libs != nil {
2460 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2461 }
2462
2463 var runtimeDeps bazel.LabelListAttribute
2464 if commonAttrs.Srcs.IsEmpty() {
2465 // if there are no sources, then the dependencies can only be used at runtime
2466 runtimeDeps = deps
2467 deps = bazel.LabelListAttribute{}
2468 }
2469
Wei Libafb6d62021-12-10 03:14:59 -08002470 mainClass := ""
2471 if m.binaryProperties.Main_class != nil {
2472 mainClass = *m.binaryProperties.Main_class
2473 }
2474 if m.properties.Manifest != nil {
2475 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2476 if err != nil {
2477 return
2478 }
2479 mainClass = mainClassInManifest
2480 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002481
Wei Libafb6d62021-12-10 03:14:59 -08002482 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002483 javaCommonAttributes: commonAttrs,
2484 Deps: deps,
2485 Runtime_deps: runtimeDeps,
2486 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002487 }
2488
2489 // Attribute jvm_flags
2490 if m.binaryProperties.Jni_libs != nil {
2491 jniLibPackages := map[string]bool{}
2492 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2493 jniLibPackage := jniLibLabel.Label
2494 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2495 if indexOfColon > 0 {
2496 // JNI lib from other package
2497 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2498 } else if indexOfColon == 0 {
2499 // JNI lib in the same package of java_binary
2500 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2501 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2502 }
2503 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2504 jniLibPackages[jniLibPackage] = true
2505 }
2506 }
2507 jniLibPaths := []string{}
2508 for jniLibPackage, _ := range jniLibPackages {
2509 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2510 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2511 }
2512 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2513 }
2514
2515 props := bazel.BazelTargetModuleProperties{
2516 Rule_class: "java_binary",
2517 }
2518
2519 // Create the BazelTargetModule.
2520 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2521}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002522
2523type bazelJavaImportAttributes struct {
2524 Jars bazel.LabelListAttribute
2525}
2526
2527// java_import bp2Build converter.
2528func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002529 var jars bazel.LabelListAttribute
2530 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2531 for axis, configToProps := range archVariantProps {
2532 for config, _props := range configToProps {
2533 if archProps, ok := _props.(*ImportProperties); ok {
2534 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2535 jars.SetSelectValue(axis, config, archJars)
2536 }
2537 }
2538 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002539
2540 attrs := &bazelJavaImportAttributes{
2541 Jars: jars,
2542 }
2543 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2544
2545 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
Sam Delmerico277795c2022-02-25 17:04:37 +00002546}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002547
Sam Delmerico277795c2022-02-25 17:04:37 +00002548var _ android.MixedBuildBuildable = (*Import)(nil)
2549
2550func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
2551 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
2552}
2553
2554func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
2555 i.commonBuildActions(ctx)
2556
2557 bazelCtx := ctx.Config().BazelContext
2558 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
2559 if err != nil {
2560 ctx.ModuleErrorf(err.Error())
2561 return
2562 }
2563
2564 bazelJars := android.Paths{}
2565 for _, bazelOutputFile := range filePaths {
2566 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
2567 }
2568
2569 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
2570 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
2571 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
2572 android.OptionalPath{}, // manifest
2573 false, // stripDirEntries
2574 []string{}, // filesToStrip
2575 []string{}, // dirsToStrip
2576 )
2577 i.combinedClasspathFile = outputFile
2578
2579 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2580 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
2581 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
2582 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
2583 //TODO(b/240308299) include AIDL information from Bazel
2584 })
2585
2586 i.maybeInstall(ctx, jarName, outputFile)
2587}
2588
2589func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
2590 bazelCtx := ctx.Config().BazelContext
2591 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
2592}
2593
2594func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
2595 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002596}