blob: 9dca4ef2f8a447f52baa65ebd8ecf1ef92d41895 [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 }
Zi Wangca65b402022-10-10 13:45:06 -0700214
215 // Rule for generating device binary default wrapper
216 deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
217 Command: `echo -e '#!/system/bin/sh\n` +
218 `export CLASSPATH=/system/framework/$jar_name\n` +
219 `exec app_process /$partition/bin $main_class "$$@"'> ${out}`,
220 Description: "Generating device binary wrapper ${jar_name}",
221 }, "jar_name", "partition", "main_class")
Paul Duffin2da04242021-04-23 19:43:28 +0100222)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900223
Colin Crossdcf71b22021-02-01 13:59:03 -0800224// JavaInfo contains information about a java module for use by modules that depend on it.
225type JavaInfo struct {
226 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
227 // against this module. If empty, ImplementationJars should be used instead.
228 HeaderJars android.Paths
229
230 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
231 // in the module as well as any resources included in the module.
232 ImplementationAndResourcesJars android.Paths
233
234 // ImplementationJars is a list of jars that contain the implementations of classes in the
235 //module.
236 ImplementationJars android.Paths
237
238 // ResourceJars is a list of jars that contain the resources included in the module.
239 ResourceJars android.Paths
240
241 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
242 // depending on this module.
243 AidlIncludeDirs android.Paths
244
245 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
246 // module.
247 SrcJarArgs []string
248
249 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
250 SrcJarDeps android.Paths
251
252 // ExportedPlugins is a list of paths that should be used as annotation processors for any
253 // module that depends on this module.
254 ExportedPlugins android.Paths
255
256 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
257 // any module that depends on this module.
258 ExportedPluginClasses []string
259
260 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
261 // requiring disbling turbine for any modules that depend on it.
262 ExportedPluginDisableTurbine bool
263
264 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
265 // instrumented by jacoco.
266 JacocoReportClassesFile android.Path
267}
268
269var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
270
Colin Cross75ce9ec2021-02-26 16:20:32 -0800271// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
272// the sysprop implementation library.
273type SyspropPublicStubInfo struct {
274 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
275 // the sysprop implementation library.
276 JavaInfo JavaInfo
277}
278
279var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
280
Paul Duffin44b481b2020-06-17 16:59:43 +0100281// Methods that need to be implemented for a module that is added to apex java_libs property.
282type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700283 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100284 ImplementationAndResourcesJars() android.Paths
285}
286
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100287// Provides build path and install path to DEX jars.
288type UsesLibraryDependency interface {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100289 DexJarBuildPath() OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100290 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000291 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100292}
293
Jaewoong Jung26342642021-03-17 15:56:23 -0700294// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800295type xref interface {
296 XrefJavaFiles() android.Paths
297}
298
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800299func (j *Module) XrefJavaFiles() android.Paths {
300 return j.kytheFiles
301}
302
Colin Crossbe1da472017-07-07 15:59:46 -0700303type dependencyTag struct {
304 blueprint.BaseDependencyTag
305 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000306
307 // True if the dependency is relinked at runtime.
308 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800309
310 // True if the dependency is a toolchain, for example an annotation processor.
311 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700312}
313
Colin Crosse9fe2942020-11-10 18:12:15 -0800314// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
315// dependency to be installed when the parent module is installed.
316type installDependencyTag struct {
317 blueprint.BaseDependencyTag
318 android.InstallAlwaysNeededDependencyTag
319 name string
320}
321
Colin Cross65cb3142021-12-10 23:05:02 +0000322func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
323 if d.runtimeLinked {
324 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800325 } else if d.toolchain {
326 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000327 }
328 return nil
329}
330
331var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
332
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100333type usesLibraryDependencyTag struct {
334 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100335 sdkVersion int // SDK version in which the library appared as a standalone library.
336 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100337}
338
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100339func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100340 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000341 dependencyTag: dependencyTag{
342 name: fmt.Sprintf("uses-library-%d", sdkVersion),
343 runtimeLinked: true,
344 },
345 sdkVersion: sdkVersion,
346 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100347 }
348}
349
Jiyong Park8be103b2019-11-08 15:53:48 +0900350func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700351 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900352}
353
Colin Crossbe1da472017-07-07 15:59:46 -0700354var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800355 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000356 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800357 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000358 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400359 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000360 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800361 pluginTag = dependencyTag{name: "plugin", toolchain: true}
362 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
363 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000364 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
365 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800366 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000367 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
368 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800369 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800370 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
371 certificateTag = dependencyTag{name: "certificate"}
372 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800373 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000374 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800375 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
376 jniInstallTag = installDependencyTag{name: "jni install"}
377 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100378 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
379 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
380 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
381 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
382 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700383)
Colin Cross2fe66872015-03-30 17:20:39 -0700384
Jiyong Park83dc74b2020-01-14 18:38:44 +0900385func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400386 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900387}
388
389func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
390 return depTag == staticLibTag
391}
392
Colin Crossfc3674a2017-09-18 17:41:52 -0700393type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100394 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700395
Colin Cross6cef4812019-10-17 14:23:50 -0700396 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
397 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100398
399 // The default system modules to use. Will be an empty string if no system
400 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700401 systemModules string
402
Pete Gilline3d44b22020-06-29 11:28:51 +0100403 // The modules that will be added to the classpath regardless of the Java language level targeted
404 classpath []string
405
Colin Cross6cef4812019-10-17 14:23:50 -0700406 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100407 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700408 java9Classpath []string
409
Colin Crossa97c5d32018-03-28 14:58:31 -0700410 frameworkResModule string
411
Colin Cross86a60ae2018-05-29 14:44:55 -0700412 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700413 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100414
415 noStandardLibs, noFrameworksLibs bool
416}
417
418func (s sdkDep) hasStandardLibs() bool {
419 return !s.noStandardLibs
420}
421
422func (s sdkDep) hasFrameworkLibs() bool {
423 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700424}
425
Colin Crossa4f08812018-10-02 22:03:40 -0700426type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700427 name string
428 path android.Path
429 target android.Target
430 coverageFile android.OptionalPath
431 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000432 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700433}
434
Jiyong Parkf1691d22021-03-29 20:11:58 +0900435func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700436 sdkDep := decodeSdkDep(ctx, sdkContext)
437 if sdkDep.useModule {
438 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
439 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400440 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700441 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
442 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
443 }
444 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
445 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
446 }
447 }
448 if sdkDep.systemModules != "" {
449 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
450 }
451}
452
Colin Cross32f676a2017-09-06 13:41:06 -0700453type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700454 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
455 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
456 // systemModules and java9Classpath instead.
457 bootClasspath classpath
458
459 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
460 // contains header jars for all static and non-static dependencies.
461 classpath classpath
462
463 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
464 // header jars for all non-static dependencies. Static dependencies have already been
465 // combined into the program jar.
466 dexClasspath classpath
467
468 // java9Classpath is the list of jars that will be added to the classpath when targeting
469 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
470 // are provided by systemModules.
471 java9Classpath classpath
472
Colin Cross748b2d82020-11-19 13:52:06 -0800473 processorPath classpath
474 errorProneProcessorPath classpath
475 processorClasses []string
476 staticJars android.Paths
477 staticHeaderJars android.Paths
478 staticResourceJars android.Paths
479 aidlIncludeDirs android.Paths
480 srcs android.Paths
481 srcJars android.Paths
482 systemModules *systemModules
483 aidlPreprocess android.OptionalPath
484 kotlinStdlib android.Paths
485 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700486 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800487
488 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700489}
Colin Cross2fe66872015-03-30 17:20:39 -0700490
Colin Cross54250902017-12-05 09:28:08 -0800491func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
492 for _, f := range dep.Srcs() {
493 if f.Ext() != ".jar" {
494 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
495 ctx.OtherModuleName(dep.(blueprint.Module)))
496 }
497 }
498}
499
Jiyong Parkf1691d22021-03-29 20:11:58 +0900500func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700501 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700502 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700503 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900504 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Bascace720c32022-05-24 12:13:50 +0100505 } else if ctx.Config().TargetsJava17() {
506 // Temporary experimental flag to be able to try and build with
507 // java version 17 options. The flag, if used, just sets Java
508 // 17 as the default version, leaving any components that
509 // target an older version intact.
510 return JAVA_VERSION_17
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000511 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000512 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700513 }
Nan Zhang357466b2018-04-17 17:38:36 -0700514}
515
Colin Cross1e743852019-10-28 11:37:20 -0700516type javaVersion int
517
518const (
519 JAVA_VERSION_UNSUPPORTED = 0
520 JAVA_VERSION_6 = 6
521 JAVA_VERSION_7 = 7
522 JAVA_VERSION_8 = 8
523 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000524 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100525 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700526)
527
528func (v javaVersion) String() string {
529 switch v {
530 case JAVA_VERSION_6:
531 return "1.6"
532 case JAVA_VERSION_7:
533 return "1.7"
534 case JAVA_VERSION_8:
535 return "1.8"
536 case JAVA_VERSION_9:
537 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000538 case JAVA_VERSION_11:
539 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100540 case JAVA_VERSION_17:
541 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700542 default:
543 return "unsupported"
544 }
545}
546
Cole Faustd96eebf2022-06-28 14:41:27 -0700547func (v javaVersion) StringForKotlinc() string {
548 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
549 // error: unknown JVM target version: foo
550 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
551 switch v {
552 case JAVA_VERSION_7:
553 return "1.6"
554 case JAVA_VERSION_9:
555 return "9"
556 default:
557 return v.String()
558 }
559}
560
Colin Cross1e743852019-10-28 11:37:20 -0700561// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
562func (v javaVersion) usesJavaModules() bool {
563 return v >= 9
564}
565
566func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100567 switch javaVersion {
568 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700569 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100570 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700571 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100572 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700573 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100574 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700575 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000576 case "11":
577 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100578 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100579 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100580 case "10", "12", "13", "14", "15", "16":
581 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700582 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100583 default:
584 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700585 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100586 }
587}
588
Colin Cross2fe66872015-03-30 17:20:39 -0700589//
590// Java libraries (.jar file)
591//
592
Colin Crossf506d872017-07-19 15:53:04 -0700593type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700594 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700595
596 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700597}
598
Jiyong Park45bf82e2020-12-15 22:29:02 +0900599var _ android.ApexModule = (*Library)(nil)
600
satayevd604b212021-07-21 14:23:52 +0100601// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100602type PermittedPackagesForUpdatableBootJars interface {
603 PermittedPackagesForUpdatableBootJars() []string
604}
605
606var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
607
608func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
609 return j.properties.Permitted_packages
610}
611
Colin Cross42be7612019-02-21 18:12:14 -0800612func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000613 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700614 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000615 return true
616 }
617
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000618 // Store uncompressed (and do not strip) dex files from boot class path jars.
619 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
620 return true
621 }
622
623 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000624 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000625 return true
626 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800627 if ctx.Config().UncompressPrivAppDex() &&
628 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
629 return true
630 }
631
Colin Cross2fc72f62018-12-21 12:59:54 -0800632 return false
633}
634
Jiakai Zhang22450f22021-10-11 03:05:20 +0000635// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
636func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
637 if dexer.dexProperties.Uncompress_dex == nil {
638 // If the value was not force-set by the user, use reasonable default based on the module.
639 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
640 }
641}
642
Colin Crossf506d872017-07-19 15:53:04 -0700643func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000644
645 j.provideHiddenAPIPropertyInfo(ctx)
646
Jiyong Park92315372021-04-02 08:45:46 +0900647 j.sdkVersion = j.SdkVersion(ctx)
648 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000649 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900650
Colin Cross56a83212020-09-15 18:30:11 -0700651 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
652 if !apexInfo.IsForPlatform() {
653 j.hideApexVariantFromMake = true
654 }
655
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100656 j.checkSdkVersions(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800657 if ctx.Device() {
658 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
659 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
660 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
661 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
662 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
663 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
664 }
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700665 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700666
bralee1fbf4402020-05-21 10:11:59 +0800667 // Collect the module directory for IDE info in java/jdeps.go.
668 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
669
Colin Cross56a83212020-09-15 18:30:11 -0700670 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900671 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700672 var extraInstallDeps android.Paths
673 if j.InstallMixin != nil {
674 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
675 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700676 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
677 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800678 j.hostdexInstallFile = ctx.InstallFile(
679 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700680 j.Stem()+"-hostdex.jar", j.outputFile)
681 }
682 var installDir android.InstallPath
683 if ctx.InstallInTestcases() {
684 var archDir string
685 if !ctx.Host() {
686 archDir = ctx.DeviceConfig().DeviceArch()
687 }
688 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
689 } else {
690 installDir = android.PathForModuleInstall(ctx, "framework")
691 }
692 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700693 }
Colin Crossb7a63242015-04-16 14:09:14 -0700694}
695
Colin Crossf506d872017-07-19 15:53:04 -0700696func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700697 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100698 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700699}
700
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000701const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000702 aidlIncludeDir = "aidl"
703 javaDir = "java"
704 jarFileSuffix = ".jar"
705 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000706)
707
Paul Duffina0dbf432019-12-05 11:25:53 +0000708// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000709func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000710 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000711}
712
Paul Duffina04c1072020-03-02 10:16:35 +0000713func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
714 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000715}
716
Paul Duffin13879572019-11-28 14:31:38 +0000717type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000718 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000719
720 // Function to retrieve the appropriate output jar (implementation or header) from
721 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000722 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
723
724 // Function to compute the snapshot relative path to which the named library's
725 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000726 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000727
728 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
729 // files like aidl files should also be copied.
730 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000731}
732
Paul Duffindb170e42020-12-08 17:48:25 +0000733const (
734 onlyCopyJarToSnapshot = true
735 copyEverythingToSnapshot = false
736)
737
Paul Duffin296701e2021-07-14 10:29:36 +0100738func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
739 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000740}
741
742func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
743 _, ok := module.(*Library)
744 return ok
745}
746
Paul Duffin3a4eb502020-03-19 16:11:18 +0000747func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
748 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000749}
Paul Duffina0dbf432019-12-05 11:25:53 +0000750
Paul Duffin14eb4672020-03-02 11:33:02 +0000751func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000752 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000753}
754
755type librarySdkMemberProperties struct {
756 android.SdkMemberPropertiesBase
757
Paul Duffin864e1b42020-05-06 10:23:19 +0100758 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000759 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100760
761 // The list of permitted packages that need to be passed to the prebuilts as they are used to
762 // create the updatable-bcp-packages.txt file.
763 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000764}
765
Paul Duffin3a4eb502020-03-19 16:11:18 +0000766func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000767 j := variant.(*Library)
768
Paul Duffindb170e42020-12-08 17:48:25 +0000769 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
770
Paul Duffina551a1c2020-03-17 21:04:24 +0000771 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100772
773 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000774}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000775
Paul Duffin3a4eb502020-03-19 16:11:18 +0000776func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000777 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000778
Paul Duffindb170e42020-12-08 17:48:25 +0000779 memberType := ctx.MemberType().(*librarySdkMemberType)
780
Paul Duffina551a1c2020-03-17 21:04:24 +0000781 exportedJar := p.JarToExport
782 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000783 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000784 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000785
786 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000787 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
788
Paul Duffina551a1c2020-03-17 21:04:24 +0000789 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
790 }
791
Paul Duffin869de142021-07-15 14:14:41 +0100792 if len(p.PermittedPackages) > 0 {
793 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
794 }
795
Paul Duffindb170e42020-12-08 17:48:25 +0000796 // Do not copy anything else to the snapshot.
797 if memberType.onlyCopyJarToSnapshot {
798 return
799 }
800
Paul Duffina551a1c2020-03-17 21:04:24 +0000801 aidlIncludeDirs := p.AidlIncludeDirs
802 if len(aidlIncludeDirs) != 0 {
803 sdkModuleContext := ctx.SdkModuleContext()
804 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000805 // TODO(jiyong): copy parcelable declarations only
806 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
807 for _, file := range aidlFiles {
808 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
809 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000810 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000811
Paul Duffina551a1c2020-03-17 21:04:24 +0000812 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000813 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000814}
815
Colin Cross1b16b0e2019-02-12 14:41:32 -0800816// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
817//
818// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
819// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
820// as a `static_libs` dependency of another module.
821//
822// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
823// a device.
824//
825// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
826// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700827func LibraryFactory() android.Module {
828 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700829
Colin Crossce6734e2020-06-15 16:09:53 -0700830 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700831
Paul Duffin71b33cc2021-06-23 11:39:47 +0100832 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100833
Jiyong Park7f7766d2019-07-25 22:02:35 +0900834 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900835 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800836 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900837 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700838 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700839}
840
Colin Cross1b16b0e2019-02-12 14:41:32 -0800841// java_library_static is an obsolete alias for java_library.
842func LibraryStaticFactory() android.Module {
843 return LibraryFactory()
844}
845
846// java_library_host builds and links sources into a `.jar` file for the host.
847//
848// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
849// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700850func LibraryHostFactory() android.Module {
851 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700852
Colin Crossce6734e2020-06-15 16:09:53 -0700853 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700854
Colin Cross9ae1b922018-06-26 17:59:05 -0700855 module.Module.properties.Installable = proptools.BoolPtr(true)
856
Jiyong Park7f7766d2019-07-25 22:02:35 +0900857 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100858 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800859 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900860 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700861 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700862}
863
864//
Colin Crossb628ea52018-08-14 16:42:33 -0700865// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700866//
867
Dan Shi95d19422020-08-15 12:24:26 -0700868// Test option struct.
869type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800870 android.CommonTestOptions
871
Dan Shi95d19422020-08-15 12:24:26 -0700872 // a list of extra test configuration files that should be installed with the module.
873 Extra_test_configs []string `android:"path,arch_variant"`
874}
875
Colin Cross05638fc2018-04-09 18:40:24 -0700876type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700877 // list of compatibility suites (for example "cts", "vts") that the module should be
878 // installed into.
879 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700880
881 // the name of the test configuration (for example "AndroidTest.xml") that should be
882 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800883 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700884
Jack He33338892018-09-19 02:21:28 -0700885 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
886 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800887 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700888
Colin Crossd96ca352018-08-10 16:06:24 -0700889 // list of files or filegroup modules that provide data that should be installed alongside
890 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900891 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700892
893 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
894 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
895 // explicitly.
896 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800897
898 // Add parameterized mainline modules to auto generated test config. The options will be
899 // handled by TradeFed to do downloading and installing the specified modules on the device.
900 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700901
902 // Test options.
903 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800904
905 // Names of modules containing JNI libraries that should be installed alongside the test.
906 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700907
908 // Install the test into a folder named for the module in all test suites.
909 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700910}
911
Liz Kammerdd849a82020-06-12 16:38:45 -0700912type hostTestProperties struct {
913 // list of native binary modules that should be installed alongside the test
914 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000915
916 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000917 // This property only adds the first variant of the dependency
918 Data_device_bins_first []string `android:"arch_variant"`
919
920 // list of device binary modules that should be installed alongside the test
921 // This property adds 64bit AND 32bit variants of the dependency
922 Data_device_bins_both []string `android:"arch_variant"`
923
924 // list of device binary modules that should be installed alongside the test
925 // This property only adds 64bit variants of the dependency
926 Data_device_bins_64 []string `android:"arch_variant"`
927
928 // list of device binary modules that should be installed alongside the test
929 // This property adds 32bit variants of the dependency if available, or else
930 // defaults to the 64bit variant
931 Data_device_bins_prefer32 []string `android:"arch_variant"`
932
933 // list of device binary modules that should be installed alongside the test
934 // This property only adds 32bit variants of the dependency
935 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700936}
937
Paul Duffin42df1442019-03-20 12:45:53 +0000938type testHelperLibraryProperties 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"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700942
943 // Install the test into a folder named for the module in all test suites.
944 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000945}
946
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000947type prebuiltTestProperties struct {
948 // list of compatibility suites (for example "cts", "vts") that the module should be
949 // installed into.
950 Test_suites []string `android:"arch_variant"`
951
952 // the name of the test configuration (for example "AndroidTest.xml") that should be
953 // installed with the module.
954 Test_config *string `android:"path,arch_variant"`
955}
956
Colin Cross05638fc2018-04-09 18:40:24 -0700957type Test struct {
958 Library
959
960 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700961
Dan Shi95d19422020-08-15 12:24:26 -0700962 testConfig android.Path
963 extraTestConfigs android.Paths
964 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700965}
966
Liz Kammerdd849a82020-06-12 16:38:45 -0700967type TestHost struct {
968 Test
969
970 testHostProperties hostTestProperties
971}
972
Paul Duffin42df1442019-03-20 12:45:53 +0000973type TestHelperLibrary struct {
974 Library
975
976 testHelperLibraryProperties testHelperLibraryProperties
977}
978
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000979type JavaTestImport struct {
980 Import
981
982 prebuiltTestProperties prebuiltTestProperties
983
984 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700985 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000986}
987
Colin Cross24cc4be62021-11-03 14:09:41 -0700988func (j *Test) InstallInTestcases() bool {
989 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
990 // testcases by base_rules.mk.
991 return !j.Host()
992}
993
994func (j *TestHelperLibrary) InstallInTestcases() bool {
995 return true
996}
997
998func (j *JavaTestImport) InstallInTestcases() bool {
999 return true
1000}
1001
Sam Delmericocc271e22022-06-01 15:45:02 +00001002func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1003 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1004 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1005 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1006 }
1007
1008 var maybeAndroid32Target *android.Target
1009 var maybeAndroid64Target *android.Target
1010 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1011 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1012 if len(android32TargetList) > 0 {
1013 maybeAndroid32Target = &android32TargetList[0]
1014 }
1015 if len(android64TargetList) > 0 {
1016 maybeAndroid64Target = &android64TargetList[0]
1017 }
1018
1019 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1020 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1021 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1022 return
1023 }
1024 if maybeAndroid32Target != nil {
1025 ctx.AddFarVariationDependencies(
1026 maybeAndroid32Target.Variations(),
1027 dataDeviceBinsTag,
1028 j.testHostProperties.Data_device_bins_both...,
1029 )
1030 }
1031 if maybeAndroid64Target != nil {
1032 ctx.AddFarVariationDependencies(
1033 maybeAndroid64Target.Variations(),
1034 dataDeviceBinsTag,
1035 j.testHostProperties.Data_device_bins_both...,
1036 )
1037 }
1038 }
1039
1040 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1041 if maybeAndroid32Target != nil {
1042 ctx.AddFarVariationDependencies(
1043 maybeAndroid32Target.Variations(),
1044 dataDeviceBinsTag,
1045 j.testHostProperties.Data_device_bins_prefer32...,
1046 )
1047 } else {
1048 if maybeAndroid64Target == nil {
1049 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1050 return
1051 }
1052 ctx.AddFarVariationDependencies(
1053 maybeAndroid64Target.Variations(),
1054 dataDeviceBinsTag,
1055 j.testHostProperties.Data_device_bins_prefer32...,
1056 )
1057 }
1058 }
1059
1060 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1061 if maybeAndroid32Target == nil {
1062 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1063 return
1064 }
1065 deviceVariations := maybeAndroid32Target.Variations()
1066 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1067 }
1068
1069 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1070 if maybeAndroid64Target == nil {
1071 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1072 return
1073 }
1074 deviceVariations := maybeAndroid64Target.Variations()
1075 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1076 }
1077}
1078
Liz Kammerdd849a82020-06-12 16:38:45 -07001079func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1080 if len(j.testHostProperties.Data_native_bins) > 0 {
1081 for _, target := range ctx.MultiTargets() {
1082 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1083 }
1084 }
1085
Colin Crossf8d9c492021-01-26 11:01:43 -08001086 if len(j.testProperties.Jni_libs) > 0 {
1087 for _, target := range ctx.MultiTargets() {
1088 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1089 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1090 }
1091 }
1092
Sam Delmericocc271e22022-06-01 15:45:02 +00001093 j.addDataDeviceBinsDeps(ctx)
1094
Liz Kammerdd849a82020-06-12 16:38:45 -07001095 j.deps(ctx)
1096}
1097
Yuexi Ma627263f2021-03-04 13:47:56 -08001098func (j *TestHost) AddExtraResource(p android.Path) {
1099 j.extraResources = append(j.extraResources, p)
1100}
1101
Sam Delmericocc271e22022-06-01 15:45:02 +00001102func (j *TestHost) dataDeviceBins() []string {
1103 ret := make([]string, 0,
1104 len(j.testHostProperties.Data_device_bins_first)+
1105 len(j.testHostProperties.Data_device_bins_both)+
1106 len(j.testHostProperties.Data_device_bins_prefer32)+
1107 len(j.testHostProperties.Data_device_bins_32)+
1108 len(j.testHostProperties.Data_device_bins_64),
1109 )
1110
1111 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1112 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1113 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1114 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1115 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1116
1117 return ret
1118}
1119
Sam Delmericob3342ce2022-01-20 21:10:28 +00001120func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1121 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001122 dataDeviceBins := j.dataDeviceBins()
1123 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001124 // add Tradefed configuration to push device bins to device for testing
1125 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1126 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001127 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001128 fullPath := filepath.Join(remoteDir, bin)
1129 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1130 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001131 configs = append(configs, tradefed.Object{
1132 Type: "target_preparer",
1133 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1134 Options: options,
1135 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001136 }
1137
1138 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
1139}
1140
Colin Cross303e21f2018-08-07 16:49:25 -07001141func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001142 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1143}
1144
1145func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001146 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1147 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001148 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001149 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1150 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001151
Dan Shi6ffaaa82019-09-26 11:41:36 -07001152 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001153 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -07001154
Colin Cross8a497952019-03-05 22:25:09 -08001155 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001156
Dan Shi95d19422020-08-15 12:24:26 -07001157 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1158
Liz Kammerdd849a82020-06-12 16:38:45 -07001159 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1160 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1161 })
1162
Sam Delmericob3342ce2022-01-20 21:10:28 +00001163 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1164 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1165 })
1166
Colin Crossf8d9c492021-01-26 11:01:43 -08001167 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1168 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1169 if sharedLibInfo.SharedLibrary != nil {
1170 // Copy to an intermediate output directory to append "lib[64]" to the path,
1171 // so that it's compatible with the default rpath values.
1172 var relPath string
1173 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1174 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1175 } else {
1176 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1177 }
1178 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1179 ctx.Build(pctx, android.BuildParams{
1180 Rule: android.Cp,
1181 Input: sharedLibInfo.SharedLibrary,
1182 Output: relocatedLib,
1183 })
1184 j.data = append(j.data, relocatedLib)
1185 } else {
1186 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1187 }
1188 })
1189
Colin Cross303e21f2018-08-07 16:49:25 -07001190 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001191}
1192
Paul Duffin42df1442019-03-20 12:45:53 +00001193func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1194 j.Library.GenerateAndroidBuildActions(ctx)
1195}
1196
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001197func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1198 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001199 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001200
1201 j.Import.GenerateAndroidBuildActions(ctx)
1202}
1203
1204type testSdkMemberType struct {
1205 android.SdkMemberTypeBase
1206}
1207
Paul Duffin296701e2021-07-14 10:29:36 +01001208func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1209 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001210}
1211
1212func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1213 _, ok := module.(*Test)
1214 return ok
1215}
1216
Paul Duffin3a4eb502020-03-19 16:11:18 +00001217func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1218 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001219}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001220
Paul Duffin14eb4672020-03-02 11:33:02 +00001221func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1222 return &testSdkMemberProperties{}
1223}
1224
1225type testSdkMemberProperties struct {
1226 android.SdkMemberPropertiesBase
1227
Paul Duffina551a1c2020-03-17 21:04:24 +00001228 JarToExport android.Path
1229 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001230}
1231
Paul Duffin3a4eb502020-03-19 16:11:18 +00001232func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001233 test := variant.(*Test)
1234
1235 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001236 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001237 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001238 }
1239
Paul Duffina551a1c2020-03-17 21:04:24 +00001240 p.JarToExport = implementationJars[0]
1241 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001242}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001243
Paul Duffin3a4eb502020-03-19 16:11:18 +00001244func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001245 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001246
Paul Duffina551a1c2020-03-17 21:04:24 +00001247 exportedJar := p.JarToExport
1248 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001249 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001250 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001251
1252 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001253 }
1254
1255 testConfig := p.TestConfig
1256 if testConfig != nil {
1257 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1258 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001259 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1260 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001261}
1262
Colin Cross1b16b0e2019-02-12 14:41:32 -08001263// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1264// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1265//
1266// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1267// compiled against the device bootclasspath.
1268//
1269// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1270// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001271func TestFactory() android.Module {
1272 module := &Test{}
1273
Colin Crossce6734e2020-06-15 16:09:53 -07001274 module.addHostAndDeviceProperties()
1275 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001276
Colin Cross9ae1b922018-06-26 17:59:05 -07001277 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001278 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001279 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001280
Paul Duffinb6b89a42021-05-06 16:33:43 +01001281 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001282 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001283 return module
1284}
1285
Paul Duffin42df1442019-03-20 12:45:53 +00001286// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1287func TestHelperLibraryFactory() android.Module {
1288 module := &TestHelperLibrary{}
1289
Colin Crossce6734e2020-06-15 16:09:53 -07001290 module.addHostAndDeviceProperties()
1291 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001292
Colin Cross9a4abed2019-04-24 13:19:28 -07001293 module.Module.properties.Installable = proptools.BoolPtr(true)
1294 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001295 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001296
Paul Duffin42df1442019-03-20 12:45:53 +00001297 InitJavaModule(module, android.HostAndDeviceSupported)
1298 return module
1299}
1300
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001301// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1302// and makes sure that it is added to the appropriate test suite.
1303//
1304// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1305// compiled against an Android classpath.
1306//
1307// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1308// for host modules.
1309func JavaTestImportFactory() android.Module {
1310 module := &JavaTestImport{}
1311
1312 module.AddProperties(
1313 &module.Import.properties,
1314 &module.prebuiltTestProperties)
1315
1316 module.Import.properties.Installable = proptools.BoolPtr(true)
1317
1318 android.InitPrebuiltModule(module, &module.properties.Jars)
1319 android.InitApexModule(module)
1320 android.InitSdkAwareModule(module)
1321 InitJavaModule(module, android.HostAndDeviceSupported)
1322 return module
1323}
1324
Colin Cross1b16b0e2019-02-12 14:41:32 -08001325// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1326// allow running the test with `atest` or a `TEST_MAPPING` file.
1327//
1328// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1329// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001330func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001331 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001332
Colin Crossce6734e2020-06-15 16:09:53 -07001333 module.addHostProperties()
1334 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001335 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001336
Yuexi Ma627263f2021-03-04 13:47:56 -08001337 InitTestHost(
1338 module,
1339 proptools.BoolPtr(true),
1340 nil,
1341 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001342
Liz Kammerdd849a82020-06-12 16:38:45 -07001343 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001344
Colin Cross05638fc2018-04-09 18:40:24 -07001345 return module
1346}
1347
Yuexi Ma627263f2021-03-04 13:47:56 -08001348func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1349 th.properties.Installable = installable
1350 th.testProperties.Auto_gen_config = autoGenConfig
1351 th.testProperties.Test_suites = testSuites
1352}
1353
Colin Cross05638fc2018-04-09 18:40:24 -07001354//
Colin Cross2fe66872015-03-30 17:20:39 -07001355// Java Binaries (.jar file plus wrapper script)
1356//
1357
Colin Crossf506d872017-07-19 15:53:04 -07001358type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001359 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001360 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001361
1362 // Name of the class containing main to be inserted into the manifest as Main-Class.
1363 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001364
1365 // Names of modules containing JNI libraries that should be installed alongside the host
1366 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001367 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001368}
1369
Colin Crossf506d872017-07-19 15:53:04 -07001370type Binary struct {
1371 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001372
Colin Crossf506d872017-07-19 15:53:04 -07001373 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001374
Colin Cross6b4a32d2017-12-05 13:42:45 -08001375 isWrapperVariant bool
1376
Colin Crossc3315992017-12-08 19:12:36 -08001377 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001378 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001379}
1380
Alex Light24237172017-10-26 09:46:21 -07001381func (j *Binary) HostToolPath() android.OptionalPath {
1382 return android.OptionalPathForPath(j.binaryFile)
1383}
1384
Colin Crossf506d872017-07-19 15:53:04 -07001385func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001386 if ctx.Arch().ArchType == android.Common {
1387 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001388 if j.binaryProperties.Main_class != nil {
1389 if j.properties.Manifest != nil {
1390 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1391 }
1392 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1393 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1394 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1395 }
1396
Colin Cross6b4a32d2017-12-05 13:42:45 -08001397 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001398 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001399 // Handle the binary wrapper
1400 j.isWrapperVariant = true
1401
Colin Cross366938f2017-12-11 16:29:02 -08001402 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001403 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001404 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001405 if ctx.Windows() {
1406 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1407 }
1408
Zi Wangca65b402022-10-10 13:45:06 -07001409 if ctx.Device() {
1410 // device binary should have a main_class property if it does not
1411 // have a specific wrapper, so that a default wrapper can
1412 // be generated for it.
1413 if j.binaryProperties.Main_class == nil {
1414 ctx.PropertyErrorf("main_class", "main_class property "+
1415 "is required for device binary if no default wrapper is assigned")
1416 } else {
1417 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1418 jarName := j.Stem() + ".jar"
1419 partition := j.PartitionTag(ctx.DeviceConfig())
1420 ctx.Build(pctx, android.BuildParams{
1421 Rule: deviceBinaryWrapper,
1422 Output: wrapper,
1423 Args: map[string]string{
1424 "jar_name": jarName,
1425 "partition": partition,
1426 "main_class": String(j.binaryProperties.Main_class),
1427 },
1428 })
1429 j.wrapperFile = wrapper
1430 }
1431 } else {
1432 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1433 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001434 }
1435
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001436 ext := ""
1437 if ctx.Windows() {
1438 ext = ".bat"
1439 }
1440
Colin Crossc179ea62020-10-09 10:54:15 -07001441 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001442 // of the wrapper variant, which will include the common variant's jar file and any JNI
1443 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001444 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001445 ctx.ModuleName()+ext, j.wrapperFile)
1446 }
Colin Cross2fe66872015-03-30 17:20:39 -07001447}
1448
Colin Crossf506d872017-07-19 15:53:04 -07001449func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001450 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001451 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001452 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001453 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001454 // These dependencies ensure the host installation rules will install the jar file and
1455 // the jni libraries when the wrapper is installed.
1456 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1457 ctx.AddVariationDependencies(
1458 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1459 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001460 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001461}
1462
Colin Cross1b16b0e2019-02-12 14:41:32 -08001463// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1464// as well.
1465//
1466// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1467// compiled against the device bootclasspath.
1468//
1469// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1470// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001471func BinaryFactory() android.Module {
1472 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001473
Colin Crossce6734e2020-06-15 16:09:53 -07001474 module.addHostAndDeviceProperties()
1475 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001476
Colin Cross9ae1b922018-06-26 17:59:05 -07001477 module.Module.properties.Installable = proptools.BoolPtr(true)
1478
Colin Cross6b4a32d2017-12-05 13:42:45 -08001479 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1480 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001481 android.InitBazelModule(module)
1482
Colin Cross36242852017-06-23 15:06:31 -07001483 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001484}
1485
Colin Cross1b16b0e2019-02-12 14:41:32 -08001486// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1487//
1488// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1489// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001490func BinaryHostFactory() android.Module {
1491 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001492
Colin Crossce6734e2020-06-15 16:09:53 -07001493 module.addHostProperties()
1494 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001495
Colin Cross9ae1b922018-06-26 17:59:05 -07001496 module.Module.properties.Installable = proptools.BoolPtr(true)
1497
Colin Cross6b4a32d2017-12-05 13:42:45 -08001498 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1499 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001500 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001501 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001502}
1503
1504//
1505// Java prebuilts
1506//
1507
Colin Cross74d73e22017-08-02 11:05:49 -07001508type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001509 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001510
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001511 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1512 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001513 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001514
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001515 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1516 // specified.
1517 Min_sdk_version *string
1518
William Loh5a082f92022-05-17 20:21:50 +00001519 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
1520 // and uses-permission tags in manifest_fixer.
1521 Replace_max_sdk_version_placeholder *string
1522
Colin Cross535e2cf2017-10-20 17:57:49 -07001523 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001524
Paul Duffin869de142021-07-15 14:14:41 +01001525 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001526 Permitted_packages []string
1527
Jiyong Park1be96912018-05-28 18:02:19 +09001528 // List of shared java libs that this module has dependencies to
1529 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001530
1531 // List of files to remove from the jar file(s)
1532 Exclude_files []string
1533
1534 // List of directories to remove from the jar file(s)
1535 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001536
1537 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001538 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001539
1540 // set the name of the output
1541 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001542
1543 Aidl struct {
1544 // directories that should be added as include directories for any aidl sources of modules
1545 // that depend on this module, as well as to aidl for this module.
1546 Export_include_dirs []string
1547 }
Colin Cross74d73e22017-08-02 11:05:49 -07001548}
1549
1550type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001551 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001552 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001553 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001554 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001555 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001556 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001557
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001558 // Functionality common to Module and Import.
1559 embeddableInModuleAndImport
1560
Liz Kammerd6c31d22020-08-05 15:40:41 -07001561 hiddenAPI
1562 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001563 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001564
Colin Cross74d73e22017-08-02 11:05:49 -07001565 properties ImportProperties
1566
Liz Kammerd6c31d22020-08-05 15:40:41 -07001567 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001568 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001569 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001570
Colin Cross0a6e0072017-08-30 14:24:55 -07001571 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001572 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001573 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001574
1575 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001576
1577 sdkVersion android.SdkSpec
1578 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001579}
1580
Paul Duffin630b11e2021-07-15 13:35:26 +01001581var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1582
1583func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1584 return j.properties.Permitted_packages
1585}
1586
Jiyong Park92315372021-04-02 08:45:46 +09001587func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1588 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001589}
1590
Jiyong Parkf1691d22021-03-29 20:11:58 +09001591func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001592 return "none"
1593}
1594
Jiyong Park92315372021-04-02 08:45:46 +09001595func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001596 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001597 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001598 }
Jiyong Park92315372021-04-02 08:45:46 +09001599 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001600}
1601
William Loh5a082f92022-05-17 20:21:50 +00001602func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
1603 if j.properties.Replace_max_sdk_version_placeholder != nil {
1604 return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
1605 }
1606 return android.SdkSpecFrom(ctx, "")
1607}
1608
Jiyong Park92315372021-04-02 08:45:46 +09001609func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1610 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001611}
1612
Colin Cross74d73e22017-08-02 11:05:49 -07001613func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001614 return &j.prebuilt
1615}
1616
Colin Cross74d73e22017-08-02 11:05:49 -07001617func (j *Import) PrebuiltSrcs() []string {
1618 return j.properties.Jars
1619}
1620
1621func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001622 return j.prebuilt.Name(j.ModuleBase.Name())
1623}
1624
Jiyong Park0b238752019-10-29 11:23:10 +09001625func (j *Import) Stem() string {
1626 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1627}
1628
Jiyong Park618922e2020-01-08 13:35:43 +09001629func (a *Import) JacocoReportClassesFile() android.Path {
1630 return nil
1631}
1632
Bill Peckhama41a6962021-01-11 10:58:54 -08001633func (j *Import) LintDepSets() LintDepSets {
1634 return LintDepSets{}
1635}
1636
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001637func (j *Import) getStrictUpdatabilityLinting() bool {
1638 return false
1639}
1640
1641func (j *Import) setStrictUpdatabilityLinting(bool) {
1642}
1643
Colin Cross74d73e22017-08-02 11:05:49 -07001644func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001645 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001646
1647 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001648 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001649 }
Colin Cross1e676be2016-10-12 14:38:15 -07001650}
1651
Sam Delmerico277795c2022-02-25 17:04:37 +00001652func (j *Import) commonBuildActions(ctx android.ModuleContext) {
1653 //TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09001654 j.sdkVersion = j.SdkVersion(ctx)
1655 j.minSdkVersion = j.MinSdkVersion(ctx)
1656
Colin Cross56a83212020-09-15 18:30:11 -07001657 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1658 j.hideApexVariantFromMake = true
1659 }
1660
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001661 if ctx.Windows() {
1662 j.HideFromMake()
1663 }
Sam Delmerico277795c2022-02-25 17:04:37 +00001664}
1665
1666func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1667 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001668
Colin Cross8a497952019-03-05 22:25:09 -08001669 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001670
Jiyong Park0b238752019-10-29 11:23:10 +09001671 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001672 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001673 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1674 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001675 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001676 inputFile := outputFile
1677 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1678 TransformJetifier(ctx, outputFile, inputFile)
1679 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001680 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001681 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001682
Liz Kammerd6c31d22020-08-05 15:40:41 -07001683 var flags javaBuilderFlags
1684
Jiyong Park1be96912018-05-28 18:02:19 +09001685 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001686 tag := ctx.OtherModuleDependencyTag(module)
1687
Colin Crossdcf71b22021-02-01 13:59:03 -08001688 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1689 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001690 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001691 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001692 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1693 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1694 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001695 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001696 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001697 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001698 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001699 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001700 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001701 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09001702 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001703 }
1704 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001705
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001706 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001707 })
1708
Sam Delmerico277795c2022-02-25 17:04:37 +00001709 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09001710
1711 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001712
Paul Duffin064b70c2020-11-02 17:32:38 +00001713 if ctx.Device() {
1714 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1715 // obtained from the associated deapexer module.
1716 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1717 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001718 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001719 di := android.FindDeapexerProviderForModule(ctx)
1720 if di == nil {
1721 return // An error has been reported by FindDeapexerProviderForModule.
1722 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001723 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001724 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1725 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001726 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1727 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001728
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001729 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001730 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001731 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1732 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001733
1734 // Initialize the hiddenapi structure.
1735 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001736 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001737 // This should never happen as a variant for a prebuilt_apex is only created if the
1738 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001739 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001740 }
1741 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001742 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001743 if sdkDep.invalidVersion {
1744 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1745 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1746 } else if sdkDep.useFiles {
1747 // sdkDep.jar is actually equivalent to turbine header.jar.
1748 flags.classpath = append(flags.classpath, sdkDep.jars...)
1749 }
1750
1751 // Dex compilation
1752
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001753 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1754 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001755 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001756 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1757
Paul Duffin612e6102021-02-02 13:38:13 +00001758 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001759 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001760 if ctx.Failed() {
1761 return
1762 }
1763
Paul Duffin74d18d12021-05-14 14:18:47 +01001764 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001765 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001766
1767 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001768 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001769
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001770 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001771 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001772 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001773 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001774
1775 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1776 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1777 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1778 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1779 AidlIncludeDirs: j.exportAidlIncludeDirs,
1780 })
Colin Cross2fe66872015-03-30 17:20:39 -07001781}
1782
Sam Delmerico277795c2022-02-25 17:04:37 +00001783func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
1784 if !Bool(j.properties.Installable) {
1785 return
1786 }
1787
1788 var installDir android.InstallPath
1789 if ctx.InstallInTestcases() {
1790 var archDir string
1791 if !ctx.Host() {
1792 archDir = ctx.DeviceConfig().DeviceArch()
1793 }
1794 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1795 } else {
1796 installDir = android.PathForModuleInstall(ctx, "framework")
1797 }
1798 ctx.InstallFile(installDir, jarName, outputFile)
1799}
1800
Paul Duffinaa55f742020-10-06 17:20:13 +01001801func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1802 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001803 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001804 return android.Paths{j.combinedClasspathFile}, nil
1805 default:
1806 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1807 }
1808}
1809
1810var _ android.OutputFileProducer = (*Import)(nil)
1811
Nan Zhanged19fc32017-10-19 13:06:22 -07001812func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001813 if j.combinedClasspathFile == nil {
1814 return nil
1815 }
Colin Cross37f6d792018-07-12 12:28:41 -07001816 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001817}
1818
Colin Cross331a1212018-08-15 20:40:52 -07001819func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001820 if j.combinedClasspathFile == nil {
1821 return nil
1822 }
Colin Cross331a1212018-08-15 20:40:52 -07001823 return android.Paths{j.combinedClasspathFile}
1824}
1825
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001826func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001827 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001828}
1829
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001830func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001831 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001832}
1833
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001834func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1835 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001836}
1837
Jiyong Park45bf82e2020-12-15 22:29:02 +09001838var _ android.ApexModule = (*Import)(nil)
1839
1840// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001841func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001842 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001843}
1844
Jiyong Park45bf82e2020-12-15 22:29:02 +09001845// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001846func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1847 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001848 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001849 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001850 return fmt.Errorf("min_sdk_version is not specified")
1851 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001852 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001853 return nil
1854 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001855 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1856 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001857 }
Jooyung Han749dc692020-04-15 11:03:39 +09001858 return nil
1859}
1860
Paul Duffinfef55002021-06-17 14:56:05 +01001861// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1862// java_sdk_library_import with the specified base module name requires to be exported from a
1863// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001864func requiredFilesFromPrebuiltApexForImport(name string) []string {
1865 // Add the dex implementation jar to the set of exported files.
1866 return []string{
1867 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001868 }
1869}
1870
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001871// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1872// the java library with the specified name.
1873func apexRootRelativePathToJavaLib(name string) string {
1874 return filepath.Join("javalib", name+".jar")
1875}
1876
Paul Duffinfef55002021-06-17 14:56:05 +01001877var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1878
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001879func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001880 name := j.BaseModuleName()
1881 return requiredFilesFromPrebuiltApexForImport(name)
1882}
1883
albaltai36ff7dc2018-12-25 14:35:23 +08001884// Add compile time check for interface implementation
1885var _ android.IDEInfo = (*Import)(nil)
1886var _ android.IDECustomizedModuleName = (*Import)(nil)
1887
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001888// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001889
1890func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1891 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1892}
1893
1894func (j *Import) IDECustomizedModuleName() string {
1895 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1896 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1897 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001898 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001899}
1900
Colin Cross74d73e22017-08-02 11:05:49 -07001901var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001902
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001903func (j *Import) IsInstallable() bool {
1904 return Bool(j.properties.Installable)
1905}
1906
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001907var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001908
Colin Cross1b16b0e2019-02-12 14:41:32 -08001909// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1910//
1911// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1912// compiled against an Android classpath.
1913//
1914// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1915// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001916func ImportFactory() android.Module {
1917 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001918
Liz Kammerd6c31d22020-08-05 15:40:41 -07001919 module.AddProperties(
1920 &module.properties,
1921 &module.dexer.dexProperties,
1922 )
Colin Cross74d73e22017-08-02 11:05:49 -07001923
Paul Duffin71b33cc2021-06-23 11:39:47 +01001924 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001925
Liz Kammerd6c31d22020-08-05 15:40:41 -07001926 module.dexProperties.Optimize.EnabledByDefault = false
1927
Colin Cross74d73e22017-08-02 11:05:49 -07001928 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001929 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001930 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001931 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001932 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001933 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001934}
1935
Colin Cross1b16b0e2019-02-12 14:41:32 -08001936// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1937// module.
1938//
1939// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1940// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001941func ImportFactoryHost() android.Module {
1942 module := &Import{}
1943
1944 module.AddProperties(&module.properties)
1945
1946 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001947 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001948 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001949 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001950 return module
1951}
1952
Colin Cross42be7612019-02-21 18:12:14 -08001953// dex_import module
1954
1955type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001956 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001957
1958 // set the name of the output
1959 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001960}
1961
1962type DexImport struct {
1963 android.ModuleBase
1964 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001965 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001966 prebuilt android.Prebuilt
1967
1968 properties DexImportProperties
1969
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001970 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001971
1972 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001973
1974 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001975}
1976
1977func (j *DexImport) Prebuilt() *android.Prebuilt {
1978 return &j.prebuilt
1979}
1980
1981func (j *DexImport) PrebuiltSrcs() []string {
1982 return j.properties.Jars
1983}
1984
1985func (j *DexImport) Name() string {
1986 return j.prebuilt.Name(j.ModuleBase.Name())
1987}
1988
Jiyong Park0b238752019-10-29 11:23:10 +09001989func (j *DexImport) Stem() string {
1990 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1991}
1992
Jiyong Park77acec62020-06-01 21:39:15 +09001993func (a *DexImport) JacocoReportClassesFile() android.Path {
1994 return nil
1995}
1996
Colin Cross08dca382020-07-21 20:31:17 -07001997func (a *DexImport) LintDepSets() LintDepSets {
1998 return LintDepSets{}
1999}
2000
Martin Stjernholm6d415272020-01-31 17:10:36 +00002001func (j *DexImport) IsInstallable() bool {
2002 return true
2003}
2004
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002005func (j *DexImport) getStrictUpdatabilityLinting() bool {
2006 return false
2007}
2008
2009func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2010}
2011
Colin Cross42be7612019-02-21 18:12:14 -08002012func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2013 if len(j.properties.Jars) != 1 {
2014 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2015 }
2016
Colin Cross56a83212020-09-15 18:30:11 -07002017 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
2018 if !apexInfo.IsForPlatform() {
2019 j.hideApexVariantFromMake = true
2020 }
2021
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002022 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2023 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08002024 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
2025
2026 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2027 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2028
2029 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002030 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002031
2032 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2033 rule.Temporary(temporary)
2034
2035 // use zip2zip to uncompress classes*.dex files
2036 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002037 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002038 FlagWithInput("-i ", inputJar).
2039 FlagWithOutput("-o ", temporary).
2040 FlagWithArg("-0 ", "'classes*.dex'")
2041
2042 // use zipalign to align uncompressed classes*.dex files
2043 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002044 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002045 Flag("-f").
2046 Text("4").
2047 Input(temporary).
2048 Output(dexOutputFile)
2049
2050 rule.DeleteTemporaryFiles()
2051
Colin Crossf1a035e2020-11-16 17:32:30 -08002052 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002053 } else {
2054 ctx.Build(pctx, android.BuildParams{
2055 Rule: android.Cp,
2056 Input: inputJar,
2057 Output: dexOutputFile,
2058 })
2059 }
2060
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002061 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002062
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002063 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002064
Colin Cross56a83212020-09-15 18:30:11 -07002065 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002066 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2067 j.Stem()+".jar", dexOutputFile)
2068 }
Colin Cross42be7612019-02-21 18:12:14 -08002069}
2070
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002071func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002072 return j.dexJarFile
2073}
2074
Jiyong Park45bf82e2020-12-15 22:29:02 +09002075var _ android.ApexModule = (*DexImport)(nil)
2076
2077// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002078func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2079 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002080 // we don't check prebuilt modules for sdk_version
2081 return nil
2082}
2083
Colin Cross42be7612019-02-21 18:12:14 -08002084// dex_import imports a `.jar` file containing classes.dex files.
2085//
2086// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2087// to the device.
2088func DexImportFactory() android.Module {
2089 module := &DexImport{}
2090
2091 module.AddProperties(&module.properties)
2092
2093 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002094 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002095 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002096 return module
2097}
2098
Colin Cross89536d42017-07-07 14:35:50 -07002099// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002100type Defaults struct {
2101 android.ModuleBase
2102 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002103 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002104}
2105
Colin Cross1b16b0e2019-02-12 14:41:32 -08002106// java_defaults provides a set of properties that can be inherited by other java or android modules.
2107//
2108// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2109// property in the defaults module that exists in the depending module will be prepended to the depending module's
2110// value for that property.
2111//
2112// Example:
2113//
Sam Delmerico277795c2022-02-25 17:04:37 +00002114// java_defaults {
2115// name: "example_defaults",
2116// srcs: ["common/**/*.java"],
2117// javacflags: ["-Xlint:all"],
2118// aaptflags: ["--auto-add-overlay"],
2119// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002120//
Sam Delmerico277795c2022-02-25 17:04:37 +00002121// java_library {
2122// name: "example",
2123// defaults: ["example_defaults"],
2124// srcs: ["example/**/*.java"],
2125// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002126//
2127// is functionally identical to:
2128//
Sam Delmerico277795c2022-02-25 17:04:37 +00002129// java_library {
2130// name: "example",
2131// srcs: [
2132// "common/**/*.java",
2133// "example/**/*.java",
2134// ],
2135// javacflags: ["-Xlint:all"],
2136// }
Paul Duffin47357662019-12-05 14:07:14 +00002137func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002138 module := &Defaults{}
2139
Colin Cross89536d42017-07-07 14:35:50 -07002140 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002141 &CommonProperties{},
2142 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002143 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002144 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002145 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002146 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002147 &aaptProperties{},
2148 &androidLibraryProperties{},
2149 &appProperties{},
2150 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002151 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002152 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002153 &ImportProperties{},
2154 &AARImportProperties{},
2155 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002156 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002157 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002158 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002159 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002160 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002161 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002162 )
2163
2164 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002165 return module
2166}
Nan Zhangea568a42017-11-08 21:20:04 -08002167
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002168func kytheExtractJavaFactory() android.Singleton {
2169 return &kytheExtractJavaSingleton{}
2170}
2171
2172type kytheExtractJavaSingleton struct {
2173}
2174
2175func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2176 var xrefTargets android.Paths
2177 ctx.VisitAllModules(func(module android.Module) {
2178 if javaModule, ok := module.(xref); ok {
2179 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2180 }
2181 })
2182 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2183 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002184 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002185 }
2186}
2187
Nan Zhangea568a42017-11-08 21:20:04 -08002188var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002189var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002190var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08002191var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002192
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002193// Add class loader context (CLC) of a given dependency to the current CLC.
2194func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2195 clcMap dexpreopt.ClassLoaderContextMap) {
2196
2197 dep, ok := depModule.(UsesLibraryDependency)
2198 if !ok {
2199 return
2200 }
2201
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002202 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2203
2204 var sdkLib *string
2205 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2206 // A shared SDK library. This should be added as a top-level CLC element.
2207 sdkLib = &depName
2208 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2209 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2210 // property. This should be handled in the same way as a shared SDK library.
2211 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002212 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002213
2214 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002215 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002216 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002217 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2218 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002219 } else if depTag == staticLibTag {
2220 // Propagate <uses-library> through static library dependencies, unless it is a component
2221 // library (such as stubs). Component libraries have a dependency on their SDK library,
2222 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002223 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002224 return
2225 }
2226 } else {
2227 // Don't propagate <uses-library> for other dependency tags.
2228 return
2229 }
2230
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002231 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2232 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2233 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2234 // from its CLC should be added to the current CLC.
2235 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002236 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002237 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002238 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002239 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2240 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002241}
Wei Libafb6d62021-12-10 03:14:59 -08002242
Sam Delmerico79985812022-03-23 20:20:42 +00002243type javaResourcesAttributes struct {
2244 Resources bazel.LabelListAttribute
2245 Resource_strip_prefix *string
2246}
2247
2248func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
2249 var resources bazel.LabelList
2250 var resourceStripPrefix *string
2251
2252 if m.properties.Java_resources != nil {
2253 resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
2254 }
2255
2256 //TODO(b/179889880) handle case where glob includes files outside package
2257 resDeps := ResourceDirsToFiles(
2258 ctx,
2259 m.properties.Java_resource_dirs,
2260 m.properties.Exclude_java_resource_dirs,
2261 m.properties.Exclude_java_resources,
2262 )
2263
2264 for i, resDep := range resDeps {
2265 dir, files := resDep.dir, resDep.files
2266
2267 resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
2268
2269 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2270 // inside the JAR file, so we need to remove that prefix
2271 resourceStripPrefix = proptools.StringPtr(dir.String())
2272 if i > 0 {
2273 // TODO(b/226423379) allow multiple resource prefixes
2274 ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
2275 }
2276 }
2277
2278 return &javaResourcesAttributes{
2279 Resources: bazel.MakeLabelListAttribute(resources),
2280 Resource_strip_prefix: resourceStripPrefix,
2281 }
2282}
2283
Sam Delmericoc0161432022-02-25 21:34:51 +00002284type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002285 *javaResourcesAttributes
Wei Libafb6d62021-12-10 03:14:59 -08002286 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002287 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002288 Javacopts bazel.StringListAttribute
2289}
2290
Sam Delmericoc0161432022-02-25 21:34:51 +00002291type javaDependencyLabels struct {
2292 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2293 Deps bazel.LabelListAttribute
2294 // Dependencies which DO contribute to the API visible to upstream dependencies.
2295 StaticDeps bazel.LabelListAttribute
2296}
2297
Sam Delmerico24da73c2022-03-16 20:36:54 +00002298type eventLogTagsAttributes struct {
2299 Srcs bazel.LabelListAttribute
2300}
2301
Sam Delmerico97bd1272022-08-25 14:45:31 -04002302type aidlLibraryAttributes struct {
2303 Srcs bazel.LabelListAttribute
2304}
2305
2306type javaAidlLibraryAttributes struct {
2307 Deps bazel.LabelListAttribute
2308}
2309
Alix8062f4d2022-11-14 21:38:07 +00002310// bp2BuildJavaInfo has information needed for the conversion of java*_modules
2311// that is needed bor Bp2Build conversion but that requires different handling
2312// depending on the module type.
2313type bp2BuildJavaInfo struct {
2314 // separates dependencies into dynamic dependencies and static dependencies.
2315 DepLabels *javaDependencyLabels
2316 hasKotlinSrcs bool
2317}
2318
2319// convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
2320// converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
2321// which has other non-attribute information needed for bp2build conversion
2322// that needs different handling depending on the module types, and thus needs
2323// to be returned to the calling function.
2324func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002325 var srcs bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002326 var deps bazel.LabelList
2327 var staticDeps bazel.LabelList
2328
Sam Delmericoe91d0302022-02-23 15:28:33 +00002329 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2330 for axis, configToProps := range archVariantProps {
2331 for config, _props := range configToProps {
2332 if archProps, ok := _props.(*CommonProperties); ok {
2333 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2334 srcs.SetSelectValue(axis, config, archSrcs)
2335 }
2336 }
2337 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002338
2339 javaSrcPartition := "java"
2340 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002341 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002342 aidlSrcPartition := "aidl"
Alix8062f4d2022-11-14 21:38:07 +00002343 kotlinPartition := "kotlin"
Sam Delmericoc7681022022-02-04 21:01:20 +00002344 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002345 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2346 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2347 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04002348 aidlSrcPartition: android.AidlSrcLabelPartition,
Alix8062f4d2022-11-14 21:38:07 +00002349 kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}},
Sam Delmericoc7681022022-02-04 21:01:20 +00002350 })
2351
Sam Delmerico24da73c2022-03-16 20:36:54 +00002352 javaSrcs := srcPartitions[javaSrcPartition]
Alix8062f4d2022-11-14 21:38:07 +00002353 kotlinSrcs := srcPartitions[kotlinPartition]
2354 javaSrcs.Append(kotlinSrcs)
Sam Delmerico24da73c2022-03-16 20:36:54 +00002355
Sam Delmerico24da73c2022-03-16 20:36:54 +00002356 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2357 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002358 ctx.CreateBazelTargetModule(
2359 bazel.BazelTargetModuleProperties{
2360 Rule_class: "event_log_tags",
Sam Delmerico48af73b2022-04-05 14:03:11 +00002361 Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
Sam Delmerico24da73c2022-03-16 20:36:54 +00002362 },
2363 android.CommonAttributes{Name: logtagsLibName},
2364 &eventLogTagsAttributes{
2365 Srcs: srcPartitions[logtagSrcPartition],
2366 },
2367 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04002368
2369 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2370 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00002371 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002372
2373 if !srcPartitions[aidlSrcPartition].IsEmpty() {
2374 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
2375 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
2376 })
2377
2378 if !aidlSrcs.IsEmpty() {
2379 aidlLibName := m.Name() + "_aidl_library"
2380 ctx.CreateBazelTargetModule(
2381 bazel.BazelTargetModuleProperties{
2382 Rule_class: "aidl_library",
2383 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
2384 },
2385 android.CommonAttributes{Name: aidlLibName},
2386 &aidlLibraryAttributes{
2387 Srcs: aidlSrcs,
2388 },
2389 )
2390 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
2391 }
2392
2393 javaAidlLibName := m.Name() + "_java_aidl_library"
2394 ctx.CreateBazelTargetModule(
2395 bazel.BazelTargetModuleProperties{
2396 Rule_class: "java_aidl_library",
2397 Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
2398 },
2399 android.CommonAttributes{Name: javaAidlLibName},
2400 &javaAidlLibraryAttributes{
2401 Deps: aidlLibs,
2402 },
2403 )
2404
2405 staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
2406 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00002407
Sam Delmerico58614c02022-03-15 21:02:09 +00002408 var javacopts []string
2409 if m.properties.Javacflags != nil {
2410 javacopts = append(javacopts, m.properties.Javacflags...)
2411 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002412 if m.properties.Java_version != nil {
2413 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2414 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2415 }
2416
Sam Delmerico58614c02022-03-15 21:02:09 +00002417 epEnabled := m.properties.Errorprone.Enabled
2418 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
2419 if Bool(epEnabled) {
2420 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2421 }
2422
Sam Delmericoc0161432022-02-25 21:34:51 +00002423 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00002424 Srcs: javaSrcs,
2425 javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
Sam Delmerico77267c72022-03-18 14:11:07 +00002426 Plugins: bazel.MakeLabelListAttribute(
2427 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2428 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002429 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002430 }
2431
2432 if m.properties.Libs != nil {
Alixb4e09a02022-09-27 15:36:01 +00002433
2434 // TODO 244210934 ALIX Check if this else statement breaks presubmits get rid of it if it doesn't
2435 if strings.HasPrefix(ctx.ModuleType(), "java_binary") {
2436 for _, d := range m.properties.Libs {
2437 neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
2438 neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
2439 deps.Add(&neverlinkLabel)
2440 }
2441
2442 } else {
2443 deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
2444 }
Wei Libafb6d62021-12-10 03:14:59 -08002445 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002446
Sam Delmericofde9fb52022-01-28 20:53:38 +00002447 if m.properties.Static_libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002448 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002449 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002450
Sam Delmericoc0161432022-02-25 21:34:51 +00002451 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2452 // Soong does not differentiate between a java_library and the Bazel equivalent of
2453 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2454 // listed directly in the srcs of a java_library, and the classes produced
2455 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2456 // that depend on a java_library with proto sources can link directly to the protobuf API,
2457 // and so this should be a static dependency.
2458 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002459
Sam Delmerico97bd1272022-08-25 14:45:31 -04002460 depLabels := &javaDependencyLabels{}
Sam Delmericoc0161432022-02-25 21:34:51 +00002461 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2462 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002463
Alix8062f4d2022-11-14 21:38:07 +00002464 bp2BuildInfo := &bp2BuildJavaInfo{
2465 DepLabels: depLabels,
2466 hasKotlinSrcs: !kotlinSrcs.IsEmpty(),
2467 }
2468
2469 return commonAttrs, bp2BuildInfo
Sam Delmericoc0161432022-02-25 21:34:51 +00002470}
2471
2472type javaLibraryAttributes struct {
2473 *javaCommonAttributes
Alix8062f4d2022-11-14 21:38:07 +00002474 Deps bazel.LabelListAttribute
2475 Exports bazel.LabelListAttribute
2476 Neverlink bazel.BoolAttribute
2477 Common_srcs bazel.LabelListAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002478}
2479
2480func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Alix8062f4d2022-11-14 21:38:07 +00002481 commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
2482 depLabels := bp2BuildInfo.DepLabels
Sam Delmericoc0161432022-02-25 21:34:51 +00002483
2484 deps := depLabels.Deps
2485 if !commonAttrs.Srcs.IsEmpty() {
2486 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2487
2488 sdkVersion := m.SdkVersion(ctx)
2489 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2490 // TODO(b/220869005) remove forced dependency on current public android.jar
2491 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2492 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002493 } else if !deps.IsEmpty() {
Sam Delmericoc0161432022-02-25 21:34:51 +00002494 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2495 }
2496
Alix8062f4d2022-11-14 21:38:07 +00002497 var props bazel.BazelTargetModuleProperties
Sam Delmericoc0161432022-02-25 21:34:51 +00002498 attrs := &javaLibraryAttributes{
2499 javaCommonAttributes: commonAttrs,
2500 Deps: deps,
2501 Exports: depLabels.StaticDeps,
2502 }
Wei Libafb6d62021-12-10 03:14:59 -08002503
Alix8062f4d2022-11-14 21:38:07 +00002504 if !bp2BuildInfo.hasKotlinSrcs && len(m.properties.Common_srcs) == 0 {
2505 props = bazel.BazelTargetModuleProperties{
2506 Rule_class: "java_library",
2507 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2508 }
2509 } else {
2510 attrs.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
2511
2512 props = bazel.BazelTargetModuleProperties{
2513 Rule_class: "kt_jvm_library",
2514 Bzl_load_location: "@rules_kotlin//kotlin:jvm_library.bzl",
2515 }
Wei Libafb6d62021-12-10 03:14:59 -08002516 }
2517
Alixb4e09a02022-09-27 15:36:01 +00002518 name := m.Name()
2519 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
Wei Libafb6d62021-12-10 03:14:59 -08002520}
2521
2522type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002523 *javaCommonAttributes
2524 Deps bazel.LabelListAttribute
2525 Runtime_deps bazel.LabelListAttribute
2526 Main_class string
2527 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002528}
2529
2530// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2531func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Alix8062f4d2022-11-14 21:38:07 +00002532 commonAttrs, bp2BuildInfo := m.convertLibraryAttrsBp2Build(ctx)
2533 depLabels := bp2BuildInfo.DepLabels
Sam Delmericoc0161432022-02-25 21:34:51 +00002534
2535 deps := depLabels.Deps
2536 deps.Append(depLabels.StaticDeps)
2537 if m.binaryProperties.Jni_libs != nil {
2538 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2539 }
2540
2541 var runtimeDeps bazel.LabelListAttribute
2542 if commonAttrs.Srcs.IsEmpty() {
2543 // if there are no sources, then the dependencies can only be used at runtime
2544 runtimeDeps = deps
2545 deps = bazel.LabelListAttribute{}
2546 }
2547
Wei Libafb6d62021-12-10 03:14:59 -08002548 mainClass := ""
2549 if m.binaryProperties.Main_class != nil {
2550 mainClass = *m.binaryProperties.Main_class
2551 }
2552 if m.properties.Manifest != nil {
2553 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2554 if err != nil {
2555 return
2556 }
2557 mainClass = mainClassInManifest
2558 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002559
Wei Libafb6d62021-12-10 03:14:59 -08002560 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002561 javaCommonAttributes: commonAttrs,
2562 Deps: deps,
2563 Runtime_deps: runtimeDeps,
2564 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002565 }
2566
2567 // Attribute jvm_flags
2568 if m.binaryProperties.Jni_libs != nil {
2569 jniLibPackages := map[string]bool{}
2570 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2571 jniLibPackage := jniLibLabel.Label
2572 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2573 if indexOfColon > 0 {
2574 // JNI lib from other package
2575 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2576 } else if indexOfColon == 0 {
2577 // JNI lib in the same package of java_binary
2578 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2579 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2580 }
2581 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2582 jniLibPackages[jniLibPackage] = true
2583 }
2584 }
2585 jniLibPaths := []string{}
2586 for jniLibPackage, _ := range jniLibPackages {
2587 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2588 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2589 }
2590 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2591 }
2592
2593 props := bazel.BazelTargetModuleProperties{
2594 Rule_class: "java_binary",
2595 }
2596
2597 // Create the BazelTargetModule.
2598 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2599}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002600
2601type bazelJavaImportAttributes struct {
Alixb4e09a02022-09-27 15:36:01 +00002602 Jars bazel.LabelListAttribute
2603 Exports bazel.LabelListAttribute
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002604}
2605
2606// java_import bp2Build converter.
2607func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002608 var jars bazel.LabelListAttribute
2609 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2610 for axis, configToProps := range archVariantProps {
2611 for config, _props := range configToProps {
2612 if archProps, ok := _props.(*ImportProperties); ok {
2613 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2614 jars.SetSelectValue(axis, config, archJars)
2615 }
2616 }
2617 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002618
2619 attrs := &bazelJavaImportAttributes{
2620 Jars: jars,
2621 }
2622 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2623
Alixb4e09a02022-09-27 15:36:01 +00002624 name := android.RemoveOptionalPrebuiltPrefix(i.Name())
2625
2626 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
2627
2628 neverlink := true
2629 neverlinkAttrs := &javaLibraryAttributes{
2630 Neverlink: bazel.BoolAttribute{Value: &neverlink},
2631 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
2632 }
2633 ctx.CreateBazelTargetModule(bazel.BazelTargetModuleProperties{Rule_class: "java_library"}, android.CommonAttributes{Name: name + "-neverlink"}, neverlinkAttrs)
2634
Sam Delmerico277795c2022-02-25 17:04:37 +00002635}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002636
Sam Delmerico277795c2022-02-25 17:04:37 +00002637var _ android.MixedBuildBuildable = (*Import)(nil)
2638
2639func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
2640 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
2641}
2642
2643func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
2644 i.commonBuildActions(ctx)
2645
2646 bazelCtx := ctx.Config().BazelContext
2647 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
2648 if err != nil {
2649 ctx.ModuleErrorf(err.Error())
2650 return
2651 }
2652
2653 bazelJars := android.Paths{}
2654 for _, bazelOutputFile := range filePaths {
2655 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
2656 }
2657
2658 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
2659 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
2660 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
2661 android.OptionalPath{}, // manifest
2662 false, // stripDirEntries
2663 []string{}, // filesToStrip
2664 []string{}, // dirsToStrip
2665 )
2666 i.combinedClasspathFile = outputFile
2667
2668 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2669 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
2670 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
2671 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
2672 //TODO(b/240308299) include AIDL information from Bazel
2673 })
2674
2675 i.maybeInstall(ctx, jarName, outputFile)
2676}
2677
2678func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
2679 bazelCtx := ctx.Config().BazelContext
2680 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
2681}
2682
2683func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
2684 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002685}