blob: d04e52a2c9aedf3706b728a55edf9aead8bde518 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17// This file contains the module types for compiling Java for Android, and converts the properties
Colin Cross46c9b8b2017-06-22 16:51:17 -070018// into the flags and filenames necessary to pass to the Module. The final creation of the rules
Colin Cross2fe66872015-03-30 17:20:39 -070019// is handled in builder.go
20
21import (
Colin Crossf19b9bb2018-03-26 14:42:44 -070022 "fmt"
Colin Crossfc3674a2017-09-18 17:41:52 -070023 "path/filepath"
Wei Libafb6d62021-12-10 03:14:59 -080024 "strings"
Colin Cross2fe66872015-03-30 17:20:39 -070025
Wei Libafb6d62021-12-10 03:14:59 -080026 "android/soong/bazel"
Sam Delmerico277795c2022-02-25 17:04:37 +000027 "android/soong/bazel/cquery"
Sam Delmerico4e272292022-01-06 20:03:51 +000028
Colin Cross2fe66872015-03-30 17:20:39 -070029 "github.com/google/blueprint"
Colin Cross76b5f0c2017-08-29 16:02:06 -070030 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070031
Colin Cross635c3b02016-05-18 15:37:25 -070032 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080033 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010034 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070035 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070036 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070037)
38
Colin Cross463a90e2015-06-17 14:20:06 -070039func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010040 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000041
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080042 RegisterJavaSdkMemberTypes()
43}
44
Paul Duffin535e0a12021-03-30 23:34:32 +010045func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080046 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
47
48 ctx.RegisterModuleType("java_library", LibraryFactory)
49 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
50 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
51 ctx.RegisterModuleType("java_binary", BinaryFactory)
52 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
53 ctx.RegisterModuleType("java_test", TestFactory)
54 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
55 ctx.RegisterModuleType("java_test_host", TestHostFactory)
56 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
57 ctx.RegisterModuleType("java_import", ImportFactory)
58 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
59 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
60 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
61 ctx.RegisterModuleType("dex_import", DexImportFactory)
62
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010063 // This mutator registers dependencies on dex2oat for modules that should be
64 // dexpreopted. This is done late when the final variants have been
65 // established, to not get the dependencies split into the wrong variants and
66 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080067 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
68 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040069 // needs access to ApexInfoProvider which is available after variant creation
70 ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080071 })
72
73 ctx.RegisterSingletonType("logtags", LogtagsSingleton)
74 ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
75}
76
77func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000078 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000079 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010080 android.RegisterSdkMemberType(javaLibsSdkMemberType)
81 android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
Jiakai Zhangea180332021-09-26 08:58:02 +000082 android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010083 android.RegisterSdkMemberType(javaTestSdkMemberType)
84}
85
86var (
87 // Supports adding java header libraries to module_exports and sdk.
88 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
89 android.SdkMemberTypeBase{
90 PropertyName: "java_header_libs",
91 SupportsSdk: true,
92 },
93 func(_ android.SdkMemberContext, j *Library) android.Path {
94 headerJars := j.HeaderJars()
95 if len(headerJars) != 1 {
96 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
97 }
98
99 return headerJars[0]
100 },
101 sdkSnapshotFilePathForJar,
102 copyEverythingToSnapshot,
103 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000104
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000105 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100106 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000107 implementationJars := j.ImplementationAndResourcesJars()
108 if len(implementationJars) != 1 {
109 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
110 }
111 return implementationJars[0]
112 }
113
Paul Duffin2da04242021-04-23 19:43:28 +0100114 // Supports adding java implementation libraries to module_exports but not sdk.
115 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000116 android.SdkMemberTypeBase{
117 PropertyName: "java_libs",
118 },
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000119 exportImplementationClassesJar,
Paul Duffindb170e42020-12-08 17:48:25 +0000120 sdkSnapshotFilePathForJar,
121 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100122 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000123
Paul Duffin13648912022-07-15 13:12:35 +0000124 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
125 // In the S build the build will break if updatable-media does not provide a full implementation
126 // jar. That issue was fixed in Tiramisu by b/229932396.
127 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
128 return true
129 }
130
131 return false
132 }
133
Paul Duffin2da04242021-04-23 19:43:28 +0100134 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000135 //
136 // The build has some implicit dependencies (via the boot jars configuration) on a number of
137 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
138 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
139 // used outside those mainline modules.
140 //
141 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
142 // either java_libs, or java_header_libs would end up exporting more information than was strictly
143 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
144 // sdk/module_exports without exposing any unnecessary information.
Paul Duffin2da04242021-04-23 19:43:28 +0100145 javaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffindb170e42020-12-08 17:48:25 +0000146 android.SdkMemberTypeBase{
147 PropertyName: "java_boot_libs",
148 SupportsSdk: true,
149 },
Paul Duffin5c211452021-07-15 12:42:44 +0100150 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000151 if snapshotRequiresImplementationJar(ctx) {
152 return exportImplementationClassesJar(ctx, j)
153 }
154
Paul Duffin5c211452021-07-15 12:42:44 +0100155 // Java boot libs are only provided in the SDK to provide access to their dex implementation
156 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
157 // actual implementation jar but the java_import will need a file that exists so just copy an
158 // empty file. Any attempt to use that file as a jar will cause a build error.
159 return ctx.SnapshotBuilder().EmptyFile()
160 },
Paul Duffin13648912022-07-15 13:12:35 +0000161 func(ctx android.SdkMemberContext, osPrefix, name string) string {
162 if snapshotRequiresImplementationJar(ctx) {
163 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
164 }
165
Paul Duffin5c211452021-07-15 12:42:44 +0100166 // Create a special name for the implementation jar to try and provide some useful information
167 // to a developer that attempts to compile against this.
168 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
169 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
170 },
Paul Duffindb170e42020-12-08 17:48:25 +0000171 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100172 }
Paul Duffindb170e42020-12-08 17:48:25 +0000173
Jiakai Zhangea180332021-09-26 08:58:02 +0000174 // Supports adding java systemserver libraries to module_exports and sdk.
175 //
176 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
177 // of modules that are part of the java systemserver classpath and which are provided by mainline
178 // modules but which are not otherwise used outside those mainline modules.
179 //
180 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
181 // either java_libs, or java_header_libs would end up exporting more information than was strictly
182 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
183 // the sdk/module_exports without exposing any unnecessary information.
184 javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
185 android.SdkMemberTypeBase{
186 PropertyName: "java_systemserver_libs",
187 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000188
189 // This was only added in Tiramisu.
190 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000191 },
192 func(ctx android.SdkMemberContext, j *Library) android.Path {
193 // Java systemserver libs are only provided in the SDK to provide access to their dex
194 // implementation jar for use by dexpreopting. They do not need to provide an actual
195 // implementation jar but the java_import will need a file that exists so just copy an empty
196 // file. Any attempt to use that file as a jar will cause a build error.
197 return ctx.SnapshotBuilder().EmptyFile()
198 },
Paul Duffin13648912022-07-15 13:12:35 +0000199 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000200 // Create a special name for the implementation jar to try and provide some useful information
201 // to a developer that attempts to compile against this.
202 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
203 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
204 },
205 onlyCopyJarToSnapshot,
206 }
207
Paul Duffin2da04242021-04-23 19:43:28 +0100208 // Supports adding java test libraries to module_exports but not sdk.
209 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000210 SdkMemberTypeBase: android.SdkMemberTypeBase{
211 PropertyName: "java_tests",
212 },
Paul Duffin2da04242021-04-23 19:43:28 +0100213 }
214)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900215
Colin Crossdcf71b22021-02-01 13:59:03 -0800216// JavaInfo contains information about a java module for use by modules that depend on it.
217type JavaInfo struct {
218 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
219 // against this module. If empty, ImplementationJars should be used instead.
220 HeaderJars android.Paths
221
222 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
223 // in the module as well as any resources included in the module.
224 ImplementationAndResourcesJars android.Paths
225
226 // ImplementationJars is a list of jars that contain the implementations of classes in the
227 //module.
228 ImplementationJars android.Paths
229
230 // ResourceJars is a list of jars that contain the resources included in the module.
231 ResourceJars android.Paths
232
233 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
234 // depending on this module.
235 AidlIncludeDirs android.Paths
236
237 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
238 // module.
239 SrcJarArgs []string
240
241 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
242 SrcJarDeps android.Paths
243
244 // ExportedPlugins is a list of paths that should be used as annotation processors for any
245 // module that depends on this module.
246 ExportedPlugins android.Paths
247
248 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
249 // any module that depends on this module.
250 ExportedPluginClasses []string
251
252 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
253 // requiring disbling turbine for any modules that depend on it.
254 ExportedPluginDisableTurbine bool
255
256 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
257 // instrumented by jacoco.
258 JacocoReportClassesFile android.Path
259}
260
261var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
262
Colin Cross75ce9ec2021-02-26 16:20:32 -0800263// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
264// the sysprop implementation library.
265type SyspropPublicStubInfo struct {
266 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
267 // the sysprop implementation library.
268 JavaInfo JavaInfo
269}
270
271var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
272
Paul Duffin44b481b2020-06-17 16:59:43 +0100273// Methods that need to be implemented for a module that is added to apex java_libs property.
274type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700275 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100276 ImplementationAndResourcesJars() android.Paths
277}
278
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100279// Provides build path and install path to DEX jars.
280type UsesLibraryDependency interface {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100281 DexJarBuildPath() OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100282 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000283 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100284}
285
Jaewoong Jung26342642021-03-17 15:56:23 -0700286// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800287type xref interface {
288 XrefJavaFiles() android.Paths
289}
290
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800291func (j *Module) XrefJavaFiles() android.Paths {
292 return j.kytheFiles
293}
294
Colin Crossbe1da472017-07-07 15:59:46 -0700295type dependencyTag struct {
296 blueprint.BaseDependencyTag
297 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000298
299 // True if the dependency is relinked at runtime.
300 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800301
302 // True if the dependency is a toolchain, for example an annotation processor.
303 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700304}
305
Colin Crosse9fe2942020-11-10 18:12:15 -0800306// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
307// dependency to be installed when the parent module is installed.
308type installDependencyTag struct {
309 blueprint.BaseDependencyTag
310 android.InstallAlwaysNeededDependencyTag
311 name string
312}
313
Colin Cross65cb3142021-12-10 23:05:02 +0000314func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
315 if d.runtimeLinked {
316 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800317 } else if d.toolchain {
318 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000319 }
320 return nil
321}
322
323var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
324
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100325type usesLibraryDependencyTag struct {
326 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100327 sdkVersion int // SDK version in which the library appared as a standalone library.
328 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100329}
330
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100331func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100332 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000333 dependencyTag: dependencyTag{
334 name: fmt.Sprintf("uses-library-%d", sdkVersion),
335 runtimeLinked: true,
336 },
337 sdkVersion: sdkVersion,
338 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100339 }
340}
341
Jiyong Park8be103b2019-11-08 15:53:48 +0900342func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700343 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900344}
345
Colin Crossbe1da472017-07-07 15:59:46 -0700346var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800347 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000348 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800349 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000350 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
351 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800352 pluginTag = dependencyTag{name: "plugin", toolchain: true}
353 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
354 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000355 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
356 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800357 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000358 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
359 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800360 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800361 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
362 certificateTag = dependencyTag{name: "certificate"}
363 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800364 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000365 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800366 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
367 jniInstallTag = installDependencyTag{name: "jni install"}
368 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100369 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
370 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
371 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
372 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
373 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700374)
Colin Cross2fe66872015-03-30 17:20:39 -0700375
Jiyong Park83dc74b2020-01-14 18:38:44 +0900376func IsLibDepTag(depTag blueprint.DependencyTag) bool {
377 return depTag == libTag
378}
379
380func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
381 return depTag == staticLibTag
382}
383
Colin Crossfc3674a2017-09-18 17:41:52 -0700384type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100385 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700386
Colin Cross6cef4812019-10-17 14:23:50 -0700387 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
388 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100389
390 // The default system modules to use. Will be an empty string if no system
391 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700392 systemModules string
393
Pete Gilline3d44b22020-06-29 11:28:51 +0100394 // The modules that will be added to the classpath regardless of the Java language level targeted
395 classpath []string
396
Colin Cross6cef4812019-10-17 14:23:50 -0700397 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100398 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700399 java9Classpath []string
400
Colin Crossa97c5d32018-03-28 14:58:31 -0700401 frameworkResModule string
402
Colin Cross86a60ae2018-05-29 14:44:55 -0700403 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700404 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100405
406 noStandardLibs, noFrameworksLibs bool
407}
408
409func (s sdkDep) hasStandardLibs() bool {
410 return !s.noStandardLibs
411}
412
413func (s sdkDep) hasFrameworkLibs() bool {
414 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700415}
416
Colin Crossa4f08812018-10-02 22:03:40 -0700417type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700418 name string
419 path android.Path
420 target android.Target
421 coverageFile android.OptionalPath
422 unstrippedFile android.Path
Colin Crossa4f08812018-10-02 22:03:40 -0700423}
424
Jiyong Parkf1691d22021-03-29 20:11:58 +0900425func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700426 sdkDep := decodeSdkDep(ctx, sdkContext)
427 if sdkDep.useModule {
428 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
429 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
430 ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
431 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
432 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
433 }
434 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
435 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
436 }
437 }
438 if sdkDep.systemModules != "" {
439 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
440 }
441}
442
Colin Cross32f676a2017-09-06 13:41:06 -0700443type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700444 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
445 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
446 // systemModules and java9Classpath instead.
447 bootClasspath classpath
448
449 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
450 // contains header jars for all static and non-static dependencies.
451 classpath classpath
452
453 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
454 // header jars for all non-static dependencies. Static dependencies have already been
455 // combined into the program jar.
456 dexClasspath classpath
457
458 // java9Classpath is the list of jars that will be added to the classpath when targeting
459 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
460 // are provided by systemModules.
461 java9Classpath classpath
462
Colin Cross748b2d82020-11-19 13:52:06 -0800463 processorPath classpath
464 errorProneProcessorPath classpath
465 processorClasses []string
466 staticJars android.Paths
467 staticHeaderJars android.Paths
468 staticResourceJars android.Paths
469 aidlIncludeDirs android.Paths
470 srcs android.Paths
471 srcJars android.Paths
472 systemModules *systemModules
473 aidlPreprocess android.OptionalPath
474 kotlinStdlib android.Paths
475 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700476 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800477
478 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700479}
Colin Cross2fe66872015-03-30 17:20:39 -0700480
Colin Cross54250902017-12-05 09:28:08 -0800481func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
482 for _, f := range dep.Srcs() {
483 if f.Ext() != ".jar" {
484 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
485 ctx.OtherModuleName(dep.(blueprint.Module)))
486 }
487 }
488}
489
Jiyong Parkf1691d22021-03-29 20:11:58 +0900490func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700491 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700492 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700493 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900494 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Bascace720c32022-05-24 12:13:50 +0100495 } else if ctx.Config().TargetsJava17() {
496 // Temporary experimental flag to be able to try and build with
497 // java version 17 options. The flag, if used, just sets Java
498 // 17 as the default version, leaving any components that
499 // target an older version intact.
500 return JAVA_VERSION_17
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000501 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000502 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700503 }
Nan Zhang357466b2018-04-17 17:38:36 -0700504}
505
Colin Cross1e743852019-10-28 11:37:20 -0700506type javaVersion int
507
508const (
509 JAVA_VERSION_UNSUPPORTED = 0
510 JAVA_VERSION_6 = 6
511 JAVA_VERSION_7 = 7
512 JAVA_VERSION_8 = 8
513 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000514 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100515 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700516)
517
518func (v javaVersion) String() string {
519 switch v {
520 case JAVA_VERSION_6:
521 return "1.6"
522 case JAVA_VERSION_7:
523 return "1.7"
524 case JAVA_VERSION_8:
525 return "1.8"
526 case JAVA_VERSION_9:
527 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000528 case JAVA_VERSION_11:
529 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100530 case JAVA_VERSION_17:
531 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700532 default:
533 return "unsupported"
534 }
535}
536
Cole Faustd96eebf2022-06-28 14:41:27 -0700537func (v javaVersion) StringForKotlinc() string {
538 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
539 // error: unknown JVM target version: foo
540 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
541 switch v {
542 case JAVA_VERSION_7:
543 return "1.6"
544 case JAVA_VERSION_9:
545 return "9"
546 default:
547 return v.String()
548 }
549}
550
Colin Cross1e743852019-10-28 11:37:20 -0700551// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
552func (v javaVersion) usesJavaModules() bool {
553 return v >= 9
554}
555
556func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100557 switch javaVersion {
558 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700559 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100560 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700561 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100562 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700563 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100564 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700565 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000566 case "11":
567 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100568 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100569 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100570 case "10", "12", "13", "14", "15", "16":
571 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700572 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100573 default:
574 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700575 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100576 }
577}
578
Colin Cross2fe66872015-03-30 17:20:39 -0700579//
580// Java libraries (.jar file)
581//
582
Colin Crossf506d872017-07-19 15:53:04 -0700583type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700584 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700585
586 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700587}
588
Jiyong Park45bf82e2020-12-15 22:29:02 +0900589var _ android.ApexModule = (*Library)(nil)
590
satayevd604b212021-07-21 14:23:52 +0100591// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100592type PermittedPackagesForUpdatableBootJars interface {
593 PermittedPackagesForUpdatableBootJars() []string
594}
595
596var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
597
598func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
599 return j.properties.Permitted_packages
600}
601
Colin Cross42be7612019-02-21 18:12:14 -0800602func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000603 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700604 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000605 return true
606 }
607
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000608 // Store uncompressed (and do not strip) dex files from boot class path jars.
609 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
610 return true
611 }
612
613 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000614 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000615 return true
616 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800617 if ctx.Config().UncompressPrivAppDex() &&
618 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
619 return true
620 }
621
Colin Cross2fc72f62018-12-21 12:59:54 -0800622 return false
623}
624
Jiakai Zhang22450f22021-10-11 03:05:20 +0000625// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
626func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
627 if dexer.dexProperties.Uncompress_dex == nil {
628 // If the value was not force-set by the user, use reasonable default based on the module.
629 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
630 }
631}
632
Colin Crossf506d872017-07-19 15:53:04 -0700633func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000634
635 j.provideHiddenAPIPropertyInfo(ctx)
636
Jiyong Park92315372021-04-02 08:45:46 +0900637 j.sdkVersion = j.SdkVersion(ctx)
638 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000639 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900640
Colin Cross56a83212020-09-15 18:30:11 -0700641 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
642 if !apexInfo.IsForPlatform() {
643 j.hideApexVariantFromMake = true
644 }
645
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100646 j.checkSdkVersions(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800647 if ctx.Device() {
648 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
649 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
650 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
651 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
652 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
653 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
654 }
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700655 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700656
bralee1fbf4402020-05-21 10:11:59 +0800657 // Collect the module directory for IDE info in java/jdeps.go.
658 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
659
Colin Cross56a83212020-09-15 18:30:11 -0700660 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900661 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700662 var extraInstallDeps android.Paths
663 if j.InstallMixin != nil {
664 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
665 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700666 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
667 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800668 j.hostdexInstallFile = ctx.InstallFile(
669 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700670 j.Stem()+"-hostdex.jar", j.outputFile)
671 }
672 var installDir android.InstallPath
673 if ctx.InstallInTestcases() {
674 var archDir string
675 if !ctx.Host() {
676 archDir = ctx.DeviceConfig().DeviceArch()
677 }
678 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
679 } else {
680 installDir = android.PathForModuleInstall(ctx, "framework")
681 }
682 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700683 }
Colin Crossb7a63242015-04-16 14:09:14 -0700684}
685
Colin Crossf506d872017-07-19 15:53:04 -0700686func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700687 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100688 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700689}
690
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000691const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000692 aidlIncludeDir = "aidl"
693 javaDir = "java"
694 jarFileSuffix = ".jar"
695 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000696)
697
Paul Duffina0dbf432019-12-05 11:25:53 +0000698// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000699func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000700 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000701}
702
Paul Duffina04c1072020-03-02 10:16:35 +0000703func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
704 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000705}
706
Paul Duffin13879572019-11-28 14:31:38 +0000707type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000708 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000709
710 // Function to retrieve the appropriate output jar (implementation or header) from
711 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000712 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
713
714 // Function to compute the snapshot relative path to which the named library's
715 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000716 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000717
718 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
719 // files like aidl files should also be copied.
720 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000721}
722
Paul Duffindb170e42020-12-08 17:48:25 +0000723const (
724 onlyCopyJarToSnapshot = true
725 copyEverythingToSnapshot = false
726)
727
Paul Duffin296701e2021-07-14 10:29:36 +0100728func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
729 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000730}
731
732func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
733 _, ok := module.(*Library)
734 return ok
735}
736
Paul Duffin3a4eb502020-03-19 16:11:18 +0000737func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
738 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000739}
Paul Duffina0dbf432019-12-05 11:25:53 +0000740
Paul Duffin14eb4672020-03-02 11:33:02 +0000741func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000742 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000743}
744
745type librarySdkMemberProperties struct {
746 android.SdkMemberPropertiesBase
747
Paul Duffin864e1b42020-05-06 10:23:19 +0100748 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000749 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100750
751 // The list of permitted packages that need to be passed to the prebuilts as they are used to
752 // create the updatable-bcp-packages.txt file.
753 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000754}
755
Paul Duffin3a4eb502020-03-19 16:11:18 +0000756func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000757 j := variant.(*Library)
758
Paul Duffindb170e42020-12-08 17:48:25 +0000759 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
760
Paul Duffina551a1c2020-03-17 21:04:24 +0000761 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100762
763 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000764}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000765
Paul Duffin3a4eb502020-03-19 16:11:18 +0000766func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000767 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000768
Paul Duffindb170e42020-12-08 17:48:25 +0000769 memberType := ctx.MemberType().(*librarySdkMemberType)
770
Paul Duffina551a1c2020-03-17 21:04:24 +0000771 exportedJar := p.JarToExport
772 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000773 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000774 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000775
776 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000777 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
778
Paul Duffina551a1c2020-03-17 21:04:24 +0000779 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
780 }
781
Paul Duffin869de142021-07-15 14:14:41 +0100782 if len(p.PermittedPackages) > 0 {
783 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
784 }
785
Paul Duffindb170e42020-12-08 17:48:25 +0000786 // Do not copy anything else to the snapshot.
787 if memberType.onlyCopyJarToSnapshot {
788 return
789 }
790
Paul Duffina551a1c2020-03-17 21:04:24 +0000791 aidlIncludeDirs := p.AidlIncludeDirs
792 if len(aidlIncludeDirs) != 0 {
793 sdkModuleContext := ctx.SdkModuleContext()
794 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000795 // TODO(jiyong): copy parcelable declarations only
796 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
797 for _, file := range aidlFiles {
798 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
799 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000800 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000801
Paul Duffina551a1c2020-03-17 21:04:24 +0000802 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000803 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000804}
805
Colin Cross1b16b0e2019-02-12 14:41:32 -0800806// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
807//
808// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
809// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
810// as a `static_libs` dependency of another module.
811//
812// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
813// a device.
814//
815// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
816// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700817func LibraryFactory() android.Module {
818 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700819
Colin Crossce6734e2020-06-15 16:09:53 -0700820 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700821
Paul Duffin71b33cc2021-06-23 11:39:47 +0100822 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100823
Jiyong Park7f7766d2019-07-25 22:02:35 +0900824 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900825 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800826 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900827 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700828 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700829}
830
Colin Cross1b16b0e2019-02-12 14:41:32 -0800831// java_library_static is an obsolete alias for java_library.
832func LibraryStaticFactory() android.Module {
833 return LibraryFactory()
834}
835
836// java_library_host builds and links sources into a `.jar` file for the host.
837//
838// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
839// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700840func LibraryHostFactory() android.Module {
841 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700842
Colin Crossce6734e2020-06-15 16:09:53 -0700843 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700844
Colin Cross9ae1b922018-06-26 17:59:05 -0700845 module.Module.properties.Installable = proptools.BoolPtr(true)
846
Jiyong Park7f7766d2019-07-25 22:02:35 +0900847 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100848 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800849 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900850 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700851 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700852}
853
854//
Colin Crossb628ea52018-08-14 16:42:33 -0700855// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700856//
857
Dan Shi95d19422020-08-15 12:24:26 -0700858// Test option struct.
859type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800860 android.CommonTestOptions
861
Dan Shi95d19422020-08-15 12:24:26 -0700862 // a list of extra test configuration files that should be installed with the module.
863 Extra_test_configs []string `android:"path,arch_variant"`
864}
865
Colin Cross05638fc2018-04-09 18:40:24 -0700866type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700867 // list of compatibility suites (for example "cts", "vts") that the module should be
868 // installed into.
869 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700870
871 // the name of the test configuration (for example "AndroidTest.xml") that should be
872 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800873 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700874
Jack He33338892018-09-19 02:21:28 -0700875 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
876 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800877 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700878
Colin Crossd96ca352018-08-10 16:06:24 -0700879 // list of files or filegroup modules that provide data that should be installed alongside
880 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900881 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700882
883 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
884 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
885 // explicitly.
886 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800887
888 // Add parameterized mainline modules to auto generated test config. The options will be
889 // handled by TradeFed to do downloading and installing the specified modules on the device.
890 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700891
892 // Test options.
893 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800894
895 // Names of modules containing JNI libraries that should be installed alongside the test.
896 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700897
898 // Install the test into a folder named for the module in all test suites.
899 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700900}
901
Liz Kammerdd849a82020-06-12 16:38:45 -0700902type hostTestProperties struct {
903 // list of native binary modules that should be installed alongside the test
904 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000905
906 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000907 // This property only adds the first variant of the dependency
908 Data_device_bins_first []string `android:"arch_variant"`
909
910 // list of device binary modules that should be installed alongside the test
911 // This property adds 64bit AND 32bit variants of the dependency
912 Data_device_bins_both []string `android:"arch_variant"`
913
914 // list of device binary modules that should be installed alongside the test
915 // This property only adds 64bit variants of the dependency
916 Data_device_bins_64 []string `android:"arch_variant"`
917
918 // list of device binary modules that should be installed alongside the test
919 // This property adds 32bit variants of the dependency if available, or else
920 // defaults to the 64bit variant
921 Data_device_bins_prefer32 []string `android:"arch_variant"`
922
923 // list of device binary modules that should be installed alongside the test
924 // This property only adds 32bit variants of the dependency
925 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700926}
927
Paul Duffin42df1442019-03-20 12:45:53 +0000928type testHelperLibraryProperties struct {
929 // list of compatibility suites (for example "cts", "vts") that the module should be
930 // installed into.
931 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700932
933 // Install the test into a folder named for the module in all test suites.
934 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000935}
936
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000937type prebuiltTestProperties struct {
938 // list of compatibility suites (for example "cts", "vts") that the module should be
939 // installed into.
940 Test_suites []string `android:"arch_variant"`
941
942 // the name of the test configuration (for example "AndroidTest.xml") that should be
943 // installed with the module.
944 Test_config *string `android:"path,arch_variant"`
945}
946
Colin Cross05638fc2018-04-09 18:40:24 -0700947type Test struct {
948 Library
949
950 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700951
Dan Shi95d19422020-08-15 12:24:26 -0700952 testConfig android.Path
953 extraTestConfigs android.Paths
954 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700955}
956
Liz Kammerdd849a82020-06-12 16:38:45 -0700957type TestHost struct {
958 Test
959
960 testHostProperties hostTestProperties
961}
962
Paul Duffin42df1442019-03-20 12:45:53 +0000963type TestHelperLibrary struct {
964 Library
965
966 testHelperLibraryProperties testHelperLibraryProperties
967}
968
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000969type JavaTestImport struct {
970 Import
971
972 prebuiltTestProperties prebuiltTestProperties
973
974 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700975 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000976}
977
Colin Cross24cc4be62021-11-03 14:09:41 -0700978func (j *Test) InstallInTestcases() bool {
979 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
980 // testcases by base_rules.mk.
981 return !j.Host()
982}
983
984func (j *TestHelperLibrary) InstallInTestcases() bool {
985 return true
986}
987
988func (j *JavaTestImport) InstallInTestcases() bool {
989 return true
990}
991
Sam Delmericocc271e22022-06-01 15:45:02 +0000992func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
993 if len(j.testHostProperties.Data_device_bins_first) > 0 {
994 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
995 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
996 }
997
998 var maybeAndroid32Target *android.Target
999 var maybeAndroid64Target *android.Target
1000 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1001 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1002 if len(android32TargetList) > 0 {
1003 maybeAndroid32Target = &android32TargetList[0]
1004 }
1005 if len(android64TargetList) > 0 {
1006 maybeAndroid64Target = &android64TargetList[0]
1007 }
1008
1009 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1010 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1011 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1012 return
1013 }
1014 if maybeAndroid32Target != nil {
1015 ctx.AddFarVariationDependencies(
1016 maybeAndroid32Target.Variations(),
1017 dataDeviceBinsTag,
1018 j.testHostProperties.Data_device_bins_both...,
1019 )
1020 }
1021 if maybeAndroid64Target != nil {
1022 ctx.AddFarVariationDependencies(
1023 maybeAndroid64Target.Variations(),
1024 dataDeviceBinsTag,
1025 j.testHostProperties.Data_device_bins_both...,
1026 )
1027 }
1028 }
1029
1030 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1031 if maybeAndroid32Target != nil {
1032 ctx.AddFarVariationDependencies(
1033 maybeAndroid32Target.Variations(),
1034 dataDeviceBinsTag,
1035 j.testHostProperties.Data_device_bins_prefer32...,
1036 )
1037 } else {
1038 if maybeAndroid64Target == nil {
1039 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1040 return
1041 }
1042 ctx.AddFarVariationDependencies(
1043 maybeAndroid64Target.Variations(),
1044 dataDeviceBinsTag,
1045 j.testHostProperties.Data_device_bins_prefer32...,
1046 )
1047 }
1048 }
1049
1050 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1051 if maybeAndroid32Target == nil {
1052 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1053 return
1054 }
1055 deviceVariations := maybeAndroid32Target.Variations()
1056 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1057 }
1058
1059 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1060 if maybeAndroid64Target == nil {
1061 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1062 return
1063 }
1064 deviceVariations := maybeAndroid64Target.Variations()
1065 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1066 }
1067}
1068
Liz Kammerdd849a82020-06-12 16:38:45 -07001069func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1070 if len(j.testHostProperties.Data_native_bins) > 0 {
1071 for _, target := range ctx.MultiTargets() {
1072 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1073 }
1074 }
1075
Colin Crossf8d9c492021-01-26 11:01:43 -08001076 if len(j.testProperties.Jni_libs) > 0 {
1077 for _, target := range ctx.MultiTargets() {
1078 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1079 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1080 }
1081 }
1082
Sam Delmericocc271e22022-06-01 15:45:02 +00001083 j.addDataDeviceBinsDeps(ctx)
1084
Liz Kammerdd849a82020-06-12 16:38:45 -07001085 j.deps(ctx)
1086}
1087
Yuexi Ma627263f2021-03-04 13:47:56 -08001088func (j *TestHost) AddExtraResource(p android.Path) {
1089 j.extraResources = append(j.extraResources, p)
1090}
1091
Sam Delmericocc271e22022-06-01 15:45:02 +00001092func (j *TestHost) dataDeviceBins() []string {
1093 ret := make([]string, 0,
1094 len(j.testHostProperties.Data_device_bins_first)+
1095 len(j.testHostProperties.Data_device_bins_both)+
1096 len(j.testHostProperties.Data_device_bins_prefer32)+
1097 len(j.testHostProperties.Data_device_bins_32)+
1098 len(j.testHostProperties.Data_device_bins_64),
1099 )
1100
1101 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1102 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1103 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1104 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1105 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1106
1107 return ret
1108}
1109
Sam Delmericob3342ce2022-01-20 21:10:28 +00001110func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1111 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001112 dataDeviceBins := j.dataDeviceBins()
1113 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001114 // add Tradefed configuration to push device bins to device for testing
1115 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1116 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001117 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001118 fullPath := filepath.Join(remoteDir, bin)
1119 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1120 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001121 configs = append(configs, tradefed.Object{
1122 Type: "target_preparer",
1123 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1124 Options: options,
1125 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001126 }
1127
1128 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
1129}
1130
Colin Cross303e21f2018-08-07 16:49:25 -07001131func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001132 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1133}
1134
1135func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001136 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1137 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001138 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001139 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1140 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001141
Dan Shi6ffaaa82019-09-26 11:41:36 -07001142 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001143 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -07001144
Colin Cross8a497952019-03-05 22:25:09 -08001145 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001146
Dan Shi95d19422020-08-15 12:24:26 -07001147 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1148
Liz Kammerdd849a82020-06-12 16:38:45 -07001149 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1150 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1151 })
1152
Sam Delmericob3342ce2022-01-20 21:10:28 +00001153 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1154 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1155 })
1156
Colin Crossf8d9c492021-01-26 11:01:43 -08001157 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1158 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1159 if sharedLibInfo.SharedLibrary != nil {
1160 // Copy to an intermediate output directory to append "lib[64]" to the path,
1161 // so that it's compatible with the default rpath values.
1162 var relPath string
1163 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1164 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1165 } else {
1166 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1167 }
1168 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1169 ctx.Build(pctx, android.BuildParams{
1170 Rule: android.Cp,
1171 Input: sharedLibInfo.SharedLibrary,
1172 Output: relocatedLib,
1173 })
1174 j.data = append(j.data, relocatedLib)
1175 } else {
1176 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1177 }
1178 })
1179
Colin Cross303e21f2018-08-07 16:49:25 -07001180 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001181}
1182
Paul Duffin42df1442019-03-20 12:45:53 +00001183func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1184 j.Library.GenerateAndroidBuildActions(ctx)
1185}
1186
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001187func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1188 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001189 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001190
1191 j.Import.GenerateAndroidBuildActions(ctx)
1192}
1193
1194type testSdkMemberType struct {
1195 android.SdkMemberTypeBase
1196}
1197
Paul Duffin296701e2021-07-14 10:29:36 +01001198func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1199 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001200}
1201
1202func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1203 _, ok := module.(*Test)
1204 return ok
1205}
1206
Paul Duffin3a4eb502020-03-19 16:11:18 +00001207func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1208 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001209}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001210
Paul Duffin14eb4672020-03-02 11:33:02 +00001211func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1212 return &testSdkMemberProperties{}
1213}
1214
1215type testSdkMemberProperties struct {
1216 android.SdkMemberPropertiesBase
1217
Paul Duffina551a1c2020-03-17 21:04:24 +00001218 JarToExport android.Path
1219 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001220}
1221
Paul Duffin3a4eb502020-03-19 16:11:18 +00001222func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001223 test := variant.(*Test)
1224
1225 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001226 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001227 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001228 }
1229
Paul Duffina551a1c2020-03-17 21:04:24 +00001230 p.JarToExport = implementationJars[0]
1231 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001232}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001233
Paul Duffin3a4eb502020-03-19 16:11:18 +00001234func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001235 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001236
Paul Duffina551a1c2020-03-17 21:04:24 +00001237 exportedJar := p.JarToExport
1238 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001239 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001240 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001241
1242 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001243 }
1244
1245 testConfig := p.TestConfig
1246 if testConfig != nil {
1247 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1248 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001249 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1250 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001251}
1252
Colin Cross1b16b0e2019-02-12 14:41:32 -08001253// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1254// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1255//
1256// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1257// compiled against the device bootclasspath.
1258//
1259// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1260// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001261func TestFactory() android.Module {
1262 module := &Test{}
1263
Colin Crossce6734e2020-06-15 16:09:53 -07001264 module.addHostAndDeviceProperties()
1265 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001266
Colin Cross9ae1b922018-06-26 17:59:05 -07001267 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001268 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001269 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001270
Paul Duffinb6b89a42021-05-06 16:33:43 +01001271 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001272 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001273 return module
1274}
1275
Paul Duffin42df1442019-03-20 12:45:53 +00001276// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1277func TestHelperLibraryFactory() android.Module {
1278 module := &TestHelperLibrary{}
1279
Colin Crossce6734e2020-06-15 16:09:53 -07001280 module.addHostAndDeviceProperties()
1281 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001282
Colin Cross9a4abed2019-04-24 13:19:28 -07001283 module.Module.properties.Installable = proptools.BoolPtr(true)
1284 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001285 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001286
Paul Duffin42df1442019-03-20 12:45:53 +00001287 InitJavaModule(module, android.HostAndDeviceSupported)
1288 return module
1289}
1290
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001291// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1292// and makes sure that it is added to the appropriate test suite.
1293//
1294// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1295// compiled against an Android classpath.
1296//
1297// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1298// for host modules.
1299func JavaTestImportFactory() android.Module {
1300 module := &JavaTestImport{}
1301
1302 module.AddProperties(
1303 &module.Import.properties,
1304 &module.prebuiltTestProperties)
1305
1306 module.Import.properties.Installable = proptools.BoolPtr(true)
1307
1308 android.InitPrebuiltModule(module, &module.properties.Jars)
1309 android.InitApexModule(module)
1310 android.InitSdkAwareModule(module)
1311 InitJavaModule(module, android.HostAndDeviceSupported)
1312 return module
1313}
1314
Colin Cross1b16b0e2019-02-12 14:41:32 -08001315// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1316// allow running the test with `atest` or a `TEST_MAPPING` file.
1317//
1318// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1319// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001320func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001321 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001322
Colin Crossce6734e2020-06-15 16:09:53 -07001323 module.addHostProperties()
1324 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001325 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001326
Yuexi Ma627263f2021-03-04 13:47:56 -08001327 InitTestHost(
1328 module,
1329 proptools.BoolPtr(true),
1330 nil,
1331 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001332
Liz Kammerdd849a82020-06-12 16:38:45 -07001333 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001334
Colin Cross05638fc2018-04-09 18:40:24 -07001335 return module
1336}
1337
Yuexi Ma627263f2021-03-04 13:47:56 -08001338func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1339 th.properties.Installable = installable
1340 th.testProperties.Auto_gen_config = autoGenConfig
1341 th.testProperties.Test_suites = testSuites
1342}
1343
Colin Cross05638fc2018-04-09 18:40:24 -07001344//
Colin Cross2fe66872015-03-30 17:20:39 -07001345// Java Binaries (.jar file plus wrapper script)
1346//
1347
Colin Crossf506d872017-07-19 15:53:04 -07001348type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001349 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001350 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001351
1352 // Name of the class containing main to be inserted into the manifest as Main-Class.
1353 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001354
1355 // Names of modules containing JNI libraries that should be installed alongside the host
1356 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001357 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001358}
1359
Colin Crossf506d872017-07-19 15:53:04 -07001360type Binary struct {
1361 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001362
Colin Crossf506d872017-07-19 15:53:04 -07001363 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001364
Colin Cross6b4a32d2017-12-05 13:42:45 -08001365 isWrapperVariant bool
1366
Colin Crossc3315992017-12-08 19:12:36 -08001367 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001368 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001369}
1370
Alex Light24237172017-10-26 09:46:21 -07001371func (j *Binary) HostToolPath() android.OptionalPath {
1372 return android.OptionalPathForPath(j.binaryFile)
1373}
1374
Colin Crossf506d872017-07-19 15:53:04 -07001375func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001376 if ctx.Arch().ArchType == android.Common {
1377 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001378 if j.binaryProperties.Main_class != nil {
1379 if j.properties.Manifest != nil {
1380 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1381 }
1382 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1383 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1384 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1385 }
1386
Colin Cross6b4a32d2017-12-05 13:42:45 -08001387 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001388 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001389 // Handle the binary wrapper
1390 j.isWrapperVariant = true
1391
Colin Cross366938f2017-12-11 16:29:02 -08001392 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001393 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001394 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001395 if ctx.Windows() {
1396 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1397 }
1398
Colin Cross6b4a32d2017-12-05 13:42:45 -08001399 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1400 }
1401
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001402 ext := ""
1403 if ctx.Windows() {
1404 ext = ".bat"
1405 }
1406
Colin Crossc179ea62020-10-09 10:54:15 -07001407 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001408 // of the wrapper variant, which will include the common variant's jar file and any JNI
1409 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001410 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001411 ctx.ModuleName()+ext, j.wrapperFile)
1412 }
Colin Cross2fe66872015-03-30 17:20:39 -07001413}
1414
Colin Crossf506d872017-07-19 15:53:04 -07001415func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001416 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001417 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001418 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001419 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001420 // These dependencies ensure the host installation rules will install the jar file and
1421 // the jni libraries when the wrapper is installed.
1422 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1423 ctx.AddVariationDependencies(
1424 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1425 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001426 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001427}
1428
Colin Cross1b16b0e2019-02-12 14:41:32 -08001429// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1430// as well.
1431//
1432// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1433// compiled against the device bootclasspath.
1434//
1435// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1436// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001437func BinaryFactory() android.Module {
1438 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001439
Colin Crossce6734e2020-06-15 16:09:53 -07001440 module.addHostAndDeviceProperties()
1441 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001442
Colin Cross9ae1b922018-06-26 17:59:05 -07001443 module.Module.properties.Installable = proptools.BoolPtr(true)
1444
Colin Cross6b4a32d2017-12-05 13:42:45 -08001445 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1446 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001447 android.InitBazelModule(module)
1448
Colin Cross36242852017-06-23 15:06:31 -07001449 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001450}
1451
Colin Cross1b16b0e2019-02-12 14:41:32 -08001452// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1453//
1454// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1455// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001456func BinaryHostFactory() android.Module {
1457 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001458
Colin Crossce6734e2020-06-15 16:09:53 -07001459 module.addHostProperties()
1460 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001461
Colin Cross9ae1b922018-06-26 17:59:05 -07001462 module.Module.properties.Installable = proptools.BoolPtr(true)
1463
Colin Cross6b4a32d2017-12-05 13:42:45 -08001464 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1465 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001466 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001467 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001468}
1469
1470//
1471// Java prebuilts
1472//
1473
Colin Cross74d73e22017-08-02 11:05:49 -07001474type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001475 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001476
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001477 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1478 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001479 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001480
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001481 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1482 // specified.
1483 Min_sdk_version *string
1484
William Loh5a082f92022-05-17 20:21:50 +00001485 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
1486 // and uses-permission tags in manifest_fixer.
1487 Replace_max_sdk_version_placeholder *string
1488
Colin Cross535e2cf2017-10-20 17:57:49 -07001489 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001490
Paul Duffin869de142021-07-15 14:14:41 +01001491 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001492 Permitted_packages []string
1493
Jiyong Park1be96912018-05-28 18:02:19 +09001494 // List of shared java libs that this module has dependencies to
1495 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001496
1497 // List of files to remove from the jar file(s)
1498 Exclude_files []string
1499
1500 // List of directories to remove from the jar file(s)
1501 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001502
1503 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001504 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001505
1506 // set the name of the output
1507 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001508
1509 Aidl struct {
1510 // directories that should be added as include directories for any aidl sources of modules
1511 // that depend on this module, as well as to aidl for this module.
1512 Export_include_dirs []string
1513 }
Colin Cross74d73e22017-08-02 11:05:49 -07001514}
1515
1516type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001517 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001518 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001519 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001520 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001521 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001522 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001523
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001524 // Functionality common to Module and Import.
1525 embeddableInModuleAndImport
1526
Liz Kammerd6c31d22020-08-05 15:40:41 -07001527 hiddenAPI
1528 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001529 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001530
Colin Cross74d73e22017-08-02 11:05:49 -07001531 properties ImportProperties
1532
Liz Kammerd6c31d22020-08-05 15:40:41 -07001533 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001534 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001535 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001536
Colin Cross0a6e0072017-08-30 14:24:55 -07001537 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001538 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001539 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001540
1541 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001542
1543 sdkVersion android.SdkSpec
1544 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001545}
1546
Paul Duffin630b11e2021-07-15 13:35:26 +01001547var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1548
1549func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1550 return j.properties.Permitted_packages
1551}
1552
Jiyong Park92315372021-04-02 08:45:46 +09001553func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1554 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001555}
1556
Jiyong Parkf1691d22021-03-29 20:11:58 +09001557func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001558 return "none"
1559}
1560
Jiyong Park92315372021-04-02 08:45:46 +09001561func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001562 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001563 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001564 }
Jiyong Park92315372021-04-02 08:45:46 +09001565 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001566}
1567
William Loh5a082f92022-05-17 20:21:50 +00001568func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
1569 if j.properties.Replace_max_sdk_version_placeholder != nil {
1570 return android.SdkSpecFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
1571 }
1572 return android.SdkSpecFrom(ctx, "")
1573}
1574
Jiyong Park92315372021-04-02 08:45:46 +09001575func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1576 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001577}
1578
Colin Cross74d73e22017-08-02 11:05:49 -07001579func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001580 return &j.prebuilt
1581}
1582
Colin Cross74d73e22017-08-02 11:05:49 -07001583func (j *Import) PrebuiltSrcs() []string {
1584 return j.properties.Jars
1585}
1586
1587func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001588 return j.prebuilt.Name(j.ModuleBase.Name())
1589}
1590
Jiyong Park0b238752019-10-29 11:23:10 +09001591func (j *Import) Stem() string {
1592 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1593}
1594
Jiyong Park618922e2020-01-08 13:35:43 +09001595func (a *Import) JacocoReportClassesFile() android.Path {
1596 return nil
1597}
1598
Bill Peckhama41a6962021-01-11 10:58:54 -08001599func (j *Import) LintDepSets() LintDepSets {
1600 return LintDepSets{}
1601}
1602
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001603func (j *Import) getStrictUpdatabilityLinting() bool {
1604 return false
1605}
1606
1607func (j *Import) setStrictUpdatabilityLinting(bool) {
1608}
1609
Colin Cross74d73e22017-08-02 11:05:49 -07001610func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001611 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001612
1613 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001614 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001615 }
Colin Cross1e676be2016-10-12 14:38:15 -07001616}
1617
Sam Delmerico277795c2022-02-25 17:04:37 +00001618func (j *Import) commonBuildActions(ctx android.ModuleContext) {
1619 //TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09001620 j.sdkVersion = j.SdkVersion(ctx)
1621 j.minSdkVersion = j.MinSdkVersion(ctx)
1622
Colin Cross56a83212020-09-15 18:30:11 -07001623 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1624 j.hideApexVariantFromMake = true
1625 }
1626
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001627 if ctx.Windows() {
1628 j.HideFromMake()
1629 }
Sam Delmerico277795c2022-02-25 17:04:37 +00001630}
1631
1632func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1633 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001634
Colin Cross8a497952019-03-05 22:25:09 -08001635 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001636
Jiyong Park0b238752019-10-29 11:23:10 +09001637 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001638 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001639 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1640 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001641 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001642 inputFile := outputFile
1643 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1644 TransformJetifier(ctx, outputFile, inputFile)
1645 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001646 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001647 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001648
Liz Kammerd6c31d22020-08-05 15:40:41 -07001649 var flags javaBuilderFlags
1650
Jiyong Park1be96912018-05-28 18:02:19 +09001651 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001652 tag := ctx.OtherModuleDependencyTag(module)
1653
Colin Crossdcf71b22021-02-01 13:59:03 -08001654 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1655 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001656 switch tag {
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001657 case libTag:
1658 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1659 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1660 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001661 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001662 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001663 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001664 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001665 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001666 switch tag {
1667 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001668 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001669 }
1670 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001671
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001672 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001673 })
1674
Sam Delmerico277795c2022-02-25 17:04:37 +00001675 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09001676
1677 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001678
Paul Duffin064b70c2020-11-02 17:32:38 +00001679 if ctx.Device() {
1680 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1681 // obtained from the associated deapexer module.
1682 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1683 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001684 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001685 di := android.FindDeapexerProviderForModule(ctx)
1686 if di == nil {
1687 return // An error has been reported by FindDeapexerProviderForModule.
1688 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001689 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001690 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1691 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001692 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1693 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001694
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001695 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001696 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001697 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1698 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001699
1700 // Initialize the hiddenapi structure.
1701 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001702 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001703 // This should never happen as a variant for a prebuilt_apex is only created if the
1704 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001705 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001706 }
1707 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001708 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001709 if sdkDep.invalidVersion {
1710 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1711 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1712 } else if sdkDep.useFiles {
1713 // sdkDep.jar is actually equivalent to turbine header.jar.
1714 flags.classpath = append(flags.classpath, sdkDep.jars...)
1715 }
1716
1717 // Dex compilation
1718
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001719 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1720 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001721 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001722 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1723
Paul Duffin612e6102021-02-02 13:38:13 +00001724 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001725 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001726 if ctx.Failed() {
1727 return
1728 }
1729
Paul Duffin74d18d12021-05-14 14:18:47 +01001730 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001731 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001732
1733 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001734 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001735
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001736 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001737 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001738 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001739 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001740
1741 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1742 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1743 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1744 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1745 AidlIncludeDirs: j.exportAidlIncludeDirs,
1746 })
Colin Cross2fe66872015-03-30 17:20:39 -07001747}
1748
Sam Delmerico277795c2022-02-25 17:04:37 +00001749func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
1750 if !Bool(j.properties.Installable) {
1751 return
1752 }
1753
1754 var installDir android.InstallPath
1755 if ctx.InstallInTestcases() {
1756 var archDir string
1757 if !ctx.Host() {
1758 archDir = ctx.DeviceConfig().DeviceArch()
1759 }
1760 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1761 } else {
1762 installDir = android.PathForModuleInstall(ctx, "framework")
1763 }
1764 ctx.InstallFile(installDir, jarName, outputFile)
1765}
1766
Paul Duffinaa55f742020-10-06 17:20:13 +01001767func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1768 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001769 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001770 return android.Paths{j.combinedClasspathFile}, nil
1771 default:
1772 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1773 }
1774}
1775
1776var _ android.OutputFileProducer = (*Import)(nil)
1777
Nan Zhanged19fc32017-10-19 13:06:22 -07001778func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001779 if j.combinedClasspathFile == nil {
1780 return nil
1781 }
Colin Cross37f6d792018-07-12 12:28:41 -07001782 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001783}
1784
Colin Cross331a1212018-08-15 20:40:52 -07001785func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001786 if j.combinedClasspathFile == nil {
1787 return nil
1788 }
Colin Cross331a1212018-08-15 20:40:52 -07001789 return android.Paths{j.combinedClasspathFile}
1790}
1791
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001792func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001793 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001794}
1795
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001796func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001797 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001798}
1799
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001800func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1801 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001802}
1803
Jiyong Park45bf82e2020-12-15 22:29:02 +09001804var _ android.ApexModule = (*Import)(nil)
1805
1806// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001807func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001808 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001809}
1810
Jiyong Park45bf82e2020-12-15 22:29:02 +09001811// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001812func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1813 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001814 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001815 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001816 return fmt.Errorf("min_sdk_version is not specified")
1817 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001818 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001819 return nil
1820 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001821 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1822 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001823 }
Jooyung Han749dc692020-04-15 11:03:39 +09001824 return nil
1825}
1826
Paul Duffinfef55002021-06-17 14:56:05 +01001827// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1828// java_sdk_library_import with the specified base module name requires to be exported from a
1829// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001830func requiredFilesFromPrebuiltApexForImport(name string) []string {
1831 // Add the dex implementation jar to the set of exported files.
1832 return []string{
1833 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001834 }
1835}
1836
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001837// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1838// the java library with the specified name.
1839func apexRootRelativePathToJavaLib(name string) string {
1840 return filepath.Join("javalib", name+".jar")
1841}
1842
Paul Duffinfef55002021-06-17 14:56:05 +01001843var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1844
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001845func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001846 name := j.BaseModuleName()
1847 return requiredFilesFromPrebuiltApexForImport(name)
1848}
1849
albaltai36ff7dc2018-12-25 14:35:23 +08001850// Add compile time check for interface implementation
1851var _ android.IDEInfo = (*Import)(nil)
1852var _ android.IDECustomizedModuleName = (*Import)(nil)
1853
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001854// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001855
1856func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1857 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1858}
1859
1860func (j *Import) IDECustomizedModuleName() string {
1861 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1862 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1863 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001864 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001865}
1866
Colin Cross74d73e22017-08-02 11:05:49 -07001867var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001868
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001869func (j *Import) IsInstallable() bool {
1870 return Bool(j.properties.Installable)
1871}
1872
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001873var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001874
Colin Cross1b16b0e2019-02-12 14:41:32 -08001875// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1876//
1877// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1878// compiled against an Android classpath.
1879//
1880// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1881// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001882func ImportFactory() android.Module {
1883 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001884
Liz Kammerd6c31d22020-08-05 15:40:41 -07001885 module.AddProperties(
1886 &module.properties,
1887 &module.dexer.dexProperties,
1888 )
Colin Cross74d73e22017-08-02 11:05:49 -07001889
Paul Duffin71b33cc2021-06-23 11:39:47 +01001890 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001891
Liz Kammerd6c31d22020-08-05 15:40:41 -07001892 module.dexProperties.Optimize.EnabledByDefault = false
1893
Colin Cross74d73e22017-08-02 11:05:49 -07001894 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001895 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001896 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001897 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001898 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001899 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001900}
1901
Colin Cross1b16b0e2019-02-12 14:41:32 -08001902// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1903// module.
1904//
1905// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1906// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001907func ImportFactoryHost() android.Module {
1908 module := &Import{}
1909
1910 module.AddProperties(&module.properties)
1911
1912 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001913 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001914 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001915 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001916 return module
1917}
1918
Colin Cross42be7612019-02-21 18:12:14 -08001919// dex_import module
1920
1921type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001922 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001923
1924 // set the name of the output
1925 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001926}
1927
1928type DexImport struct {
1929 android.ModuleBase
1930 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001931 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001932 prebuilt android.Prebuilt
1933
1934 properties DexImportProperties
1935
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001936 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001937
1938 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001939
1940 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001941}
1942
1943func (j *DexImport) Prebuilt() *android.Prebuilt {
1944 return &j.prebuilt
1945}
1946
1947func (j *DexImport) PrebuiltSrcs() []string {
1948 return j.properties.Jars
1949}
1950
1951func (j *DexImport) Name() string {
1952 return j.prebuilt.Name(j.ModuleBase.Name())
1953}
1954
Jiyong Park0b238752019-10-29 11:23:10 +09001955func (j *DexImport) Stem() string {
1956 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1957}
1958
Jiyong Park77acec62020-06-01 21:39:15 +09001959func (a *DexImport) JacocoReportClassesFile() android.Path {
1960 return nil
1961}
1962
Colin Cross08dca382020-07-21 20:31:17 -07001963func (a *DexImport) LintDepSets() LintDepSets {
1964 return LintDepSets{}
1965}
1966
Martin Stjernholm6d415272020-01-31 17:10:36 +00001967func (j *DexImport) IsInstallable() bool {
1968 return true
1969}
1970
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001971func (j *DexImport) getStrictUpdatabilityLinting() bool {
1972 return false
1973}
1974
1975func (j *DexImport) setStrictUpdatabilityLinting(bool) {
1976}
1977
Colin Cross42be7612019-02-21 18:12:14 -08001978func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1979 if len(j.properties.Jars) != 1 {
1980 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
1981 }
1982
Colin Cross56a83212020-09-15 18:30:11 -07001983 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1984 if !apexInfo.IsForPlatform() {
1985 j.hideApexVariantFromMake = true
1986 }
1987
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001988 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1989 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08001990 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
1991
1992 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
1993 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
1994
1995 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08001996 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08001997
1998 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
1999 rule.Temporary(temporary)
2000
2001 // use zip2zip to uncompress classes*.dex files
2002 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002003 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002004 FlagWithInput("-i ", inputJar).
2005 FlagWithOutput("-o ", temporary).
2006 FlagWithArg("-0 ", "'classes*.dex'")
2007
2008 // use zipalign to align uncompressed classes*.dex files
2009 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002010 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002011 Flag("-f").
2012 Text("4").
2013 Input(temporary).
2014 Output(dexOutputFile)
2015
2016 rule.DeleteTemporaryFiles()
2017
Colin Crossf1a035e2020-11-16 17:32:30 -08002018 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002019 } else {
2020 ctx.Build(pctx, android.BuildParams{
2021 Rule: android.Cp,
2022 Input: inputJar,
2023 Output: dexOutputFile,
2024 })
2025 }
2026
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002027 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002028
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002029 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002030
Colin Cross56a83212020-09-15 18:30:11 -07002031 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002032 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2033 j.Stem()+".jar", dexOutputFile)
2034 }
Colin Cross42be7612019-02-21 18:12:14 -08002035}
2036
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002037func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002038 return j.dexJarFile
2039}
2040
Jiyong Park45bf82e2020-12-15 22:29:02 +09002041var _ android.ApexModule = (*DexImport)(nil)
2042
2043// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002044func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2045 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002046 // we don't check prebuilt modules for sdk_version
2047 return nil
2048}
2049
Colin Cross42be7612019-02-21 18:12:14 -08002050// dex_import imports a `.jar` file containing classes.dex files.
2051//
2052// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2053// to the device.
2054func DexImportFactory() android.Module {
2055 module := &DexImport{}
2056
2057 module.AddProperties(&module.properties)
2058
2059 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002060 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002061 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002062 return module
2063}
2064
Colin Cross89536d42017-07-07 14:35:50 -07002065// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002066type Defaults struct {
2067 android.ModuleBase
2068 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002069 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002070}
2071
Colin Cross1b16b0e2019-02-12 14:41:32 -08002072// java_defaults provides a set of properties that can be inherited by other java or android modules.
2073//
2074// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2075// property in the defaults module that exists in the depending module will be prepended to the depending module's
2076// value for that property.
2077//
2078// Example:
2079//
Sam Delmerico277795c2022-02-25 17:04:37 +00002080// java_defaults {
2081// name: "example_defaults",
2082// srcs: ["common/**/*.java"],
2083// javacflags: ["-Xlint:all"],
2084// aaptflags: ["--auto-add-overlay"],
2085// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002086//
Sam Delmerico277795c2022-02-25 17:04:37 +00002087// java_library {
2088// name: "example",
2089// defaults: ["example_defaults"],
2090// srcs: ["example/**/*.java"],
2091// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002092//
2093// is functionally identical to:
2094//
Sam Delmerico277795c2022-02-25 17:04:37 +00002095// java_library {
2096// name: "example",
2097// srcs: [
2098// "common/**/*.java",
2099// "example/**/*.java",
2100// ],
2101// javacflags: ["-Xlint:all"],
2102// }
Paul Duffin47357662019-12-05 14:07:14 +00002103func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002104 module := &Defaults{}
2105
Colin Cross89536d42017-07-07 14:35:50 -07002106 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002107 &CommonProperties{},
2108 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002109 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002110 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002111 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002112 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002113 &aaptProperties{},
2114 &androidLibraryProperties{},
2115 &appProperties{},
2116 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002117 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002118 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002119 &ImportProperties{},
2120 &AARImportProperties{},
2121 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002122 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002123 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002124 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002125 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002126 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002127 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002128 )
2129
2130 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002131 return module
2132}
Nan Zhangea568a42017-11-08 21:20:04 -08002133
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002134func kytheExtractJavaFactory() android.Singleton {
2135 return &kytheExtractJavaSingleton{}
2136}
2137
2138type kytheExtractJavaSingleton struct {
2139}
2140
2141func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2142 var xrefTargets android.Paths
2143 ctx.VisitAllModules(func(module android.Module) {
2144 if javaModule, ok := module.(xref); ok {
2145 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2146 }
2147 })
2148 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2149 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002150 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002151 }
2152}
2153
Nan Zhangea568a42017-11-08 21:20:04 -08002154var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002155var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002156var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08002157var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002158
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002159// Add class loader context (CLC) of a given dependency to the current CLC.
2160func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2161 clcMap dexpreopt.ClassLoaderContextMap) {
2162
2163 dep, ok := depModule.(UsesLibraryDependency)
2164 if !ok {
2165 return
2166 }
2167
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002168 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2169
2170 var sdkLib *string
2171 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2172 // A shared SDK library. This should be added as a top-level CLC element.
2173 sdkLib = &depName
2174 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2175 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2176 // property. This should be handled in the same way as a shared SDK library.
2177 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002178 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002179
2180 depTag := ctx.OtherModuleDependencyTag(depModule)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +01002181 if depTag == libTag {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002182 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002183 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2184 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002185 } else if depTag == staticLibTag {
2186 // Propagate <uses-library> through static library dependencies, unless it is a component
2187 // library (such as stubs). Component libraries have a dependency on their SDK library,
2188 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002189 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002190 return
2191 }
2192 } else {
2193 // Don't propagate <uses-library> for other dependency tags.
2194 return
2195 }
2196
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002197 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2198 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2199 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2200 // from its CLC should be added to the current CLC.
2201 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002202 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002203 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002204 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002205 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2206 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002207}
Wei Libafb6d62021-12-10 03:14:59 -08002208
Sam Delmerico79985812022-03-23 20:20:42 +00002209type javaResourcesAttributes struct {
2210 Resources bazel.LabelListAttribute
2211 Resource_strip_prefix *string
2212}
2213
2214func (m *Library) convertJavaResourcesAttributes(ctx android.TopDownMutatorContext) *javaResourcesAttributes {
2215 var resources bazel.LabelList
2216 var resourceStripPrefix *string
2217
2218 if m.properties.Java_resources != nil {
2219 resources.Append(android.BazelLabelForModuleSrc(ctx, m.properties.Java_resources))
2220 }
2221
2222 //TODO(b/179889880) handle case where glob includes files outside package
2223 resDeps := ResourceDirsToFiles(
2224 ctx,
2225 m.properties.Java_resource_dirs,
2226 m.properties.Exclude_java_resource_dirs,
2227 m.properties.Exclude_java_resources,
2228 )
2229
2230 for i, resDep := range resDeps {
2231 dir, files := resDep.dir, resDep.files
2232
2233 resources.Append(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files)))
2234
2235 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2236 // inside the JAR file, so we need to remove that prefix
2237 resourceStripPrefix = proptools.StringPtr(dir.String())
2238 if i > 0 {
2239 // TODO(b/226423379) allow multiple resource prefixes
2240 ctx.ModuleErrorf("bp2build does not support more than one directory in java_resource_dirs (b/226423379)")
2241 }
2242 }
2243
2244 return &javaResourcesAttributes{
2245 Resources: bazel.MakeLabelListAttribute(resources),
2246 Resource_strip_prefix: resourceStripPrefix,
2247 }
2248}
2249
Sam Delmericoc0161432022-02-25 21:34:51 +00002250type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002251 *javaResourcesAttributes
Wei Libafb6d62021-12-10 03:14:59 -08002252 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002253 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002254 Javacopts bazel.StringListAttribute
2255}
2256
Sam Delmericoc0161432022-02-25 21:34:51 +00002257type javaDependencyLabels struct {
2258 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2259 Deps bazel.LabelListAttribute
2260 // Dependencies which DO contribute to the API visible to upstream dependencies.
2261 StaticDeps bazel.LabelListAttribute
2262}
2263
Sam Delmerico24da73c2022-03-16 20:36:54 +00002264type eventLogTagsAttributes struct {
2265 Srcs bazel.LabelListAttribute
2266}
2267
Sam Delmerico97bd1272022-08-25 14:45:31 -04002268type aidlLibraryAttributes struct {
2269 Srcs bazel.LabelListAttribute
2270}
2271
2272type javaAidlLibraryAttributes struct {
2273 Deps bazel.LabelListAttribute
2274}
2275
2276// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
2277// and also separates dependencies into dynamic dependencies and static dependencies.
2278// Each corresponding Bazel target type, can have a different method for handling
2279// dynamic vs. static dependencies, and so these are returned to the calling function.
Sam Delmericoc0161432022-02-25 21:34:51 +00002280func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002281 var srcs bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002282 var deps bazel.LabelList
2283 var staticDeps bazel.LabelList
2284
Sam Delmericoe91d0302022-02-23 15:28:33 +00002285 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2286 for axis, configToProps := range archVariantProps {
2287 for config, _props := range configToProps {
2288 if archProps, ok := _props.(*CommonProperties); ok {
2289 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2290 srcs.SetSelectValue(axis, config, archSrcs)
2291 }
2292 }
2293 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002294
2295 javaSrcPartition := "java"
2296 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002297 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002298 aidlSrcPartition := "aidl"
Sam Delmericoc7681022022-02-04 21:01:20 +00002299 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002300 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2301 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2302 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04002303 aidlSrcPartition: android.AidlSrcLabelPartition,
Sam Delmericoc7681022022-02-04 21:01:20 +00002304 })
2305
Sam Delmerico24da73c2022-03-16 20:36:54 +00002306 javaSrcs := srcPartitions[javaSrcPartition]
2307
Sam Delmerico24da73c2022-03-16 20:36:54 +00002308 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2309 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002310 ctx.CreateBazelTargetModule(
2311 bazel.BazelTargetModuleProperties{
2312 Rule_class: "event_log_tags",
2313 Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
2314 },
2315 android.CommonAttributes{Name: logtagsLibName},
2316 &eventLogTagsAttributes{
2317 Srcs: srcPartitions[logtagSrcPartition],
2318 },
2319 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04002320
2321 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2322 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00002323 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002324
2325 if !srcPartitions[aidlSrcPartition].IsEmpty() {
2326 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
2327 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
2328 })
2329
2330 if !aidlSrcs.IsEmpty() {
2331 aidlLibName := m.Name() + "_aidl_library"
2332 ctx.CreateBazelTargetModule(
2333 bazel.BazelTargetModuleProperties{
2334 Rule_class: "aidl_library",
2335 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
2336 },
2337 android.CommonAttributes{Name: aidlLibName},
2338 &aidlLibraryAttributes{
2339 Srcs: aidlSrcs,
2340 },
2341 )
2342 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
2343 }
2344
2345 javaAidlLibName := m.Name() + "_java_aidl_library"
2346 ctx.CreateBazelTargetModule(
2347 bazel.BazelTargetModuleProperties{
2348 Rule_class: "java_aidl_library",
2349 Bzl_load_location: "//build/bazel/rules/java:aidl_library.bzl",
2350 },
2351 android.CommonAttributes{Name: javaAidlLibName},
2352 &javaAidlLibraryAttributes{
2353 Deps: aidlLibs,
2354 },
2355 )
2356
2357 staticDeps.Add(&bazel.Label{Label: ":" + javaAidlLibName})
2358 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00002359
Sam Delmerico58614c02022-03-15 21:02:09 +00002360 var javacopts []string
2361 if m.properties.Javacflags != nil {
2362 javacopts = append(javacopts, m.properties.Javacflags...)
2363 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002364 if m.properties.Java_version != nil {
2365 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2366 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2367 }
2368
Sam Delmerico58614c02022-03-15 21:02:09 +00002369 epEnabled := m.properties.Errorprone.Enabled
2370 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
2371 if Bool(epEnabled) {
2372 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2373 }
2374
Sam Delmericoc0161432022-02-25 21:34:51 +00002375 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00002376 Srcs: javaSrcs,
2377 javaResourcesAttributes: m.convertJavaResourcesAttributes(ctx),
Sam Delmerico77267c72022-03-18 14:11:07 +00002378 Plugins: bazel.MakeLabelListAttribute(
2379 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2380 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002381 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002382 }
2383
2384 if m.properties.Libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002385 deps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Libs))))
Wei Libafb6d62021-12-10 03:14:59 -08002386 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002387
Sam Delmericofde9fb52022-01-28 20:53:38 +00002388 if m.properties.Static_libs != nil {
Romain Jobredeauxc9b2bba2022-02-15 09:35:07 -05002389 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, android.LastUniqueStrings(android.CopyOf(m.properties.Static_libs))))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002390 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002391
Sam Delmericoc0161432022-02-25 21:34:51 +00002392 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2393 // Soong does not differentiate between a java_library and the Bazel equivalent of
2394 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2395 // listed directly in the srcs of a java_library, and the classes produced
2396 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2397 // that depend on a java_library with proto sources can link directly to the protobuf API,
2398 // and so this should be a static dependency.
2399 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002400
Sam Delmerico97bd1272022-08-25 14:45:31 -04002401 depLabels := &javaDependencyLabels{}
Sam Delmericoc0161432022-02-25 21:34:51 +00002402 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2403 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002404
Sam Delmericoc0161432022-02-25 21:34:51 +00002405 return commonAttrs, depLabels
2406}
2407
2408type javaLibraryAttributes struct {
2409 *javaCommonAttributes
2410 Deps bazel.LabelListAttribute
2411 Exports bazel.LabelListAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002412}
2413
2414func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002415 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2416
2417 deps := depLabels.Deps
2418 if !commonAttrs.Srcs.IsEmpty() {
2419 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2420
2421 sdkVersion := m.SdkVersion(ctx)
2422 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2423 // TODO(b/220869005) remove forced dependency on current public android.jar
2424 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2425 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04002426 } else if !deps.IsEmpty() {
Sam Delmericoc0161432022-02-25 21:34:51 +00002427 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2428 }
2429
2430 attrs := &javaLibraryAttributes{
2431 javaCommonAttributes: commonAttrs,
2432 Deps: deps,
2433 Exports: depLabels.StaticDeps,
2434 }
Wei Libafb6d62021-12-10 03:14:59 -08002435
2436 props := bazel.BazelTargetModuleProperties{
2437 Rule_class: "java_library",
2438 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2439 }
2440
2441 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2442}
2443
2444type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002445 *javaCommonAttributes
2446 Deps bazel.LabelListAttribute
2447 Runtime_deps bazel.LabelListAttribute
2448 Main_class string
2449 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002450}
2451
2452// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2453func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002454 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2455
2456 deps := depLabels.Deps
2457 deps.Append(depLabels.StaticDeps)
2458 if m.binaryProperties.Jni_libs != nil {
2459 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2460 }
2461
2462 var runtimeDeps bazel.LabelListAttribute
2463 if commonAttrs.Srcs.IsEmpty() {
2464 // if there are no sources, then the dependencies can only be used at runtime
2465 runtimeDeps = deps
2466 deps = bazel.LabelListAttribute{}
2467 }
2468
Wei Libafb6d62021-12-10 03:14:59 -08002469 mainClass := ""
2470 if m.binaryProperties.Main_class != nil {
2471 mainClass = *m.binaryProperties.Main_class
2472 }
2473 if m.properties.Manifest != nil {
2474 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2475 if err != nil {
2476 return
2477 }
2478 mainClass = mainClassInManifest
2479 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002480
Wei Libafb6d62021-12-10 03:14:59 -08002481 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002482 javaCommonAttributes: commonAttrs,
2483 Deps: deps,
2484 Runtime_deps: runtimeDeps,
2485 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002486 }
2487
2488 // Attribute jvm_flags
2489 if m.binaryProperties.Jni_libs != nil {
2490 jniLibPackages := map[string]bool{}
2491 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2492 jniLibPackage := jniLibLabel.Label
2493 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2494 if indexOfColon > 0 {
2495 // JNI lib from other package
2496 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2497 } else if indexOfColon == 0 {
2498 // JNI lib in the same package of java_binary
2499 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2500 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2501 }
2502 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2503 jniLibPackages[jniLibPackage] = true
2504 }
2505 }
2506 jniLibPaths := []string{}
2507 for jniLibPackage, _ := range jniLibPackages {
2508 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2509 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2510 }
2511 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2512 }
2513
2514 props := bazel.BazelTargetModuleProperties{
2515 Rule_class: "java_binary",
2516 }
2517
2518 // Create the BazelTargetModule.
2519 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2520}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002521
2522type bazelJavaImportAttributes struct {
2523 Jars bazel.LabelListAttribute
2524}
2525
2526// java_import bp2Build converter.
2527func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002528 var jars bazel.LabelListAttribute
2529 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2530 for axis, configToProps := range archVariantProps {
2531 for config, _props := range configToProps {
2532 if archProps, ok := _props.(*ImportProperties); ok {
2533 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2534 jars.SetSelectValue(axis, config, archJars)
2535 }
2536 }
2537 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002538
2539 attrs := &bazelJavaImportAttributes{
2540 Jars: jars,
2541 }
2542 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2543
2544 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
Sam Delmerico277795c2022-02-25 17:04:37 +00002545}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002546
Sam Delmerico277795c2022-02-25 17:04:37 +00002547var _ android.MixedBuildBuildable = (*Import)(nil)
2548
2549func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
2550 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
2551}
2552
2553func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
2554 i.commonBuildActions(ctx)
2555
2556 bazelCtx := ctx.Config().BazelContext
2557 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
2558 if err != nil {
2559 ctx.ModuleErrorf(err.Error())
2560 return
2561 }
2562
2563 bazelJars := android.Paths{}
2564 for _, bazelOutputFile := range filePaths {
2565 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
2566 }
2567
2568 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
2569 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
2570 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
2571 android.OptionalPath{}, // manifest
2572 false, // stripDirEntries
2573 []string{}, // filesToStrip
2574 []string{}, // dirsToStrip
2575 )
2576 i.combinedClasspathFile = outputFile
2577
2578 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2579 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
2580 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
2581 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
2582 //TODO(b/240308299) include AIDL information from Bazel
2583 })
2584
2585 i.maybeInstall(ctx, jarName, outputFile)
2586}
2587
2588func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
2589 bazelCtx := ctx.Config().BazelContext
2590 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
2591}
2592
2593func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
2594 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002595}