blob: 3471abb79dbdea7354d9e7fe0257c9bab8573393 [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{
Paul Duffinc61783b2022-10-20 17:21:40 +010089 SdkMemberTypeBase: android.SdkMemberTypeBase{
Paul Duffin2da04242021-04-23 19:43:28 +010090 PropertyName: "java_header_libs",
91 SupportsSdk: true,
92 },
Paul Duffinc61783b2022-10-20 17:21:40 +010093 jarToExportGetter: func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin2da04242021-04-23 19:43:28 +010094 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 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100101 snapshotPathGetter: sdkSnapshotFilePathForJar,
102 onlyCopyJarToSnapshot: copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100103 }
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 Duffinc61783b2022-10-20 17:21:40 +0100116 SdkMemberTypeBase: android.SdkMemberTypeBase{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000117 PropertyName: "java_libs",
118 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100119 jarToExportGetter: exportImplementationClassesJar,
120 snapshotPathGetter: sdkSnapshotFilePathForJar,
121 onlyCopyJarToSnapshot: 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 Duffinc61783b2022-10-20 17:21:40 +0100146 SdkMemberTypeBase: android.SdkMemberTypeBase{
Paul Duffindb170e42020-12-08 17:48:25 +0000147 PropertyName: "java_boot_libs",
148 SupportsSdk: true,
149 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100150 jarToExportGetter: 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.
Paul Duffinc61783b2022-10-20 17:21:40 +0100159 return nil
Paul Duffin5c211452021-07-15 12:42:44 +0100160 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100161 snapshotPathGetter: func(ctx android.SdkMemberContext, osPrefix, name string) string {
Paul Duffin13648912022-07-15 13:12:35 +0000162 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 Duffinc61783b2022-10-20 17:21:40 +0100171 onlyCopyJarToSnapshot: 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{
Paul Duffinc61783b2022-10-20 17:21:40 +0100185 SdkMemberTypeBase: android.SdkMemberTypeBase{
Jiakai Zhangea180332021-09-26 08:58:02 +0000186 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 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100192 jarToExportGetter: func(ctx android.SdkMemberContext, j *Library) android.Path {
Jiakai Zhangea180332021-09-26 08:58:02 +0000193 // 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.
Paul Duffinc61783b2022-10-20 17:21:40 +0100197 return nil
Jiakai Zhangea180332021-09-26 08:58:02 +0000198 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100199 snapshotPathGetter: 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 },
Paul Duffinc61783b2022-10-20 17:21:40 +0100205 onlyCopyJarToSnapshot: onlyCopyJarToSnapshot,
Jiakai Zhangea180332021-09-26 08:58:02 +0000206 }
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
Paul Duffinc61783b2022-10-20 17:21:40 +0100235 // module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800236 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
Paul Duffinc61783b2022-10-20 17:21:40 +0100721 // the library, if this returns nil then it is assumed that the snapshot must not provide access
722 // to the jar.
Paul Duffindb170e42020-12-08 17:48:25 +0000723 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
724
725 // Function to compute the snapshot relative path to which the named library's
726 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000727 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000728
729 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
730 // files like aidl files should also be copied.
731 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000732}
733
Paul Duffindb170e42020-12-08 17:48:25 +0000734const (
735 onlyCopyJarToSnapshot = true
736 copyEverythingToSnapshot = false
737)
738
Paul Duffin296701e2021-07-14 10:29:36 +0100739func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
740 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000741}
742
743func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
744 _, ok := module.(*Library)
745 return ok
746}
747
Paul Duffin3a4eb502020-03-19 16:11:18 +0000748func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
749 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000750}
Paul Duffina0dbf432019-12-05 11:25:53 +0000751
Paul Duffin14eb4672020-03-02 11:33:02 +0000752func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000753 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000754}
755
756type librarySdkMemberProperties struct {
757 android.SdkMemberPropertiesBase
758
Paul Duffinc61783b2022-10-20 17:21:40 +0100759 JarToExport android.Path `android:"arch_variant"`
760
761 // The path to a script to use when the jar is invalid.
762 InvalidJarScript android.Path
763
Paul Duffina551a1c2020-03-17 21:04:24 +0000764 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100765
766 // The list of permitted packages that need to be passed to the prebuilts as they are used to
767 // create the updatable-bcp-packages.txt file.
768 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000769}
770
Paul Duffin3a4eb502020-03-19 16:11:18 +0000771func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000772 j := variant.(*Library)
773
Paul Duffinc61783b2022-10-20 17:21:40 +0100774 memberType := ctx.MemberType().(*librarySdkMemberType)
775 p.JarToExport = memberType.jarToExportGetter(ctx, j)
776
777 // If no jar was provided for export then disallow access to it completely.
778 if p.JarToExport == nil {
779 // Copy the script to prevent access to the jar into the snapshot.
780 p.InvalidJarScript = android.PathForSource(ctx.SdkModuleContext(),
781 "build/soong/java/invalid_implementation_jar.sh")
782 }
Paul Duffindb170e42020-12-08 17:48:25 +0000783
Paul Duffina551a1c2020-03-17 21:04:24 +0000784 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100785
786 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000787}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000788
Paul Duffin3a4eb502020-03-19 16:11:18 +0000789func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000790 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000791
Paul Duffindb170e42020-12-08 17:48:25 +0000792 memberType := ctx.MemberType().(*librarySdkMemberType)
793
Paul Duffina551a1c2020-03-17 21:04:24 +0000794 exportedJar := p.JarToExport
795 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000796 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000797 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000798
799 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000800 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
801
Paul Duffina551a1c2020-03-17 21:04:24 +0000802 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
803 }
804
Paul Duffinc61783b2022-10-20 17:21:40 +0100805 if scriptSrc := p.InvalidJarScript; scriptSrc != nil {
806 // Copy the script to prevent access to the jar into the snapshot.
807 scriptDest := filepath.Join("scripts", scriptSrc.Base())
808 builder.CopyToSnapshot(scriptSrc, scriptDest)
809
810 // Generate a genrule module that will invoke the script passing in the module name.
811 genrule := builder.AddInternalModule(p, "genrule", "error")
812 genRuleName := genrule.Name()
813 genrule.AddProperty("out", []string{"this-file-will-never-be-created.jar"})
814 genrule.AddProperty("tool_files", []string{scriptDest})
815 genrule.AddProperty("cmd", fmt.Sprintf("$(location %s) %s", scriptDest, p.Name()))
816
817 propertySet.AddPropertyWithTag("jars", []string{":" + genRuleName}, builder.SdkMemberReferencePropertyTag(true))
818 }
819
Paul Duffin869de142021-07-15 14:14:41 +0100820 if len(p.PermittedPackages) > 0 {
821 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
822 }
823
Paul Duffindb170e42020-12-08 17:48:25 +0000824 // Do not copy anything else to the snapshot.
825 if memberType.onlyCopyJarToSnapshot {
826 return
827 }
828
Paul Duffina551a1c2020-03-17 21:04:24 +0000829 aidlIncludeDirs := p.AidlIncludeDirs
830 if len(aidlIncludeDirs) != 0 {
831 sdkModuleContext := ctx.SdkModuleContext()
832 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000833 // TODO(jiyong): copy parcelable declarations only
834 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
835 for _, file := range aidlFiles {
836 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
837 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000838 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000839
Paul Duffina551a1c2020-03-17 21:04:24 +0000840 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000841 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000842}
843
Colin Cross1b16b0e2019-02-12 14:41:32 -0800844// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
845//
846// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
847// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
848// as a `static_libs` dependency of another module.
849//
850// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
851// a device.
852//
853// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
854// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700855func LibraryFactory() android.Module {
856 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700857
Colin Crossce6734e2020-06-15 16:09:53 -0700858 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700859
Paul Duffin71b33cc2021-06-23 11:39:47 +0100860 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100861
Jiyong Park7f7766d2019-07-25 22:02:35 +0900862 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900863 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800864 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900865 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700866 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700867}
868
Colin Cross1b16b0e2019-02-12 14:41:32 -0800869// java_library_static is an obsolete alias for java_library.
870func LibraryStaticFactory() android.Module {
871 return LibraryFactory()
872}
873
874// java_library_host builds and links sources into a `.jar` file for the host.
875//
876// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
877// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700878func LibraryHostFactory() android.Module {
879 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700880
Colin Crossce6734e2020-06-15 16:09:53 -0700881 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700882
Colin Cross9ae1b922018-06-26 17:59:05 -0700883 module.Module.properties.Installable = proptools.BoolPtr(true)
884
Jiyong Park7f7766d2019-07-25 22:02:35 +0900885 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100886 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800887 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900888 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700889 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700890}
891
892//
Colin Crossb628ea52018-08-14 16:42:33 -0700893// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700894//
895
Dan Shi95d19422020-08-15 12:24:26 -0700896// Test option struct.
897type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800898 android.CommonTestOptions
899
Dan Shi95d19422020-08-15 12:24:26 -0700900 // a list of extra test configuration files that should be installed with the module.
901 Extra_test_configs []string `android:"path,arch_variant"`
902}
903
Colin Cross05638fc2018-04-09 18:40:24 -0700904type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700905 // list of compatibility suites (for example "cts", "vts") that the module should be
906 // installed into.
907 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700908
909 // the name of the test configuration (for example "AndroidTest.xml") that should be
910 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800911 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700912
Jack He33338892018-09-19 02:21:28 -0700913 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
914 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800915 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700916
Colin Crossd96ca352018-08-10 16:06:24 -0700917 // list of files or filegroup modules that provide data that should be installed alongside
918 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900919 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700920
921 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
922 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
923 // explicitly.
924 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800925
926 // Add parameterized mainline modules to auto generated test config. The options will be
927 // handled by TradeFed to do downloading and installing the specified modules on the device.
928 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700929
930 // Test options.
931 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800932
933 // Names of modules containing JNI libraries that should be installed alongside the test.
934 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700935
936 // Install the test into a folder named for the module in all test suites.
937 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700938}
939
Liz Kammerdd849a82020-06-12 16:38:45 -0700940type hostTestProperties struct {
941 // list of native binary modules that should be installed alongside the test
942 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000943
944 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000945 // This property only adds the first variant of the dependency
946 Data_device_bins_first []string `android:"arch_variant"`
947
948 // list of device binary modules that should be installed alongside the test
949 // This property adds 64bit AND 32bit variants of the dependency
950 Data_device_bins_both []string `android:"arch_variant"`
951
952 // list of device binary modules that should be installed alongside the test
953 // This property only adds 64bit variants of the dependency
954 Data_device_bins_64 []string `android:"arch_variant"`
955
956 // list of device binary modules that should be installed alongside the test
957 // This property adds 32bit variants of the dependency if available, or else
958 // defaults to the 64bit variant
959 Data_device_bins_prefer32 []string `android:"arch_variant"`
960
961 // list of device binary modules that should be installed alongside the test
962 // This property only adds 32bit variants of the dependency
963 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700964}
965
Paul Duffin42df1442019-03-20 12:45:53 +0000966type testHelperLibraryProperties struct {
967 // list of compatibility suites (for example "cts", "vts") that the module should be
968 // installed into.
969 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700970
971 // Install the test into a folder named for the module in all test suites.
972 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000973}
974
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000975type prebuiltTestProperties struct {
976 // list of compatibility suites (for example "cts", "vts") that the module should be
977 // installed into.
978 Test_suites []string `android:"arch_variant"`
979
980 // the name of the test configuration (for example "AndroidTest.xml") that should be
981 // installed with the module.
982 Test_config *string `android:"path,arch_variant"`
983}
984
Colin Cross05638fc2018-04-09 18:40:24 -0700985type Test struct {
986 Library
987
988 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700989
Dan Shi95d19422020-08-15 12:24:26 -0700990 testConfig android.Path
991 extraTestConfigs android.Paths
992 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700993}
994
Liz Kammerdd849a82020-06-12 16:38:45 -0700995type TestHost struct {
996 Test
997
998 testHostProperties hostTestProperties
999}
1000
Paul Duffin42df1442019-03-20 12:45:53 +00001001type TestHelperLibrary struct {
1002 Library
1003
1004 testHelperLibraryProperties testHelperLibraryProperties
1005}
1006
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001007type JavaTestImport struct {
1008 Import
1009
1010 prebuiltTestProperties prebuiltTestProperties
1011
1012 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001013 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001014}
1015
Colin Cross24cc4be62021-11-03 14:09:41 -07001016func (j *Test) InstallInTestcases() bool {
1017 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1018 // testcases by base_rules.mk.
1019 return !j.Host()
1020}
1021
1022func (j *TestHelperLibrary) InstallInTestcases() bool {
1023 return true
1024}
1025
1026func (j *JavaTestImport) InstallInTestcases() bool {
1027 return true
1028}
1029
Sam Delmericocc271e22022-06-01 15:45:02 +00001030func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1031 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1032 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1033 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1034 }
1035
1036 var maybeAndroid32Target *android.Target
1037 var maybeAndroid64Target *android.Target
1038 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1039 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1040 if len(android32TargetList) > 0 {
1041 maybeAndroid32Target = &android32TargetList[0]
1042 }
1043 if len(android64TargetList) > 0 {
1044 maybeAndroid64Target = &android64TargetList[0]
1045 }
1046
1047 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1048 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1049 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1050 return
1051 }
1052 if maybeAndroid32Target != nil {
1053 ctx.AddFarVariationDependencies(
1054 maybeAndroid32Target.Variations(),
1055 dataDeviceBinsTag,
1056 j.testHostProperties.Data_device_bins_both...,
1057 )
1058 }
1059 if maybeAndroid64Target != nil {
1060 ctx.AddFarVariationDependencies(
1061 maybeAndroid64Target.Variations(),
1062 dataDeviceBinsTag,
1063 j.testHostProperties.Data_device_bins_both...,
1064 )
1065 }
1066 }
1067
1068 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1069 if maybeAndroid32Target != nil {
1070 ctx.AddFarVariationDependencies(
1071 maybeAndroid32Target.Variations(),
1072 dataDeviceBinsTag,
1073 j.testHostProperties.Data_device_bins_prefer32...,
1074 )
1075 } else {
1076 if maybeAndroid64Target == nil {
1077 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1078 return
1079 }
1080 ctx.AddFarVariationDependencies(
1081 maybeAndroid64Target.Variations(),
1082 dataDeviceBinsTag,
1083 j.testHostProperties.Data_device_bins_prefer32...,
1084 )
1085 }
1086 }
1087
1088 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1089 if maybeAndroid32Target == nil {
1090 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1091 return
1092 }
1093 deviceVariations := maybeAndroid32Target.Variations()
1094 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1095 }
1096
1097 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1098 if maybeAndroid64Target == nil {
1099 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1100 return
1101 }
1102 deviceVariations := maybeAndroid64Target.Variations()
1103 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1104 }
1105}
1106
Liz Kammerdd849a82020-06-12 16:38:45 -07001107func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1108 if len(j.testHostProperties.Data_native_bins) > 0 {
1109 for _, target := range ctx.MultiTargets() {
1110 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1111 }
1112 }
1113
Colin Crossf8d9c492021-01-26 11:01:43 -08001114 if len(j.testProperties.Jni_libs) > 0 {
1115 for _, target := range ctx.MultiTargets() {
1116 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1117 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1118 }
1119 }
1120
Sam Delmericocc271e22022-06-01 15:45:02 +00001121 j.addDataDeviceBinsDeps(ctx)
1122
Liz Kammerdd849a82020-06-12 16:38:45 -07001123 j.deps(ctx)
1124}
1125
Yuexi Ma627263f2021-03-04 13:47:56 -08001126func (j *TestHost) AddExtraResource(p android.Path) {
1127 j.extraResources = append(j.extraResources, p)
1128}
1129
Sam Delmericocc271e22022-06-01 15:45:02 +00001130func (j *TestHost) dataDeviceBins() []string {
1131 ret := make([]string, 0,
1132 len(j.testHostProperties.Data_device_bins_first)+
1133 len(j.testHostProperties.Data_device_bins_both)+
1134 len(j.testHostProperties.Data_device_bins_prefer32)+
1135 len(j.testHostProperties.Data_device_bins_32)+
1136 len(j.testHostProperties.Data_device_bins_64),
1137 )
1138
1139 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1140 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1141 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1142 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1143 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1144
1145 return ret
1146}
1147
Sam Delmericob3342ce2022-01-20 21:10:28 +00001148func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1149 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001150 dataDeviceBins := j.dataDeviceBins()
1151 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001152 // add Tradefed configuration to push device bins to device for testing
1153 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1154 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001155 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001156 fullPath := filepath.Join(remoteDir, bin)
1157 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1158 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001159 configs = append(configs, tradefed.Object{
1160 Type: "target_preparer",
1161 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1162 Options: options,
1163 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001164 }
1165
1166 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
1167}
1168
Colin Cross303e21f2018-08-07 16:49:25 -07001169func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001170 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1171}
1172
1173func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001174 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1175 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001176 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001177 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1178 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001179
Dan Shi6ffaaa82019-09-26 11:41:36 -07001180 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001181 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -07001182
Colin Cross8a497952019-03-05 22:25:09 -08001183 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001184
Dan Shi95d19422020-08-15 12:24:26 -07001185 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1186
Liz Kammerdd849a82020-06-12 16:38:45 -07001187 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1188 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1189 })
1190
Sam Delmericob3342ce2022-01-20 21:10:28 +00001191 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1192 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1193 })
1194
Colin Crossf8d9c492021-01-26 11:01:43 -08001195 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1196 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1197 if sharedLibInfo.SharedLibrary != nil {
1198 // Copy to an intermediate output directory to append "lib[64]" to the path,
1199 // so that it's compatible with the default rpath values.
1200 var relPath string
1201 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1202 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1203 } else {
1204 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1205 }
1206 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1207 ctx.Build(pctx, android.BuildParams{
1208 Rule: android.Cp,
1209 Input: sharedLibInfo.SharedLibrary,
1210 Output: relocatedLib,
1211 })
1212 j.data = append(j.data, relocatedLib)
1213 } else {
1214 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1215 }
1216 })
1217
Colin Cross303e21f2018-08-07 16:49:25 -07001218 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001219}
1220
Paul Duffin42df1442019-03-20 12:45:53 +00001221func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1222 j.Library.GenerateAndroidBuildActions(ctx)
1223}
1224
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001225func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1226 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001227 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001228
1229 j.Import.GenerateAndroidBuildActions(ctx)
1230}
1231
1232type testSdkMemberType struct {
1233 android.SdkMemberTypeBase
1234}
1235
Paul Duffin296701e2021-07-14 10:29:36 +01001236func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1237 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001238}
1239
1240func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1241 _, ok := module.(*Test)
1242 return ok
1243}
1244
Paul Duffin3a4eb502020-03-19 16:11:18 +00001245func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1246 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001247}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001248
Paul Duffin14eb4672020-03-02 11:33:02 +00001249func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1250 return &testSdkMemberProperties{}
1251}
1252
1253type testSdkMemberProperties struct {
1254 android.SdkMemberPropertiesBase
1255
Paul Duffina551a1c2020-03-17 21:04:24 +00001256 JarToExport android.Path
1257 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001258}
1259
Paul Duffin3a4eb502020-03-19 16:11:18 +00001260func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001261 test := variant.(*Test)
1262
1263 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001264 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001265 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001266 }
1267
Paul Duffina551a1c2020-03-17 21:04:24 +00001268 p.JarToExport = implementationJars[0]
1269 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001270}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001271
Paul Duffin3a4eb502020-03-19 16:11:18 +00001272func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001273 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001274
Paul Duffina551a1c2020-03-17 21:04:24 +00001275 exportedJar := p.JarToExport
1276 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001277 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001278 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001279
1280 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001281 }
1282
1283 testConfig := p.TestConfig
1284 if testConfig != nil {
1285 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1286 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001287 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1288 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001289}
1290
Colin Cross1b16b0e2019-02-12 14:41:32 -08001291// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1292// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1293//
1294// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1295// compiled against the device bootclasspath.
1296//
1297// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1298// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001299func TestFactory() android.Module {
1300 module := &Test{}
1301
Colin Crossce6734e2020-06-15 16:09:53 -07001302 module.addHostAndDeviceProperties()
1303 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001304
Colin Cross9ae1b922018-06-26 17:59:05 -07001305 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001306 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001307 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001308
Paul Duffinb6b89a42021-05-06 16:33:43 +01001309 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001310 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001311 return module
1312}
1313
Paul Duffin42df1442019-03-20 12:45:53 +00001314// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1315func TestHelperLibraryFactory() android.Module {
1316 module := &TestHelperLibrary{}
1317
Colin Crossce6734e2020-06-15 16:09:53 -07001318 module.addHostAndDeviceProperties()
1319 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001320
Colin Cross9a4abed2019-04-24 13:19:28 -07001321 module.Module.properties.Installable = proptools.BoolPtr(true)
1322 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001323 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001324
Paul Duffin42df1442019-03-20 12:45:53 +00001325 InitJavaModule(module, android.HostAndDeviceSupported)
1326 return module
1327}
1328
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001329// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1330// and makes sure that it is added to the appropriate test suite.
1331//
1332// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1333// compiled against an Android classpath.
1334//
1335// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1336// for host modules.
1337func JavaTestImportFactory() android.Module {
1338 module := &JavaTestImport{}
1339
1340 module.AddProperties(
1341 &module.Import.properties,
1342 &module.prebuiltTestProperties)
1343
1344 module.Import.properties.Installable = proptools.BoolPtr(true)
1345
1346 android.InitPrebuiltModule(module, &module.properties.Jars)
1347 android.InitApexModule(module)
1348 android.InitSdkAwareModule(module)
1349 InitJavaModule(module, android.HostAndDeviceSupported)
1350 return module
1351}
1352
Colin Cross1b16b0e2019-02-12 14:41:32 -08001353// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1354// allow running the test with `atest` or a `TEST_MAPPING` file.
1355//
1356// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1357// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001358func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001359 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001360
Colin Crossce6734e2020-06-15 16:09:53 -07001361 module.addHostProperties()
1362 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001363 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001364
Yuexi Ma627263f2021-03-04 13:47:56 -08001365 InitTestHost(
1366 module,
1367 proptools.BoolPtr(true),
1368 nil,
1369 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001370
Liz Kammerdd849a82020-06-12 16:38:45 -07001371 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001372
Colin Cross05638fc2018-04-09 18:40:24 -07001373 return module
1374}
1375
Yuexi Ma627263f2021-03-04 13:47:56 -08001376func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1377 th.properties.Installable = installable
1378 th.testProperties.Auto_gen_config = autoGenConfig
1379 th.testProperties.Test_suites = testSuites
1380}
1381
Colin Cross05638fc2018-04-09 18:40:24 -07001382//
Colin Cross2fe66872015-03-30 17:20:39 -07001383// Java Binaries (.jar file plus wrapper script)
1384//
1385
Colin Crossf506d872017-07-19 15:53:04 -07001386type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001387 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001388 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001389
1390 // Name of the class containing main to be inserted into the manifest as Main-Class.
1391 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001392
1393 // Names of modules containing JNI libraries that should be installed alongside the host
1394 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001395 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001396}
1397
Colin Crossf506d872017-07-19 15:53:04 -07001398type Binary struct {
1399 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001400
Colin Crossf506d872017-07-19 15:53:04 -07001401 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001402
Colin Cross6b4a32d2017-12-05 13:42:45 -08001403 isWrapperVariant bool
1404
Colin Crossc3315992017-12-08 19:12:36 -08001405 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001406 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001407}
1408
Alex Light24237172017-10-26 09:46:21 -07001409func (j *Binary) HostToolPath() android.OptionalPath {
1410 return android.OptionalPathForPath(j.binaryFile)
1411}
1412
Colin Crossf506d872017-07-19 15:53:04 -07001413func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001414 if ctx.Arch().ArchType == android.Common {
1415 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001416 if j.binaryProperties.Main_class != nil {
1417 if j.properties.Manifest != nil {
1418 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1419 }
1420 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1421 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1422 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1423 }
1424
Colin Cross6b4a32d2017-12-05 13:42:45 -08001425 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001426 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001427 // Handle the binary wrapper
1428 j.isWrapperVariant = true
1429
Colin Cross366938f2017-12-11 16:29:02 -08001430 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001431 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001432 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001433 if ctx.Windows() {
1434 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1435 }
1436
Zi Wangca65b402022-10-10 13:45:06 -07001437 if ctx.Device() {
1438 // device binary should have a main_class property if it does not
1439 // have a specific wrapper, so that a default wrapper can
1440 // be generated for it.
1441 if j.binaryProperties.Main_class == nil {
1442 ctx.PropertyErrorf("main_class", "main_class property "+
1443 "is required for device binary if no default wrapper is assigned")
1444 } else {
1445 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1446 jarName := j.Stem() + ".jar"
1447 partition := j.PartitionTag(ctx.DeviceConfig())
1448 ctx.Build(pctx, android.BuildParams{
1449 Rule: deviceBinaryWrapper,
1450 Output: wrapper,
1451 Args: map[string]string{
1452 "jar_name": jarName,
1453 "partition": partition,
1454 "main_class": String(j.binaryProperties.Main_class),
1455 },
1456 })
1457 j.wrapperFile = wrapper
1458 }
1459 } else {
1460 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1461 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001462 }
1463
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001464 ext := ""
1465 if ctx.Windows() {
1466 ext = ".bat"
1467 }
1468
Colin Crossc179ea62020-10-09 10:54:15 -07001469 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001470 // of the wrapper variant, which will include the common variant's jar file and any JNI
1471 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001472 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001473 ctx.ModuleName()+ext, j.wrapperFile)
1474 }
Colin Cross2fe66872015-03-30 17:20:39 -07001475}
1476
Colin Crossf506d872017-07-19 15:53:04 -07001477func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001478 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001479 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001480 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001481 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001482 // These dependencies ensure the host installation rules will install the jar file and
1483 // the jni libraries when the wrapper is installed.
1484 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1485 ctx.AddVariationDependencies(
1486 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1487 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001488 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001489}
1490
Colin Cross1b16b0e2019-02-12 14:41:32 -08001491// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1492// as well.
1493//
1494// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1495// compiled against the device bootclasspath.
1496//
1497// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1498// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001499func BinaryFactory() android.Module {
1500 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001501
Colin Crossce6734e2020-06-15 16:09:53 -07001502 module.addHostAndDeviceProperties()
1503 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001504
Colin Cross9ae1b922018-06-26 17:59:05 -07001505 module.Module.properties.Installable = proptools.BoolPtr(true)
1506
Colin Cross6b4a32d2017-12-05 13:42:45 -08001507 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1508 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001509 android.InitBazelModule(module)
1510
Colin Cross36242852017-06-23 15:06:31 -07001511 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001512}
1513
Colin Cross1b16b0e2019-02-12 14:41:32 -08001514// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1515//
1516// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1517// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001518func BinaryHostFactory() android.Module {
1519 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001520
Colin Crossce6734e2020-06-15 16:09:53 -07001521 module.addHostProperties()
1522 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001523
Colin Cross9ae1b922018-06-26 17:59:05 -07001524 module.Module.properties.Installable = proptools.BoolPtr(true)
1525
Colin Cross6b4a32d2017-12-05 13:42:45 -08001526 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1527 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001528 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001529 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001530}
1531
1532//
1533// Java prebuilts
1534//
1535
Colin Cross74d73e22017-08-02 11:05:49 -07001536type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001537 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001538
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001539 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1540 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001541 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001542
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001543 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1544 // specified.
1545 Min_sdk_version *string
1546
William Loh5a082f92022-05-17 20:21:50 +00001547 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
1548 // and uses-permission tags in manifest_fixer.
1549 Replace_max_sdk_version_placeholder *string
1550
Colin Cross535e2cf2017-10-20 17:57:49 -07001551 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001552
Paul Duffin869de142021-07-15 14:14:41 +01001553 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001554 Permitted_packages []string
1555
Jiyong Park1be96912018-05-28 18:02:19 +09001556 // List of shared java libs that this module has dependencies to
1557 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001558
1559 // List of files to remove from the jar file(s)
1560 Exclude_files []string
1561
1562 // List of directories to remove from the jar file(s)
1563 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001564
1565 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001566 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001567
1568 // set the name of the output
1569 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001570
1571 Aidl struct {
1572 // directories that should be added as include directories for any aidl sources of modules
1573 // that depend on this module, as well as to aidl for this module.
1574 Export_include_dirs []string
1575 }
Colin Cross74d73e22017-08-02 11:05:49 -07001576}
1577
1578type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001579 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001580 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001581 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001582 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001583 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001584 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001585
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001586 // Functionality common to Module and Import.
1587 embeddableInModuleAndImport
1588
Liz Kammerd6c31d22020-08-05 15:40:41 -07001589 hiddenAPI
1590 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001591 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001592
Colin Cross74d73e22017-08-02 11:05:49 -07001593 properties ImportProperties
1594
Liz Kammerd6c31d22020-08-05 15:40:41 -07001595 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001596 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001597 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001598
Colin Cross0a6e0072017-08-30 14:24:55 -07001599 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001600 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001601 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001602
1603 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001604
1605 sdkVersion android.SdkSpec
1606 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001607}
1608
Paul Duffin630b11e2021-07-15 13:35:26 +01001609var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1610
1611func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1612 return j.properties.Permitted_packages
1613}
1614
Jiyong Park92315372021-04-02 08:45:46 +09001615func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1616 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001617}
1618
Jiyong Parkf1691d22021-03-29 20:11:58 +09001619func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001620 return "none"
1621}
1622
Jiyong Park92315372021-04-02 08:45:46 +09001623func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001624 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001625 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001626 }
Jiyong Park92315372021-04-02 08:45:46 +09001627 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001628}
1629
William Loh5a082f92022-05-17 20:21:50 +00001630func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
1631 if j.properties.Replace_max_sdk_version_placeholder != nil {
1632 return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
1633 }
1634 return android.SdkSpecFrom(ctx, "")
1635}
1636
Jiyong Park92315372021-04-02 08:45:46 +09001637func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1638 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001639}
1640
Colin Cross74d73e22017-08-02 11:05:49 -07001641func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001642 return &j.prebuilt
1643}
1644
Colin Cross74d73e22017-08-02 11:05:49 -07001645func (j *Import) PrebuiltSrcs() []string {
1646 return j.properties.Jars
1647}
1648
1649func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001650 return j.prebuilt.Name(j.ModuleBase.Name())
1651}
1652
Jiyong Park0b238752019-10-29 11:23:10 +09001653func (j *Import) Stem() string {
1654 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1655}
1656
Jiyong Park618922e2020-01-08 13:35:43 +09001657func (a *Import) JacocoReportClassesFile() android.Path {
1658 return nil
1659}
1660
Bill Peckhama41a6962021-01-11 10:58:54 -08001661func (j *Import) LintDepSets() LintDepSets {
1662 return LintDepSets{}
1663}
1664
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001665func (j *Import) getStrictUpdatabilityLinting() bool {
1666 return false
1667}
1668
1669func (j *Import) setStrictUpdatabilityLinting(bool) {
1670}
1671
Colin Cross74d73e22017-08-02 11:05:49 -07001672func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001673 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001674
1675 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001676 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001677 }
Colin Cross1e676be2016-10-12 14:38:15 -07001678}
1679
Sam Delmerico277795c2022-02-25 17:04:37 +00001680func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Paul Duffinc61783b2022-10-20 17:21:40 +01001681 // TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09001682 j.sdkVersion = j.SdkVersion(ctx)
1683 j.minSdkVersion = j.MinSdkVersion(ctx)
1684
Colin Cross56a83212020-09-15 18:30:11 -07001685 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1686 j.hideApexVariantFromMake = true
1687 }
1688
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001689 if ctx.Windows() {
1690 j.HideFromMake()
1691 }
Sam Delmerico277795c2022-02-25 17:04:37 +00001692}
1693
1694func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1695 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001696
Colin Cross8a497952019-03-05 22:25:09 -08001697 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001698
Jiyong Park0b238752019-10-29 11:23:10 +09001699 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001700 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001701 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1702 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001703 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001704 inputFile := outputFile
1705 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1706 TransformJetifier(ctx, outputFile, inputFile)
1707 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001708 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001709 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001710
Liz Kammerd6c31d22020-08-05 15:40:41 -07001711 var flags javaBuilderFlags
1712
Jiyong Park1be96912018-05-28 18:02:19 +09001713 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001714 tag := ctx.OtherModuleDependencyTag(module)
1715
Colin Crossdcf71b22021-02-01 13:59:03 -08001716 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1717 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001718 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001719 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001720 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1721 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1722 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001723 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001724 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001725 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001726 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001727 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001728 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001729 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09001730 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001731 }
1732 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001733
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001734 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001735 })
1736
Sam Delmerico277795c2022-02-25 17:04:37 +00001737 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09001738
1739 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001740
Paul Duffin064b70c2020-11-02 17:32:38 +00001741 if ctx.Device() {
1742 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1743 // obtained from the associated deapexer module.
1744 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1745 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001746 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001747 di := android.FindDeapexerProviderForModule(ctx)
1748 if di == nil {
1749 return // An error has been reported by FindDeapexerProviderForModule.
1750 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001751 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001752 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1753 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001754 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1755 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001756
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001757 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001758 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001759 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1760 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001761
1762 // Initialize the hiddenapi structure.
1763 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001764 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001765 // This should never happen as a variant for a prebuilt_apex is only created if the
1766 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001767 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001768 }
1769 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001770 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001771 if sdkDep.invalidVersion {
1772 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1773 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1774 } else if sdkDep.useFiles {
1775 // sdkDep.jar is actually equivalent to turbine header.jar.
1776 flags.classpath = append(flags.classpath, sdkDep.jars...)
1777 }
1778
1779 // Dex compilation
1780
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001781 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1782 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001783 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001784 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1785
Paul Duffin612e6102021-02-02 13:38:13 +00001786 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001787 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001788 if ctx.Failed() {
1789 return
1790 }
1791
Paul Duffin74d18d12021-05-14 14:18:47 +01001792 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001793 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001794
1795 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001796 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001797
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001798 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001799 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001800 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001801 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001802
1803 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1804 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1805 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1806 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1807 AidlIncludeDirs: j.exportAidlIncludeDirs,
1808 })
Colin Cross2fe66872015-03-30 17:20:39 -07001809}
1810
Sam Delmerico277795c2022-02-25 17:04:37 +00001811func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
1812 if !Bool(j.properties.Installable) {
1813 return
1814 }
1815
1816 var installDir android.InstallPath
1817 if ctx.InstallInTestcases() {
1818 var archDir string
1819 if !ctx.Host() {
1820 archDir = ctx.DeviceConfig().DeviceArch()
1821 }
1822 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1823 } else {
1824 installDir = android.PathForModuleInstall(ctx, "framework")
1825 }
1826 ctx.InstallFile(installDir, jarName, outputFile)
1827}
1828
Paul Duffinaa55f742020-10-06 17:20:13 +01001829func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1830 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001831 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001832 return android.Paths{j.combinedClasspathFile}, nil
1833 default:
1834 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1835 }
1836}
1837
1838var _ android.OutputFileProducer = (*Import)(nil)
1839
Nan Zhanged19fc32017-10-19 13:06:22 -07001840func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001841 if j.combinedClasspathFile == nil {
1842 return nil
1843 }
Colin Cross37f6d792018-07-12 12:28:41 -07001844 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001845}
1846
Colin Cross331a1212018-08-15 20:40:52 -07001847func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001848 if j.combinedClasspathFile == nil {
1849 return nil
1850 }
Colin Cross331a1212018-08-15 20:40:52 -07001851 return android.Paths{j.combinedClasspathFile}
1852}
1853
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001854func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001855 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001856}
1857
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001858func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001859 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001860}
1861
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001862func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1863 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001864}
1865
Jiyong Park45bf82e2020-12-15 22:29:02 +09001866var _ android.ApexModule = (*Import)(nil)
1867
1868// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001869func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001870 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001871}
1872
Jiyong Park45bf82e2020-12-15 22:29:02 +09001873// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001874func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1875 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001876 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001877 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001878 return fmt.Errorf("min_sdk_version is not specified")
1879 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001880 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001881 return nil
1882 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001883 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1884 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001885 }
Jooyung Han749dc692020-04-15 11:03:39 +09001886 return nil
1887}
1888
Paul Duffinfef55002021-06-17 14:56:05 +01001889// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1890// java_sdk_library_import with the specified base module name requires to be exported from a
1891// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001892func requiredFilesFromPrebuiltApexForImport(name string) []string {
1893 // Add the dex implementation jar to the set of exported files.
1894 return []string{
1895 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001896 }
1897}
1898
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001899// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1900// the java library with the specified name.
1901func apexRootRelativePathToJavaLib(name string) string {
1902 return filepath.Join("javalib", name+".jar")
1903}
1904
Paul Duffinfef55002021-06-17 14:56:05 +01001905var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1906
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001907func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001908 name := j.BaseModuleName()
1909 return requiredFilesFromPrebuiltApexForImport(name)
1910}
1911
albaltai36ff7dc2018-12-25 14:35:23 +08001912// Add compile time check for interface implementation
1913var _ android.IDEInfo = (*Import)(nil)
1914var _ android.IDECustomizedModuleName = (*Import)(nil)
1915
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001916// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001917
1918func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1919 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1920}
1921
1922func (j *Import) IDECustomizedModuleName() string {
1923 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1924 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1925 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001926 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001927}
1928
Colin Cross74d73e22017-08-02 11:05:49 -07001929var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001930
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001931func (j *Import) IsInstallable() bool {
1932 return Bool(j.properties.Installable)
1933}
1934
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001935var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001936
Colin Cross1b16b0e2019-02-12 14:41:32 -08001937// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1938//
1939// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1940// compiled against an Android classpath.
1941//
1942// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1943// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001944func ImportFactory() android.Module {
1945 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001946
Liz Kammerd6c31d22020-08-05 15:40:41 -07001947 module.AddProperties(
1948 &module.properties,
1949 &module.dexer.dexProperties,
1950 )
Colin Cross74d73e22017-08-02 11:05:49 -07001951
Paul Duffin71b33cc2021-06-23 11:39:47 +01001952 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001953
Liz Kammerd6c31d22020-08-05 15:40:41 -07001954 module.dexProperties.Optimize.EnabledByDefault = false
1955
Colin Cross74d73e22017-08-02 11:05:49 -07001956 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001957 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001958 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001959 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001960 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001961 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001962}
1963
Colin Cross1b16b0e2019-02-12 14:41:32 -08001964// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1965// module.
1966//
1967// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1968// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001969func ImportFactoryHost() android.Module {
1970 module := &Import{}
1971
1972 module.AddProperties(&module.properties)
1973
1974 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001975 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001976 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001977 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001978 return module
1979}
1980
Colin Cross42be7612019-02-21 18:12:14 -08001981// dex_import module
1982
1983type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001984 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001985
1986 // set the name of the output
1987 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001988}
1989
1990type DexImport struct {
1991 android.ModuleBase
1992 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001993 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001994 prebuilt android.Prebuilt
1995
1996 properties DexImportProperties
1997
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001998 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001999
2000 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07002001
2002 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08002003}
2004
2005func (j *DexImport) Prebuilt() *android.Prebuilt {
2006 return &j.prebuilt
2007}
2008
2009func (j *DexImport) PrebuiltSrcs() []string {
2010 return j.properties.Jars
2011}
2012
2013func (j *DexImport) Name() string {
2014 return j.prebuilt.Name(j.ModuleBase.Name())
2015}
2016
Jiyong Park0b238752019-10-29 11:23:10 +09002017func (j *DexImport) Stem() string {
2018 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2019}
2020
Jiyong Park77acec62020-06-01 21:39:15 +09002021func (a *DexImport) JacocoReportClassesFile() android.Path {
2022 return nil
2023}
2024
Colin Cross08dca382020-07-21 20:31:17 -07002025func (a *DexImport) LintDepSets() LintDepSets {
2026 return LintDepSets{}
2027}
2028
Martin Stjernholm6d415272020-01-31 17:10:36 +00002029func (j *DexImport) IsInstallable() bool {
2030 return true
2031}
2032
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002033func (j *DexImport) getStrictUpdatabilityLinting() bool {
2034 return false
2035}
2036
2037func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2038}
2039
Colin Cross42be7612019-02-21 18:12:14 -08002040func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2041 if len(j.properties.Jars) != 1 {
2042 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2043 }
2044
Colin Cross56a83212020-09-15 18:30:11 -07002045 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
2046 if !apexInfo.IsForPlatform() {
2047 j.hideApexVariantFromMake = true
2048 }
2049
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002050 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2051 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08002052 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
2053
2054 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2055 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2056
2057 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002058 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002059
2060 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2061 rule.Temporary(temporary)
2062
2063 // use zip2zip to uncompress classes*.dex files
2064 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002065 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002066 FlagWithInput("-i ", inputJar).
2067 FlagWithOutput("-o ", temporary).
2068 FlagWithArg("-0 ", "'classes*.dex'")
2069
2070 // use zipalign to align uncompressed classes*.dex files
2071 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002072 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002073 Flag("-f").
2074 Text("4").
2075 Input(temporary).
2076 Output(dexOutputFile)
2077
2078 rule.DeleteTemporaryFiles()
2079
Colin Crossf1a035e2020-11-16 17:32:30 -08002080 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002081 } else {
2082 ctx.Build(pctx, android.BuildParams{
2083 Rule: android.Cp,
2084 Input: inputJar,
2085 Output: dexOutputFile,
2086 })
2087 }
2088
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002089 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002090
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002091 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002092
Colin Cross56a83212020-09-15 18:30:11 -07002093 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002094 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2095 j.Stem()+".jar", dexOutputFile)
2096 }
Colin Cross42be7612019-02-21 18:12:14 -08002097}
2098
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002099func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002100 return j.dexJarFile
2101}
2102
Jiyong Park45bf82e2020-12-15 22:29:02 +09002103var _ android.ApexModule = (*DexImport)(nil)
2104
2105// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002106func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2107 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002108 // we don't check prebuilt modules for sdk_version
2109 return nil
2110}
2111
Colin Cross42be7612019-02-21 18:12:14 -08002112// dex_import imports a `.jar` file containing classes.dex files.
2113//
2114// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2115// to the device.
2116func DexImportFactory() android.Module {
2117 module := &DexImport{}
2118
2119 module.AddProperties(&module.properties)
2120
2121 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002122 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002123 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002124 return module
2125}
2126
Colin Cross89536d42017-07-07 14:35:50 -07002127// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002128type Defaults struct {
2129 android.ModuleBase
2130 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002131 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002132}
2133
Colin Cross1b16b0e2019-02-12 14:41:32 -08002134// java_defaults provides a set of properties that can be inherited by other java or android modules.
2135//
2136// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2137// property in the defaults module that exists in the depending module will be prepended to the depending module's
2138// value for that property.
2139//
2140// Example:
2141//
Sam Delmerico277795c2022-02-25 17:04:37 +00002142// java_defaults {
2143// name: "example_defaults",
2144// srcs: ["common/**/*.java"],
2145// javacflags: ["-Xlint:all"],
2146// aaptflags: ["--auto-add-overlay"],
2147// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002148//
Sam Delmerico277795c2022-02-25 17:04:37 +00002149// java_library {
2150// name: "example",
2151// defaults: ["example_defaults"],
2152// srcs: ["example/**/*.java"],
2153// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002154//
2155// is functionally identical to:
2156//
Sam Delmerico277795c2022-02-25 17:04:37 +00002157// java_library {
2158// name: "example",
2159// srcs: [
2160// "common/**/*.java",
2161// "example/**/*.java",
2162// ],
2163// javacflags: ["-Xlint:all"],
2164// }
Paul Duffin47357662019-12-05 14:07:14 +00002165func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002166 module := &Defaults{}
2167
Colin Cross89536d42017-07-07 14:35:50 -07002168 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002169 &CommonProperties{},
2170 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002171 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002172 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002173 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002174 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002175 &aaptProperties{},
2176 &androidLibraryProperties{},
2177 &appProperties{},
2178 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002179 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002180 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002181 &ImportProperties{},
2182 &AARImportProperties{},
2183 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002184 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002185 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002186 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002187 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002188 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002189 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002190 )
2191
2192 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002193 return module
2194}
Nan Zhangea568a42017-11-08 21:20:04 -08002195
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002196func kytheExtractJavaFactory() android.Singleton {
2197 return &kytheExtractJavaSingleton{}
2198}
2199
2200type kytheExtractJavaSingleton struct {
2201}
2202
2203func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2204 var xrefTargets android.Paths
2205 ctx.VisitAllModules(func(module android.Module) {
2206 if javaModule, ok := module.(xref); ok {
2207 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2208 }
2209 })
2210 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2211 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002212 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002213 }
2214}
2215
Nan Zhangea568a42017-11-08 21:20:04 -08002216var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002217var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002218var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08002219var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002220
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002221// Add class loader context (CLC) of a given dependency to the current CLC.
2222func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2223 clcMap dexpreopt.ClassLoaderContextMap) {
2224
2225 dep, ok := depModule.(UsesLibraryDependency)
2226 if !ok {
2227 return
2228 }
2229
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002230 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2231
2232 var sdkLib *string
2233 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2234 // A shared SDK library. This should be added as a top-level CLC element.
2235 sdkLib = &depName
2236 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2237 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2238 // property. This should be handled in the same way as a shared SDK library.
2239 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002240 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002241
2242 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002243 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002244 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002245 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2246 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002247 } else if depTag == staticLibTag {
2248 // Propagate <uses-library> through static library dependencies, unless it is a component
2249 // library (such as stubs). Component libraries have a dependency on their SDK library,
2250 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002251 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002252 return
2253 }
2254 } else {
2255 // Don't propagate <uses-library> for other dependency tags.
2256 return
2257 }
2258
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002259 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2260 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2261 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2262 // from its CLC should be added to the current CLC.
2263 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002264 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002265 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002266 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002267 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2268 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002269}
Wei Libafb6d62021-12-10 03:14:59 -08002270
Sam Delmerico79985812022-03-23 20:20:42 +00002271type javaResourcesAttributes struct {
2272 Resources bazel.LabelListAttribute
2273 Resource_strip_prefix *string
2274}
2275
2276func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
2277 var resources bazel.LabelList
2278 var resourceStripPrefix *string
2279
2280 if m.properties.Java_resources != nil {
2281 resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
2282 }
2283
Paul Duffinc61783b2022-10-20 17:21:40 +01002284 // TODO(b/179889880) handle case where glob includes files outside package
Sam Delmerico79985812022-03-23 20:20:42 +00002285 resDeps := ResourceDirsToFiles(
2286 ctx,
2287 m.properties.Java_resource_dirs,
2288 m.properties.Exclude_java_resource_dirs,
2289 m.properties.Exclude_java_resources,
2290 )
2291
2292 for i, resDep := range resDeps {
2293 dir, files := resDep.dir, resDep.files
2294
2295 resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
2296
2297 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2298 // inside the JAR file, so we need to remove that prefix
2299 resourceStripPrefix = proptools.StringPtr(dir.String())
2300 if i > 0 {
2301 // TODO(b/226423379) allow multiple resource prefixes
2302 ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
2303 }
2304 }
2305
2306 return &javaResourcesAttributes{
2307 Resources: bazel.MakeLabelListAttribute(resources),
2308 Resource_strip_prefix: resourceStripPrefix,
2309 }
2310}
2311
Sam Delmericoc0161432022-02-25 21:34:51 +00002312type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002313 *javaResourcesAttributes
Wei Libafb6d62021-12-10 03:14:59 -08002314 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002315 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002316 Javacopts bazel.StringListAttribute
2317}
2318
Sam Delmericoc0161432022-02-25 21:34:51 +00002319type javaDependencyLabels struct {
2320 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2321 Deps bazel.LabelListAttribute
2322 // Dependencies which DO contribute to the API visible to upstream dependencies.
2323 StaticDeps bazel.LabelListAttribute
2324}
2325
Sam Delmerico24da73c2022-03-16 20:36:54 +00002326type eventLogTagsAttributes struct {
2327 Srcs bazel.LabelListAttribute
2328}
2329
Sam Delmerico97bd1272022-08-25 14:45:31 -04002330type aidlLibraryAttributes struct {
2331 Srcs bazel.LabelListAttribute
2332}
2333
2334type javaAidlLibraryAttributes struct {
2335 Deps bazel.LabelListAttribute
2336}
2337
2338// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
2339// and also separates dependencies into dynamic dependencies and static dependencies.
2340// Each corresponding Bazel target type, can have a different method for handling
2341// dynamic vs. static dependencies, and so these are returned to the calling function.
Sam Delmericoc0161432022-02-25 21:34:51 +00002342func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002343 var srcs bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002344 var deps bazel.LabelList
2345 var staticDeps bazel.LabelList
2346
Sam Delmericoe91d0302022-02-23 15:28:33 +00002347 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2348 for axis, configToProps := range archVariantProps {
2349 for config, _props := range configToProps {
2350 if archProps, ok := _props.(*CommonProperties); ok {
2351 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2352 srcs.SetSelectValue(axis, config, archSrcs)
2353 }
2354 }
2355 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002356
2357 javaSrcPartition := "java"
2358 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002359 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002360 aidlSrcPartition := "aidl"
Sam Delmericoc7681022022-02-04 21:01:20 +00002361 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002362 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2363 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2364 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04002365 aidlSrcPartition: android.AidlSrcLabelPartition,
Sam Delmericoc7681022022-02-04 21:01:20 +00002366 })
2367
Sam Delmerico24da73c2022-03-16 20:36:54 +00002368 javaSrcs := srcPartitions[javaSrcPartition]
2369
Sam Delmerico24da73c2022-03-16 20:36:54 +00002370 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2371 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002372 ctx.CreateBazelTargetModule(
2373 bazel.BazelTargetModuleProperties{
2374 Rule_class: "event_log_tags",
Sam Delmerico48af73b2022-04-05 14:03:11 +00002375 Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
Sam Delmerico24da73c2022-03-16 20:36:54 +00002376 },
2377 android.CommonAttributes{Name: logtagsLibName},
2378 &eventLogTagsAttributes{
2379 Srcs: srcPartitions[logtagSrcPartition],
2380 },
2381 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04002382
2383 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2384 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00002385 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002386
2387 if !srcPartitions[aidlSrcPartition].IsEmpty() {
2388 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
2389 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
2390 })
2391
2392 if !aidlSrcs.IsEmpty() {
2393 aidlLibName := m.Name() + "_aidl_library"
2394 ctx.CreateBazelTargetModule(
2395 bazel.BazelTargetModuleProperties{
2396 Rule_class: "aidl_library",
2397 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
2398 },
2399 android.CommonAttributes{Name: aidlLibName},
2400 &aidlLibraryAttributes{
2401 Srcs: aidlSrcs,
2402 },
2403 )
2404 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
2405 }
2406
2407 javaAidlLibName := m.Name() + "_java_aidl_library"
2408 ctx.CreateBazelTargetModule(
2409 bazel.BazelTargetModuleProperties{
2410 Rule_class: "java_aidl_library",
2411 Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
2412 },
2413 android.CommonAttributes{Name: javaAidlLibName},
2414 &javaAidlLibraryAttributes{
2415 Deps: aidlLibs,
2416 },
2417 )
2418
2419 staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
2420 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00002421
Sam Delmerico58614c02022-03-15 21:02:09 +00002422 var javacopts []string
2423 if m.properties.Javacflags != nil {
2424 javacopts = append(javacopts, m.properties.Javacflags...)
2425 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002426 if m.properties.Java_version != nil {
2427 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2428 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2429 }
2430
Sam Delmerico58614c02022-03-15 21:02:09 +00002431 epEnabled := m.properties.Errorprone.Enabled
Paul Duffinc61783b2022-10-20 17:21:40 +01002432 // TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
Sam Delmerico58614c02022-03-15 21:02:09 +00002433 if Bool(epEnabled) {
2434 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2435 }
2436
Sam Delmericoc0161432022-02-25 21:34:51 +00002437 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00002438 Srcs: javaSrcs,
2439 javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
Sam Delmerico77267c72022-03-18 14:11:07 +00002440 Plugins: bazel.MakeLabelListAttribute(
2441 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2442 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002443 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002444 }
2445
2446 if m.properties.Libs != nil {
Alixb4e09a02022-09-27 15:36:01 +00002447
2448 // TODO 244210934 ALIX Check if this else statement breaks presubmits get rid of it if it doesn't
2449 if strings.HasPrefix(ctx.ModuleType(), "java_binary") {
2450 for _, d := range m.properties.Libs {
2451 neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
2452 neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
2453 deps.Add(&neverlinkLabel)
2454 }
2455
2456 } else {
2457 deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
2458 }
Wei Libafb6d62021-12-10 03:14:59 -08002459 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002460
Sam Delmericofde9fb52022-01-28 20:53:38 +00002461 if m.properties.Static_libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002462 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002463 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002464
Sam Delmericoc0161432022-02-25 21:34:51 +00002465 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2466 // Soong does not differentiate between a java_library and the Bazel equivalent of
2467 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2468 // listed directly in the srcs of a java_library, and the classes produced
2469 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2470 // that depend on a java_library with proto sources can link directly to the protobuf API,
2471 // and so this should be a static dependency.
2472 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002473
Sam Delmerico97bd1272022-08-25 14:45:31 -04002474 depLabels := &javaDependencyLabels{}
Sam Delmericoc0161432022-02-25 21:34:51 +00002475 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2476 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002477
Sam Delmericoc0161432022-02-25 21:34:51 +00002478 return commonAttrs, depLabels
2479}
2480
2481type javaLibraryAttributes struct {
2482 *javaCommonAttributes
Alixb4e09a02022-09-27 15:36:01 +00002483 Deps bazel.LabelListAttribute
2484 Exports bazel.LabelListAttribute
2485 Neverlink bazel.BoolAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002486}
2487
2488func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002489 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2490
2491 deps := depLabels.Deps
2492 if !commonAttrs.Srcs.IsEmpty() {
2493 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2494
2495 sdkVersion := m.SdkVersion(ctx)
2496 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2497 // TODO(b/220869005) remove forced dependency on current public android.jar
2498 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2499 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002500 } else if !deps.IsEmpty() {
Sam Delmericoc0161432022-02-25 21:34:51 +00002501 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2502 }
2503
2504 attrs := &javaLibraryAttributes{
2505 javaCommonAttributes: commonAttrs,
2506 Deps: deps,
2507 Exports: depLabels.StaticDeps,
2508 }
Wei Libafb6d62021-12-10 03:14:59 -08002509
2510 props := bazel.BazelTargetModuleProperties{
2511 Rule_class: "java_library",
2512 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2513 }
2514
Alixb4e09a02022-09-27 15:36:01 +00002515 name := m.Name()
2516 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
Wei Libafb6d62021-12-10 03:14:59 -08002517}
2518
2519type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002520 *javaCommonAttributes
2521 Deps bazel.LabelListAttribute
2522 Runtime_deps bazel.LabelListAttribute
2523 Main_class string
2524 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002525}
2526
2527// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2528func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002529 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2530
2531 deps := depLabels.Deps
2532 deps.Append(depLabels.StaticDeps)
2533 if m.binaryProperties.Jni_libs != nil {
2534 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2535 }
2536
2537 var runtimeDeps bazel.LabelListAttribute
2538 if commonAttrs.Srcs.IsEmpty() {
2539 // if there are no sources, then the dependencies can only be used at runtime
2540 runtimeDeps = deps
2541 deps = bazel.LabelListAttribute{}
2542 }
2543
Wei Libafb6d62021-12-10 03:14:59 -08002544 mainClass := ""
2545 if m.binaryProperties.Main_class != nil {
2546 mainClass = *m.binaryProperties.Main_class
2547 }
2548 if m.properties.Manifest != nil {
2549 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2550 if err != nil {
2551 return
2552 }
2553 mainClass = mainClassInManifest
2554 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002555
Wei Libafb6d62021-12-10 03:14:59 -08002556 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002557 javaCommonAttributes: commonAttrs,
2558 Deps: deps,
2559 Runtime_deps: runtimeDeps,
2560 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002561 }
2562
2563 // Attribute jvm_flags
2564 if m.binaryProperties.Jni_libs != nil {
2565 jniLibPackages := map[string]bool{}
2566 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2567 jniLibPackage := jniLibLabel.Label
2568 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2569 if indexOfColon > 0 {
2570 // JNI lib from other package
2571 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2572 } else if indexOfColon == 0 {
2573 // JNI lib in the same package of java_binary
2574 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2575 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2576 }
2577 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2578 jniLibPackages[jniLibPackage] = true
2579 }
2580 }
2581 jniLibPaths := []string{}
2582 for jniLibPackage, _ := range jniLibPackages {
2583 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2584 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2585 }
2586 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2587 }
2588
2589 props := bazel.BazelTargetModuleProperties{
2590 Rule_class: "java_binary",
2591 }
2592
2593 // Create the BazelTargetModule.
2594 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2595}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002596
2597type bazelJavaImportAttributes struct {
Alixb4e09a02022-09-27 15:36:01 +00002598 Jars bazel.LabelListAttribute
2599 Exports bazel.LabelListAttribute
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002600}
2601
2602// java_import bp2Build converter.
2603func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002604 var jars bazel.LabelListAttribute
2605 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2606 for axis, configToProps := range archVariantProps {
2607 for config, _props := range configToProps {
2608 if archProps, ok := _props.(*ImportProperties); ok {
2609 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2610 jars.SetSelectValue(axis, config, archJars)
2611 }
2612 }
2613 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002614
2615 attrs := &bazelJavaImportAttributes{
2616 Jars: jars,
2617 }
2618 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2619
Alixb4e09a02022-09-27 15:36:01 +00002620 name := android.RemoveOptionalPrebuiltPrefix(i.Name())
2621
2622 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
2623
2624 neverlink := true
2625 neverlinkAttrs := &javaLibraryAttributes{
2626 Neverlink: bazel.BoolAttribute{Value: &neverlink},
2627 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
2628 }
2629 ctx.CreateBazelTargetModule(bazel.BazelTargetModuleProperties{Rule_class: "java_library"}, android.CommonAttributes{Name: name + "-neverlink"}, neverlinkAttrs)
2630
Sam Delmerico277795c2022-02-25 17:04:37 +00002631}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002632
Sam Delmerico277795c2022-02-25 17:04:37 +00002633var _ android.MixedBuildBuildable = (*Import)(nil)
2634
2635func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
2636 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
2637}
2638
2639func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
2640 i.commonBuildActions(ctx)
2641
2642 bazelCtx := ctx.Config().BazelContext
2643 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
2644 if err != nil {
2645 ctx.ModuleErrorf(err.Error())
2646 return
2647 }
2648
2649 bazelJars := android.Paths{}
2650 for _, bazelOutputFile := range filePaths {
2651 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
2652 }
2653
2654 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
2655 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
2656 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
2657 android.OptionalPath{}, // manifest
2658 false, // stripDirEntries
2659 []string{}, // filesToStrip
2660 []string{}, // dirsToStrip
2661 )
2662 i.combinedClasspathFile = outputFile
2663
2664 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2665 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
2666 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
2667 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
Paul Duffinc61783b2022-10-20 17:21:40 +01002668 // TODO(b/240308299) include AIDL information from Bazel
Sam Delmerico277795c2022-02-25 17:04:37 +00002669 })
2670
2671 i.maybeInstall(ctx, jarName, outputFile)
2672}
2673
2674func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
2675 bazelCtx := ctx.Config().BazelContext
2676 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
2677}
2678
2679func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
2680 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002681}