blob: 895ce7af1bf98ac9c1242cc601d183e725de9c4d [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 Delmerico4e272292022-01-06 20:03:51 +000027
Colin Cross2fe66872015-03-30 17:20:39 -070028 "github.com/google/blueprint"
Colin Cross76b5f0c2017-08-29 16:02:06 -070029 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070030
Colin Cross635c3b02016-05-18 15:37:25 -070031 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080032 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010033 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070034 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070035 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070036)
37
Colin Cross463a90e2015-06-17 14:20:06 -070038func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010039 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000040
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080041 RegisterJavaSdkMemberTypes()
42}
43
Paul Duffin535e0a12021-03-30 23:34:32 +010044func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080045 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
46
47 ctx.RegisterModuleType("java_library", LibraryFactory)
48 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
49 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
50 ctx.RegisterModuleType("java_binary", BinaryFactory)
51 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
52 ctx.RegisterModuleType("java_test", TestFactory)
53 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
54 ctx.RegisterModuleType("java_test_host", TestHostFactory)
55 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
56 ctx.RegisterModuleType("java_import", ImportFactory)
57 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
58 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
59 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
60 ctx.RegisterModuleType("dex_import", DexImportFactory)
61
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010062 // This mutator registers dependencies on dex2oat for modules that should be
63 // dexpreopted. This is done late when the final variants have been
64 // established, to not get the dependencies split into the wrong variants and
65 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080066 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
67 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
68 })
69
70 ctx.RegisterSingletonType("logtags", LogtagsSingleton)
71 ctx.RegisterSingletonType("kythe_java_extract", kytheExtractJavaFactory)
72}
73
74func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000075 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000076 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010077 android.RegisterSdkMemberType(javaLibsSdkMemberType)
78 android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
Jiakai Zhangea180332021-09-26 08:58:02 +000079 android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010080 android.RegisterSdkMemberType(javaTestSdkMemberType)
81}
82
83var (
84 // Supports adding java header libraries to module_exports and sdk.
85 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
86 android.SdkMemberTypeBase{
87 PropertyName: "java_header_libs",
88 SupportsSdk: true,
89 },
90 func(_ android.SdkMemberContext, j *Library) android.Path {
91 headerJars := j.HeaderJars()
92 if len(headerJars) != 1 {
93 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
94 }
95
96 return headerJars[0]
97 },
98 sdkSnapshotFilePathForJar,
99 copyEverythingToSnapshot,
100 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000101
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000102 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100103 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000104 implementationJars := j.ImplementationAndResourcesJars()
105 if len(implementationJars) != 1 {
106 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
107 }
108 return implementationJars[0]
109 }
110
Paul Duffin2da04242021-04-23 19:43:28 +0100111 // Supports adding java implementation libraries to module_exports but not sdk.
112 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000113 android.SdkMemberTypeBase{
114 PropertyName: "java_libs",
115 },
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000116 exportImplementationClassesJar,
Paul Duffindb170e42020-12-08 17:48:25 +0000117 sdkSnapshotFilePathForJar,
118 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100119 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000120
Paul Duffin2da04242021-04-23 19:43:28 +0100121 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000122 //
123 // The build has some implicit dependencies (via the boot jars configuration) on a number of
124 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
125 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
126 // used outside those mainline modules.
127 //
128 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
129 // either java_libs, or java_header_libs would end up exporting more information than was strictly
130 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
131 // sdk/module_exports without exposing any unnecessary information.
Paul Duffin2da04242021-04-23 19:43:28 +0100132 javaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffindb170e42020-12-08 17:48:25 +0000133 android.SdkMemberTypeBase{
134 PropertyName: "java_boot_libs",
135 SupportsSdk: true,
136 },
Paul Duffin5c211452021-07-15 12:42:44 +0100137 func(ctx android.SdkMemberContext, j *Library) android.Path {
138 // Java boot libs are only provided in the SDK to provide access to their dex implementation
139 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
140 // actual implementation jar but the java_import will need a file that exists so just copy an
141 // empty file. Any attempt to use that file as a jar will cause a build error.
142 return ctx.SnapshotBuilder().EmptyFile()
143 },
144 func(osPrefix, name string) string {
145 // Create a special name for the implementation jar to try and provide some useful information
146 // to a developer that attempts to compile against this.
147 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
148 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
149 },
Paul Duffindb170e42020-12-08 17:48:25 +0000150 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100151 }
Paul Duffindb170e42020-12-08 17:48:25 +0000152
Jiakai Zhangea180332021-09-26 08:58:02 +0000153 // Supports adding java systemserver libraries to module_exports and sdk.
154 //
155 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
156 // of modules that are part of the java systemserver classpath and which are provided by mainline
157 // modules but which are not otherwise used outside those mainline modules.
158 //
159 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
160 // either java_libs, or java_header_libs would end up exporting more information than was strictly
161 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
162 // the sdk/module_exports without exposing any unnecessary information.
163 javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
164 android.SdkMemberTypeBase{
165 PropertyName: "java_systemserver_libs",
166 SupportsSdk: true,
167 },
168 func(ctx android.SdkMemberContext, j *Library) android.Path {
169 // Java systemserver libs are only provided in the SDK to provide access to their dex
170 // implementation jar for use by dexpreopting. They do not need to provide an actual
171 // implementation jar but the java_import will need a file that exists so just copy an empty
172 // file. Any attempt to use that file as a jar will cause a build error.
173 return ctx.SnapshotBuilder().EmptyFile()
174 },
175 func(osPrefix, name string) string {
176 // Create a special name for the implementation jar to try and provide some useful information
177 // to a developer that attempts to compile against this.
178 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
179 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
180 },
181 onlyCopyJarToSnapshot,
182 }
183
Paul Duffin2da04242021-04-23 19:43:28 +0100184 // Supports adding java test libraries to module_exports but not sdk.
185 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000186 SdkMemberTypeBase: android.SdkMemberTypeBase{
187 PropertyName: "java_tests",
188 },
Paul Duffin2da04242021-04-23 19:43:28 +0100189 }
190)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900191
Colin Crossdcf71b22021-02-01 13:59:03 -0800192// JavaInfo contains information about a java module for use by modules that depend on it.
193type JavaInfo struct {
194 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
195 // against this module. If empty, ImplementationJars should be used instead.
196 HeaderJars android.Paths
197
198 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
199 // in the module as well as any resources included in the module.
200 ImplementationAndResourcesJars android.Paths
201
202 // ImplementationJars is a list of jars that contain the implementations of classes in the
203 //module.
204 ImplementationJars android.Paths
205
206 // ResourceJars is a list of jars that contain the resources included in the module.
207 ResourceJars android.Paths
208
209 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
210 // depending on this module.
211 AidlIncludeDirs android.Paths
212
213 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
214 // module.
215 SrcJarArgs []string
216
217 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
218 SrcJarDeps android.Paths
219
220 // ExportedPlugins is a list of paths that should be used as annotation processors for any
221 // module that depends on this module.
222 ExportedPlugins android.Paths
223
224 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
225 // any module that depends on this module.
226 ExportedPluginClasses []string
227
228 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
229 // requiring disbling turbine for any modules that depend on it.
230 ExportedPluginDisableTurbine bool
231
232 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
233 // instrumented by jacoco.
234 JacocoReportClassesFile android.Path
235}
236
237var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
238
Colin Cross75ce9ec2021-02-26 16:20:32 -0800239// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
240// the sysprop implementation library.
241type SyspropPublicStubInfo struct {
242 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
243 // the sysprop implementation library.
244 JavaInfo JavaInfo
245}
246
247var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
248
Paul Duffin44b481b2020-06-17 16:59:43 +0100249// Methods that need to be implemented for a module that is added to apex java_libs property.
250type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700251 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100252 ImplementationAndResourcesJars() android.Paths
253}
254
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100255// Provides build path and install path to DEX jars.
256type UsesLibraryDependency interface {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100257 DexJarBuildPath() OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100258 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000259 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100260}
261
Jaewoong Jung26342642021-03-17 15:56:23 -0700262// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800263type xref interface {
264 XrefJavaFiles() android.Paths
265}
266
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800267func (j *Module) XrefJavaFiles() android.Paths {
268 return j.kytheFiles
269}
270
Colin Crossbe1da472017-07-07 15:59:46 -0700271type dependencyTag struct {
272 blueprint.BaseDependencyTag
273 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000274
275 // True if the dependency is relinked at runtime.
276 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800277
278 // True if the dependency is a toolchain, for example an annotation processor.
279 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700280}
281
Colin Crosse9fe2942020-11-10 18:12:15 -0800282// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
283// dependency to be installed when the parent module is installed.
284type installDependencyTag struct {
285 blueprint.BaseDependencyTag
286 android.InstallAlwaysNeededDependencyTag
287 name string
288}
289
Colin Cross65cb3142021-12-10 23:05:02 +0000290func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
291 if d.runtimeLinked {
292 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800293 } else if d.toolchain {
294 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000295 }
296 return nil
297}
298
299var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
300
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100301type usesLibraryDependencyTag struct {
302 dependencyTag
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100303
304 // SDK version in which the library appared as a standalone library.
305 sdkVersion int
306
307 // If the dependency is optional or required.
308 optional bool
309
310 // Whether this is an implicit dependency inferred by Soong, or an explicit one added via
311 // `uses_libs`/`optional_uses_libs` properties.
312 implicit bool
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100313}
314
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100315func makeUsesLibraryDependencyTag(sdkVersion int, optional bool, implicit bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100316 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000317 dependencyTag: dependencyTag{
318 name: fmt.Sprintf("uses-library-%d", sdkVersion),
319 runtimeLinked: true,
320 },
321 sdkVersion: sdkVersion,
322 optional: optional,
323 implicit: implicit,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100324 }
325}
326
Jiyong Park8be103b2019-11-08 15:53:48 +0900327func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700328 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900329}
330
Colin Crossbe1da472017-07-07 15:59:46 -0700331var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800332 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000333 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800334 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000335 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
336 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800337 pluginTag = dependencyTag{name: "plugin", toolchain: true}
338 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
339 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000340 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
341 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800342 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000343 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
344 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800345 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800346 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
347 certificateTag = dependencyTag{name: "certificate"}
348 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800349 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000350 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800351 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
352 jniInstallTag = installDependencyTag{name: "jni install"}
353 binaryInstallTag = installDependencyTag{name: "binary install"}
Colin Crossbe1da472017-07-07 15:59:46 -0700354)
Colin Cross2fe66872015-03-30 17:20:39 -0700355
Jiyong Park83dc74b2020-01-14 18:38:44 +0900356func IsLibDepTag(depTag blueprint.DependencyTag) bool {
357 return depTag == libTag
358}
359
360func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
361 return depTag == staticLibTag
362}
363
Colin Crossfc3674a2017-09-18 17:41:52 -0700364type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100365 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700366
Colin Cross6cef4812019-10-17 14:23:50 -0700367 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
368 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100369
370 // The default system modules to use. Will be an empty string if no system
371 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700372 systemModules string
373
Pete Gilline3d44b22020-06-29 11:28:51 +0100374 // The modules that will be added to the classpath regardless of the Java language level targeted
375 classpath []string
376
Colin Cross6cef4812019-10-17 14:23:50 -0700377 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100378 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700379 java9Classpath []string
380
Colin Crossa97c5d32018-03-28 14:58:31 -0700381 frameworkResModule string
382
Colin Cross86a60ae2018-05-29 14:44:55 -0700383 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700384 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100385
386 noStandardLibs, noFrameworksLibs bool
387}
388
389func (s sdkDep) hasStandardLibs() bool {
390 return !s.noStandardLibs
391}
392
393func (s sdkDep) hasFrameworkLibs() bool {
394 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700395}
396
Colin Crossa4f08812018-10-02 22:03:40 -0700397type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700398 name string
399 path android.Path
400 target android.Target
401 coverageFile android.OptionalPath
402 unstrippedFile android.Path
Colin Crossa4f08812018-10-02 22:03:40 -0700403}
404
Jiyong Parkf1691d22021-03-29 20:11:58 +0900405func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700406 sdkDep := decodeSdkDep(ctx, sdkContext)
407 if sdkDep.useModule {
408 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
409 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
410 ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
411 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
412 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
413 }
414 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
415 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
416 }
417 }
418 if sdkDep.systemModules != "" {
419 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
420 }
421}
422
Colin Cross32f676a2017-09-06 13:41:06 -0700423type deps struct {
Colin Cross748b2d82020-11-19 13:52:06 -0800424 classpath classpath
425 java9Classpath classpath
426 bootClasspath classpath
427 processorPath classpath
428 errorProneProcessorPath classpath
429 processorClasses []string
430 staticJars android.Paths
431 staticHeaderJars android.Paths
432 staticResourceJars android.Paths
433 aidlIncludeDirs android.Paths
434 srcs android.Paths
435 srcJars android.Paths
436 systemModules *systemModules
437 aidlPreprocess android.OptionalPath
438 kotlinStdlib android.Paths
439 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700440 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800441
442 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700443}
Colin Cross2fe66872015-03-30 17:20:39 -0700444
Colin Cross54250902017-12-05 09:28:08 -0800445func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
446 for _, f := range dep.Srcs() {
447 if f.Ext() != ".jar" {
448 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
449 ctx.OtherModuleName(dep.(blueprint.Module)))
450 }
451 }
452}
453
Jiyong Parkf1691d22021-03-29 20:11:58 +0900454func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700455 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700456 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700457 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900458 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000459 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000460 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700461 }
Nan Zhang357466b2018-04-17 17:38:36 -0700462}
463
Colin Cross1e743852019-10-28 11:37:20 -0700464type javaVersion int
465
466const (
467 JAVA_VERSION_UNSUPPORTED = 0
468 JAVA_VERSION_6 = 6
469 JAVA_VERSION_7 = 7
470 JAVA_VERSION_8 = 8
471 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000472 JAVA_VERSION_11 = 11
Colin Cross1e743852019-10-28 11:37:20 -0700473)
474
475func (v javaVersion) String() string {
476 switch v {
477 case JAVA_VERSION_6:
478 return "1.6"
479 case JAVA_VERSION_7:
480 return "1.7"
481 case JAVA_VERSION_8:
482 return "1.8"
483 case JAVA_VERSION_9:
484 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000485 case JAVA_VERSION_11:
486 return "11"
Colin Cross1e743852019-10-28 11:37:20 -0700487 default:
488 return "unsupported"
489 }
490}
491
492// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
493func (v javaVersion) usesJavaModules() bool {
494 return v >= 9
495}
496
497func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100498 switch javaVersion {
499 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700500 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100501 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700502 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100503 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700504 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100505 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700506 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000507 case "11":
508 return JAVA_VERSION_11
509 case "10":
510 ctx.PropertyErrorf("java_version", "Java language levels 10 is not supported")
Colin Cross1e743852019-10-28 11:37:20 -0700511 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100512 default:
513 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700514 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100515 }
516}
517
Colin Cross2fe66872015-03-30 17:20:39 -0700518//
519// Java libraries (.jar file)
520//
521
Colin Crossf506d872017-07-19 15:53:04 -0700522type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700523 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700524
525 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700526}
527
Jiyong Park45bf82e2020-12-15 22:29:02 +0900528var _ android.ApexModule = (*Library)(nil)
529
satayevd604b212021-07-21 14:23:52 +0100530// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100531type PermittedPackagesForUpdatableBootJars interface {
532 PermittedPackagesForUpdatableBootJars() []string
533}
534
535var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
536
537func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
538 return j.properties.Permitted_packages
539}
540
Colin Cross42be7612019-02-21 18:12:14 -0800541func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000542 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700543 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000544 return true
545 }
546
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000547 // Store uncompressed (and do not strip) dex files from boot class path jars.
548 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
549 return true
550 }
551
552 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000553 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000554 return true
555 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800556 if ctx.Config().UncompressPrivAppDex() &&
557 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
558 return true
559 }
560
Colin Cross2fc72f62018-12-21 12:59:54 -0800561 return false
562}
563
Jiakai Zhang22450f22021-10-11 03:05:20 +0000564// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
565func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
566 if dexer.dexProperties.Uncompress_dex == nil {
567 // If the value was not force-set by the user, use reasonable default based on the module.
568 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
569 }
570}
571
Colin Crossf506d872017-07-19 15:53:04 -0700572func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +0900573 j.sdkVersion = j.SdkVersion(ctx)
574 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000575 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900576
Colin Cross56a83212020-09-15 18:30:11 -0700577 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
578 if !apexInfo.IsForPlatform() {
579 j.hideApexVariantFromMake = true
580 }
581
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100582 j.checkSdkVersions(ctx)
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000583 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
584 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross43f08db2018-11-12 10:13:39 -0800585 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
Jiakai Zhang22450f22021-10-11 03:05:20 +0000586 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Liz Kammera7a64f32020-07-09 15:16:41 -0700587 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100588 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700589 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700590
bralee1fbf4402020-05-21 10:11:59 +0800591 // Collect the module directory for IDE info in java/jdeps.go.
592 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
593
Colin Cross56a83212020-09-15 18:30:11 -0700594 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900595 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700596 var extraInstallDeps android.Paths
597 if j.InstallMixin != nil {
598 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
599 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700600 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
601 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800602 j.hostdexInstallFile = ctx.InstallFile(
603 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700604 j.Stem()+"-hostdex.jar", j.outputFile)
605 }
606 var installDir android.InstallPath
607 if ctx.InstallInTestcases() {
608 var archDir string
609 if !ctx.Host() {
610 archDir = ctx.DeviceConfig().DeviceArch()
611 }
612 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
613 } else {
614 installDir = android.PathForModuleInstall(ctx, "framework")
615 }
616 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700617 }
Colin Crossb7a63242015-04-16 14:09:14 -0700618}
619
Colin Crossf506d872017-07-19 15:53:04 -0700620func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700621 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100622 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700623}
624
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000625const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000626 aidlIncludeDir = "aidl"
627 javaDir = "java"
628 jarFileSuffix = ".jar"
629 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000630)
631
Paul Duffina0dbf432019-12-05 11:25:53 +0000632// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffina04c1072020-03-02 10:16:35 +0000633func sdkSnapshotFilePathForJar(osPrefix, name string) string {
634 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000635}
636
Paul Duffina04c1072020-03-02 10:16:35 +0000637func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
638 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000639}
640
Paul Duffin13879572019-11-28 14:31:38 +0000641type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000642 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000643
644 // Function to retrieve the appropriate output jar (implementation or header) from
645 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000646 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
647
648 // Function to compute the snapshot relative path to which the named library's
649 // jar should be copied.
650 snapshotPathGetter func(osPrefix, name string) string
651
652 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
653 // files like aidl files should also be copied.
654 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000655}
656
Paul Duffindb170e42020-12-08 17:48:25 +0000657const (
658 onlyCopyJarToSnapshot = true
659 copyEverythingToSnapshot = false
660)
661
Paul Duffin296701e2021-07-14 10:29:36 +0100662func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
663 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000664}
665
666func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
667 _, ok := module.(*Library)
668 return ok
669}
670
Paul Duffin3a4eb502020-03-19 16:11:18 +0000671func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
672 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000673}
Paul Duffina0dbf432019-12-05 11:25:53 +0000674
Paul Duffin14eb4672020-03-02 11:33:02 +0000675func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000676 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000677}
678
679type librarySdkMemberProperties struct {
680 android.SdkMemberPropertiesBase
681
Paul Duffin864e1b42020-05-06 10:23:19 +0100682 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000683 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100684
685 // The list of permitted packages that need to be passed to the prebuilts as they are used to
686 // create the updatable-bcp-packages.txt file.
687 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000688}
689
Paul Duffin3a4eb502020-03-19 16:11:18 +0000690func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000691 j := variant.(*Library)
692
Paul Duffindb170e42020-12-08 17:48:25 +0000693 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
694
Paul Duffina551a1c2020-03-17 21:04:24 +0000695 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100696
697 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000698}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000699
Paul Duffin3a4eb502020-03-19 16:11:18 +0000700func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000701 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000702
Paul Duffindb170e42020-12-08 17:48:25 +0000703 memberType := ctx.MemberType().(*librarySdkMemberType)
704
Paul Duffina551a1c2020-03-17 21:04:24 +0000705 exportedJar := p.JarToExport
706 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000707 // Delegate the creation of the snapshot relative path to the member type.
708 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(p.OsPrefix(), ctx.Name())
709
710 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000711 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
712
Paul Duffina551a1c2020-03-17 21:04:24 +0000713 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
714 }
715
Paul Duffin869de142021-07-15 14:14:41 +0100716 if len(p.PermittedPackages) > 0 {
717 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
718 }
719
Paul Duffindb170e42020-12-08 17:48:25 +0000720 // Do not copy anything else to the snapshot.
721 if memberType.onlyCopyJarToSnapshot {
722 return
723 }
724
Paul Duffina551a1c2020-03-17 21:04:24 +0000725 aidlIncludeDirs := p.AidlIncludeDirs
726 if len(aidlIncludeDirs) != 0 {
727 sdkModuleContext := ctx.SdkModuleContext()
728 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000729 // TODO(jiyong): copy parcelable declarations only
730 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
731 for _, file := range aidlFiles {
732 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
733 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000734 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000735
Paul Duffina551a1c2020-03-17 21:04:24 +0000736 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000737 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000738}
739
Colin Cross1b16b0e2019-02-12 14:41:32 -0800740// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
741//
742// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
743// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
744// as a `static_libs` dependency of another module.
745//
746// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
747// a device.
748//
749// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
750// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700751func LibraryFactory() android.Module {
752 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700753
Colin Crossce6734e2020-06-15 16:09:53 -0700754 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700755
Paul Duffin71b33cc2021-06-23 11:39:47 +0100756 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100757
Jiyong Park7f7766d2019-07-25 22:02:35 +0900758 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900759 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800760 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900761 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700762 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700763}
764
Colin Cross1b16b0e2019-02-12 14:41:32 -0800765// java_library_static is an obsolete alias for java_library.
766func LibraryStaticFactory() android.Module {
767 return LibraryFactory()
768}
769
770// java_library_host builds and links sources into a `.jar` file for the host.
771//
772// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
773// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700774func LibraryHostFactory() android.Module {
775 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700776
Colin Crossce6734e2020-06-15 16:09:53 -0700777 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700778
Colin Cross9ae1b922018-06-26 17:59:05 -0700779 module.Module.properties.Installable = proptools.BoolPtr(true)
780
Jiyong Park7f7766d2019-07-25 22:02:35 +0900781 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100782 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800783 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900784 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700785 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700786}
787
788//
Colin Crossb628ea52018-08-14 16:42:33 -0700789// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700790//
791
Dan Shi95d19422020-08-15 12:24:26 -0700792// Test option struct.
793type TestOptions struct {
794 // a list of extra test configuration files that should be installed with the module.
795 Extra_test_configs []string `android:"path,arch_variant"`
Dan Shid79572f2020-11-13 14:33:46 -0800796
797 // If the test is a hostside(no device required) unittest that shall be run during presubmit check.
798 Unit_test *bool
Dan Shi95d19422020-08-15 12:24:26 -0700799}
800
Colin Cross05638fc2018-04-09 18:40:24 -0700801type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700802 // list of compatibility suites (for example "cts", "vts") that the module should be
803 // installed into.
804 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700805
806 // the name of the test configuration (for example "AndroidTest.xml") that should be
807 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800808 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700809
Jack He33338892018-09-19 02:21:28 -0700810 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
811 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800812 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700813
Colin Crossd96ca352018-08-10 16:06:24 -0700814 // list of files or filegroup modules that provide data that should be installed alongside
815 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900816 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700817
818 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
819 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
820 // explicitly.
821 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800822
823 // Add parameterized mainline modules to auto generated test config. The options will be
824 // handled by TradeFed to do downloading and installing the specified modules on the device.
825 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700826
827 // Test options.
828 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800829
830 // Names of modules containing JNI libraries that should be installed alongside the test.
831 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700832
833 // Install the test into a folder named for the module in all test suites.
834 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700835}
836
Liz Kammerdd849a82020-06-12 16:38:45 -0700837type hostTestProperties struct {
838 // list of native binary modules that should be installed alongside the test
839 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000840
841 // list of device binary modules that should be installed alongside the test
842 Data_device_bins []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700843}
844
Paul Duffin42df1442019-03-20 12:45:53 +0000845type testHelperLibraryProperties struct {
846 // list of compatibility suites (for example "cts", "vts") that the module should be
847 // installed into.
848 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700849
850 // Install the test into a folder named for the module in all test suites.
851 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000852}
853
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000854type prebuiltTestProperties struct {
855 // list of compatibility suites (for example "cts", "vts") that the module should be
856 // installed into.
857 Test_suites []string `android:"arch_variant"`
858
859 // the name of the test configuration (for example "AndroidTest.xml") that should be
860 // installed with the module.
861 Test_config *string `android:"path,arch_variant"`
862}
863
Colin Cross05638fc2018-04-09 18:40:24 -0700864type Test struct {
865 Library
866
867 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700868
Dan Shi95d19422020-08-15 12:24:26 -0700869 testConfig android.Path
870 extraTestConfigs android.Paths
871 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700872}
873
Liz Kammerdd849a82020-06-12 16:38:45 -0700874type TestHost struct {
875 Test
876
877 testHostProperties hostTestProperties
878}
879
Paul Duffin42df1442019-03-20 12:45:53 +0000880type TestHelperLibrary struct {
881 Library
882
883 testHelperLibraryProperties testHelperLibraryProperties
884}
885
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000886type JavaTestImport struct {
887 Import
888
889 prebuiltTestProperties prebuiltTestProperties
890
891 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700892 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000893}
894
Colin Cross24cc4be62021-11-03 14:09:41 -0700895func (j *Test) InstallInTestcases() bool {
896 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
897 // testcases by base_rules.mk.
898 return !j.Host()
899}
900
901func (j *TestHelperLibrary) InstallInTestcases() bool {
902 return true
903}
904
905func (j *JavaTestImport) InstallInTestcases() bool {
906 return true
907}
908
Liz Kammerdd849a82020-06-12 16:38:45 -0700909func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
910 if len(j.testHostProperties.Data_native_bins) > 0 {
911 for _, target := range ctx.MultiTargets() {
912 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
913 }
914 }
915
Sam Delmericob3342ce2022-01-20 21:10:28 +0000916 if len(j.testHostProperties.Data_device_bins) > 0 {
917 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
918 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins...)
919 }
920
Colin Crossf8d9c492021-01-26 11:01:43 -0800921 if len(j.testProperties.Jni_libs) > 0 {
922 for _, target := range ctx.MultiTargets() {
923 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
924 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
925 }
926 }
927
Liz Kammerdd849a82020-06-12 16:38:45 -0700928 j.deps(ctx)
929}
930
Yuexi Ma627263f2021-03-04 13:47:56 -0800931func (j *TestHost) AddExtraResource(p android.Path) {
932 j.extraResources = append(j.extraResources, p)
933}
934
Sam Delmericob3342ce2022-01-20 21:10:28 +0000935func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
936 var configs []tradefed.Config
937 if len(j.testHostProperties.Data_device_bins) > 0 {
938 // add Tradefed configuration to push device bins to device for testing
939 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
940 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
941 for _, bin := range j.testHostProperties.Data_device_bins {
942 fullPath := filepath.Join(remoteDir, bin)
943 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
944 }
945 configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.PushFilePreparer", options})
946 }
947
948 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
949}
950
Colin Cross303e21f2018-08-07 16:49:25 -0700951func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +0000952 j.generateAndroidBuildActionsWithConfig(ctx, nil)
953}
954
955func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +0000956 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
957 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -0700958 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +0000959 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
960 }
Sam Delmericob3342ce2022-01-20 21:10:28 +0000961
Dan Shi6ffaaa82019-09-26 11:41:36 -0700962 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +0000963 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -0700964
Colin Cross8a497952019-03-05 22:25:09 -0800965 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700966
Dan Shi95d19422020-08-15 12:24:26 -0700967 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
968
Liz Kammerdd849a82020-06-12 16:38:45 -0700969 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
970 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
971 })
972
Sam Delmericob3342ce2022-01-20 21:10:28 +0000973 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
974 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
975 })
976
Colin Crossf8d9c492021-01-26 11:01:43 -0800977 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
978 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
979 if sharedLibInfo.SharedLibrary != nil {
980 // Copy to an intermediate output directory to append "lib[64]" to the path,
981 // so that it's compatible with the default rpath values.
982 var relPath string
983 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
984 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
985 } else {
986 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
987 }
988 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
989 ctx.Build(pctx, android.BuildParams{
990 Rule: android.Cp,
991 Input: sharedLibInfo.SharedLibrary,
992 Output: relocatedLib,
993 })
994 j.data = append(j.data, relocatedLib)
995 } else {
996 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
997 }
998 })
999
Colin Cross303e21f2018-08-07 16:49:25 -07001000 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001001}
1002
Paul Duffin42df1442019-03-20 12:45:53 +00001003func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1004 j.Library.GenerateAndroidBuildActions(ctx)
1005}
1006
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001007func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1008 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001009 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001010
1011 j.Import.GenerateAndroidBuildActions(ctx)
1012}
1013
1014type testSdkMemberType struct {
1015 android.SdkMemberTypeBase
1016}
1017
Paul Duffin296701e2021-07-14 10:29:36 +01001018func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1019 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001020}
1021
1022func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1023 _, ok := module.(*Test)
1024 return ok
1025}
1026
Paul Duffin3a4eb502020-03-19 16:11:18 +00001027func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1028 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001029}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001030
Paul Duffin14eb4672020-03-02 11:33:02 +00001031func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1032 return &testSdkMemberProperties{}
1033}
1034
1035type testSdkMemberProperties struct {
1036 android.SdkMemberPropertiesBase
1037
Paul Duffina551a1c2020-03-17 21:04:24 +00001038 JarToExport android.Path
1039 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001040}
1041
Paul Duffin3a4eb502020-03-19 16:11:18 +00001042func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001043 test := variant.(*Test)
1044
1045 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001046 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001047 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001048 }
1049
Paul Duffina551a1c2020-03-17 21:04:24 +00001050 p.JarToExport = implementationJars[0]
1051 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001052}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001053
Paul Duffin3a4eb502020-03-19 16:11:18 +00001054func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001055 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001056
Paul Duffina551a1c2020-03-17 21:04:24 +00001057 exportedJar := p.JarToExport
1058 if exportedJar != nil {
1059 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(p.OsPrefix(), ctx.Name())
1060 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001061
1062 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001063 }
1064
1065 testConfig := p.TestConfig
1066 if testConfig != nil {
1067 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1068 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001069 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1070 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001071}
1072
Colin Cross1b16b0e2019-02-12 14:41:32 -08001073// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1074// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1075//
1076// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1077// compiled against the device bootclasspath.
1078//
1079// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1080// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001081func TestFactory() android.Module {
1082 module := &Test{}
1083
Colin Crossce6734e2020-06-15 16:09:53 -07001084 module.addHostAndDeviceProperties()
1085 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001086
Colin Cross9ae1b922018-06-26 17:59:05 -07001087 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001088 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001089 module.Module.linter.test = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001090
Paul Duffinb6b89a42021-05-06 16:33:43 +01001091 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001092 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001093 return module
1094}
1095
Paul Duffin42df1442019-03-20 12:45:53 +00001096// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1097func TestHelperLibraryFactory() android.Module {
1098 module := &TestHelperLibrary{}
1099
Colin Crossce6734e2020-06-15 16:09:53 -07001100 module.addHostAndDeviceProperties()
1101 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001102
Colin Cross9a4abed2019-04-24 13:19:28 -07001103 module.Module.properties.Installable = proptools.BoolPtr(true)
1104 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001105 module.Module.linter.test = true
Colin Cross9a4abed2019-04-24 13:19:28 -07001106
Paul Duffin42df1442019-03-20 12:45:53 +00001107 InitJavaModule(module, android.HostAndDeviceSupported)
1108 return module
1109}
1110
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001111// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1112// and makes sure that it is added to the appropriate test suite.
1113//
1114// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1115// compiled against an Android classpath.
1116//
1117// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1118// for host modules.
1119func JavaTestImportFactory() android.Module {
1120 module := &JavaTestImport{}
1121
1122 module.AddProperties(
1123 &module.Import.properties,
1124 &module.prebuiltTestProperties)
1125
1126 module.Import.properties.Installable = proptools.BoolPtr(true)
1127
1128 android.InitPrebuiltModule(module, &module.properties.Jars)
1129 android.InitApexModule(module)
1130 android.InitSdkAwareModule(module)
1131 InitJavaModule(module, android.HostAndDeviceSupported)
1132 return module
1133}
1134
Colin Cross1b16b0e2019-02-12 14:41:32 -08001135// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1136// allow running the test with `atest` or a `TEST_MAPPING` file.
1137//
1138// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1139// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001140func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001141 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001142
Colin Crossce6734e2020-06-15 16:09:53 -07001143 module.addHostProperties()
1144 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001145 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001146
Yuexi Ma627263f2021-03-04 13:47:56 -08001147 InitTestHost(
1148 module,
1149 proptools.BoolPtr(true),
1150 nil,
1151 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001152
Liz Kammerdd849a82020-06-12 16:38:45 -07001153 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001154
Colin Cross05638fc2018-04-09 18:40:24 -07001155 return module
1156}
1157
Yuexi Ma627263f2021-03-04 13:47:56 -08001158func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1159 th.properties.Installable = installable
1160 th.testProperties.Auto_gen_config = autoGenConfig
1161 th.testProperties.Test_suites = testSuites
1162}
1163
Colin Cross05638fc2018-04-09 18:40:24 -07001164//
Colin Cross2fe66872015-03-30 17:20:39 -07001165// Java Binaries (.jar file plus wrapper script)
1166//
1167
Colin Crossf506d872017-07-19 15:53:04 -07001168type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001169 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001170 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001171
1172 // Name of the class containing main to be inserted into the manifest as Main-Class.
1173 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001174
1175 // Names of modules containing JNI libraries that should be installed alongside the host
1176 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001177 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001178}
1179
Colin Crossf506d872017-07-19 15:53:04 -07001180type Binary struct {
1181 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001182
Colin Crossf506d872017-07-19 15:53:04 -07001183 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001184
Colin Cross6b4a32d2017-12-05 13:42:45 -08001185 isWrapperVariant bool
1186
Colin Crossc3315992017-12-08 19:12:36 -08001187 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001188 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001189}
1190
Alex Light24237172017-10-26 09:46:21 -07001191func (j *Binary) HostToolPath() android.OptionalPath {
1192 return android.OptionalPathForPath(j.binaryFile)
1193}
1194
Colin Crossf506d872017-07-19 15:53:04 -07001195func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001196 if ctx.Arch().ArchType == android.Common {
1197 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001198 if j.binaryProperties.Main_class != nil {
1199 if j.properties.Manifest != nil {
1200 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1201 }
1202 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1203 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1204 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1205 }
1206
Colin Cross6b4a32d2017-12-05 13:42:45 -08001207 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001208 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001209 // Handle the binary wrapper
1210 j.isWrapperVariant = true
1211
Colin Cross366938f2017-12-11 16:29:02 -08001212 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001213 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001214 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001215 if ctx.Windows() {
1216 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1217 }
1218
Colin Cross6b4a32d2017-12-05 13:42:45 -08001219 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1220 }
1221
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001222 ext := ""
1223 if ctx.Windows() {
1224 ext = ".bat"
1225 }
1226
Colin Crossc179ea62020-10-09 10:54:15 -07001227 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001228 // of the wrapper variant, which will include the common variant's jar file and any JNI
1229 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001230 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001231 ctx.ModuleName()+ext, j.wrapperFile)
1232 }
Colin Cross2fe66872015-03-30 17:20:39 -07001233}
1234
Colin Crossf506d872017-07-19 15:53:04 -07001235func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -05001236 if ctx.Arch().ArchType == android.Common || ctx.BazelConversionMode() {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001237 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001238 }
1239 if ctx.Arch().ArchType != android.Common || ctx.BazelConversionMode() {
Colin Crosse9fe2942020-11-10 18:12:15 -08001240 // These dependencies ensure the host installation rules will install the jar file and
1241 // the jni libraries when the wrapper is installed.
1242 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1243 ctx.AddVariationDependencies(
1244 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1245 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001246 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001247}
1248
Colin Cross1b16b0e2019-02-12 14:41:32 -08001249// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1250// as well.
1251//
1252// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1253// compiled against the device bootclasspath.
1254//
1255// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1256// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001257func BinaryFactory() android.Module {
1258 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001259
Colin Crossce6734e2020-06-15 16:09:53 -07001260 module.addHostAndDeviceProperties()
1261 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001262
Colin Cross9ae1b922018-06-26 17:59:05 -07001263 module.Module.properties.Installable = proptools.BoolPtr(true)
1264
Colin Cross6b4a32d2017-12-05 13:42:45 -08001265 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1266 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001267 android.InitBazelModule(module)
1268
Colin Cross36242852017-06-23 15:06:31 -07001269 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001270}
1271
Colin Cross1b16b0e2019-02-12 14:41:32 -08001272// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1273//
1274// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1275// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001276func BinaryHostFactory() android.Module {
1277 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001278
Colin Crossce6734e2020-06-15 16:09:53 -07001279 module.addHostProperties()
1280 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001281
Colin Cross9ae1b922018-06-26 17:59:05 -07001282 module.Module.properties.Installable = proptools.BoolPtr(true)
1283
Colin Cross6b4a32d2017-12-05 13:42:45 -08001284 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1285 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001286 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001287 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001288}
1289
1290//
1291// Java prebuilts
1292//
1293
Colin Cross74d73e22017-08-02 11:05:49 -07001294type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001295 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001296
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001297 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1298 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001299 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001300
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001301 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1302 // specified.
1303 Min_sdk_version *string
1304
Colin Cross535e2cf2017-10-20 17:57:49 -07001305 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001306
Paul Duffin869de142021-07-15 14:14:41 +01001307 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001308 Permitted_packages []string
1309
Jiyong Park1be96912018-05-28 18:02:19 +09001310 // List of shared java libs that this module has dependencies to
1311 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001312
1313 // List of files to remove from the jar file(s)
1314 Exclude_files []string
1315
1316 // List of directories to remove from the jar file(s)
1317 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001318
1319 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001320 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001321
1322 // set the name of the output
1323 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001324
1325 Aidl struct {
1326 // directories that should be added as include directories for any aidl sources of modules
1327 // that depend on this module, as well as to aidl for this module.
1328 Export_include_dirs []string
1329 }
Colin Cross74d73e22017-08-02 11:05:49 -07001330}
1331
1332type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001333 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001334 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001335 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001336 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001337 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001338 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001339
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001340 // Functionality common to Module and Import.
1341 embeddableInModuleAndImport
1342
Liz Kammerd6c31d22020-08-05 15:40:41 -07001343 hiddenAPI
1344 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001345 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001346
Colin Cross74d73e22017-08-02 11:05:49 -07001347 properties ImportProperties
1348
Liz Kammerd6c31d22020-08-05 15:40:41 -07001349 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001350 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001351 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001352
Colin Cross0a6e0072017-08-30 14:24:55 -07001353 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001354 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001355 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001356
1357 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001358
1359 sdkVersion android.SdkSpec
1360 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001361}
1362
Paul Duffin630b11e2021-07-15 13:35:26 +01001363var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1364
1365func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1366 return j.properties.Permitted_packages
1367}
1368
Jiyong Park92315372021-04-02 08:45:46 +09001369func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1370 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001371}
1372
Jiyong Parkf1691d22021-03-29 20:11:58 +09001373func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001374 return "none"
1375}
1376
Jiyong Park92315372021-04-02 08:45:46 +09001377func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001378 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001379 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001380 }
Jiyong Park92315372021-04-02 08:45:46 +09001381 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001382}
1383
Jiyong Park92315372021-04-02 08:45:46 +09001384func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1385 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001386}
1387
Colin Cross74d73e22017-08-02 11:05:49 -07001388func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001389 return &j.prebuilt
1390}
1391
Colin Cross74d73e22017-08-02 11:05:49 -07001392func (j *Import) PrebuiltSrcs() []string {
1393 return j.properties.Jars
1394}
1395
1396func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001397 return j.prebuilt.Name(j.ModuleBase.Name())
1398}
1399
Jiyong Park0b238752019-10-29 11:23:10 +09001400func (j *Import) Stem() string {
1401 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1402}
1403
Jiyong Park618922e2020-01-08 13:35:43 +09001404func (a *Import) JacocoReportClassesFile() android.Path {
1405 return nil
1406}
1407
Bill Peckhama41a6962021-01-11 10:58:54 -08001408func (j *Import) LintDepSets() LintDepSets {
1409 return LintDepSets{}
1410}
1411
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001412func (j *Import) getStrictUpdatabilityLinting() bool {
1413 return false
1414}
1415
1416func (j *Import) setStrictUpdatabilityLinting(bool) {
1417}
1418
Colin Cross74d73e22017-08-02 11:05:49 -07001419func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001420 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001421
1422 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001423 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001424 }
Colin Cross1e676be2016-10-12 14:38:15 -07001425}
1426
Colin Cross74d73e22017-08-02 11:05:49 -07001427func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09001428 j.sdkVersion = j.SdkVersion(ctx)
1429 j.minSdkVersion = j.MinSdkVersion(ctx)
1430
Colin Cross56a83212020-09-15 18:30:11 -07001431 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1432 j.hideApexVariantFromMake = true
1433 }
1434
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001435 if ctx.Windows() {
1436 j.HideFromMake()
1437 }
1438
Colin Cross8a497952019-03-05 22:25:09 -08001439 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001440
Jiyong Park0b238752019-10-29 11:23:10 +09001441 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001442 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001443 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1444 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001445 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001446 inputFile := outputFile
1447 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1448 TransformJetifier(ctx, outputFile, inputFile)
1449 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001450 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001451 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001452
Liz Kammerd6c31d22020-08-05 15:40:41 -07001453 var flags javaBuilderFlags
1454
Jiyong Park1be96912018-05-28 18:02:19 +09001455 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001456 tag := ctx.OtherModuleDependencyTag(module)
1457
Colin Crossdcf71b22021-02-01 13:59:03 -08001458 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1459 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001460 switch tag {
1461 case libTag, staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001462 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001463 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001464 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001465 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001466 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001467 switch tag {
1468 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001469 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001470 }
1471 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001472
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001473 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001474 })
1475
Nan Zhang4973ecf2018-08-10 13:42:12 -07001476 if Bool(j.properties.Installable) {
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001477 var installDir android.InstallPath
1478 if ctx.InstallInTestcases() {
1479 var archDir string
1480 if !ctx.Host() {
1481 archDir = ctx.DeviceConfig().DeviceArch()
1482 }
1483 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1484 } else {
1485 installDir = android.PathForModuleInstall(ctx, "framework")
1486 }
1487 ctx.InstallFile(installDir, jarName, outputFile)
Nan Zhang4973ecf2018-08-10 13:42:12 -07001488 }
Jiyong Park19604de2020-03-24 16:44:11 +09001489
1490 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001491
Paul Duffin064b70c2020-11-02 17:32:38 +00001492 if ctx.Device() {
1493 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1494 // obtained from the associated deapexer module.
1495 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1496 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001497 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001498 di := android.FindDeapexerProviderForModule(ctx)
1499 if di == nil {
1500 return // An error has been reported by FindDeapexerProviderForModule.
1501 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001502 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001503 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1504 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001505 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1506 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001507
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001508 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001509 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001510 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1511 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001512
1513 // Initialize the hiddenapi structure.
1514 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001515 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001516 // This should never happen as a variant for a prebuilt_apex is only created if the
1517 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001518 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001519 }
1520 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001521 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001522 if sdkDep.invalidVersion {
1523 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1524 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1525 } else if sdkDep.useFiles {
1526 // sdkDep.jar is actually equivalent to turbine header.jar.
1527 flags.classpath = append(flags.classpath, sdkDep.jars...)
1528 }
1529
1530 // Dex compilation
1531
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001532 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1533 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001534 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001535 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1536
Paul Duffin612e6102021-02-02 13:38:13 +00001537 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001538 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001539 if ctx.Failed() {
1540 return
1541 }
1542
Paul Duffin74d18d12021-05-14 14:18:47 +01001543 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001544 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001545
1546 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001547 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001548
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001549 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001550 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001551 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001552 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001553
1554 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1555 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1556 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1557 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1558 AidlIncludeDirs: j.exportAidlIncludeDirs,
1559 })
Colin Cross2fe66872015-03-30 17:20:39 -07001560}
1561
Paul Duffinaa55f742020-10-06 17:20:13 +01001562func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1563 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001564 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001565 return android.Paths{j.combinedClasspathFile}, nil
1566 default:
1567 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1568 }
1569}
1570
1571var _ android.OutputFileProducer = (*Import)(nil)
1572
Nan Zhanged19fc32017-10-19 13:06:22 -07001573func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001574 if j.combinedClasspathFile == nil {
1575 return nil
1576 }
Colin Cross37f6d792018-07-12 12:28:41 -07001577 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001578}
1579
Colin Cross331a1212018-08-15 20:40:52 -07001580func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001581 if j.combinedClasspathFile == nil {
1582 return nil
1583 }
Colin Cross331a1212018-08-15 20:40:52 -07001584 return android.Paths{j.combinedClasspathFile}
1585}
1586
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001587func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001588 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001589}
1590
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001591func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001592 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001593}
1594
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001595func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1596 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001597}
1598
Jiyong Park45bf82e2020-12-15 22:29:02 +09001599var _ android.ApexModule = (*Import)(nil)
1600
1601// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001602func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001603 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001604}
1605
Jiyong Park45bf82e2020-12-15 22:29:02 +09001606// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001607func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1608 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001609 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001610 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001611 return fmt.Errorf("min_sdk_version is not specified")
1612 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001613 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001614 return nil
1615 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001616 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1617 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001618 }
Jooyung Han749dc692020-04-15 11:03:39 +09001619 return nil
1620}
1621
Paul Duffinfef55002021-06-17 14:56:05 +01001622// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1623// java_sdk_library_import with the specified base module name requires to be exported from a
1624// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001625func requiredFilesFromPrebuiltApexForImport(name string) []string {
1626 // Add the dex implementation jar to the set of exported files.
1627 return []string{
1628 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001629 }
1630}
1631
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001632// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1633// the java library with the specified name.
1634func apexRootRelativePathToJavaLib(name string) string {
1635 return filepath.Join("javalib", name+".jar")
1636}
1637
Paul Duffinfef55002021-06-17 14:56:05 +01001638var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1639
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001640func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001641 name := j.BaseModuleName()
1642 return requiredFilesFromPrebuiltApexForImport(name)
1643}
1644
albaltai36ff7dc2018-12-25 14:35:23 +08001645// Add compile time check for interface implementation
1646var _ android.IDEInfo = (*Import)(nil)
1647var _ android.IDECustomizedModuleName = (*Import)(nil)
1648
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001649// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001650
1651func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1652 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1653}
1654
1655func (j *Import) IDECustomizedModuleName() string {
1656 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1657 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1658 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001659 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001660}
1661
Colin Cross74d73e22017-08-02 11:05:49 -07001662var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001663
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001664func (j *Import) IsInstallable() bool {
1665 return Bool(j.properties.Installable)
1666}
1667
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001668var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001669
Colin Cross1b16b0e2019-02-12 14:41:32 -08001670// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1671//
1672// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1673// compiled against an Android classpath.
1674//
1675// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1676// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001677func ImportFactory() android.Module {
1678 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001679
Liz Kammerd6c31d22020-08-05 15:40:41 -07001680 module.AddProperties(
1681 &module.properties,
1682 &module.dexer.dexProperties,
1683 )
Colin Cross74d73e22017-08-02 11:05:49 -07001684
Paul Duffin71b33cc2021-06-23 11:39:47 +01001685 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001686
Liz Kammerd6c31d22020-08-05 15:40:41 -07001687 module.dexProperties.Optimize.EnabledByDefault = false
1688
Colin Cross74d73e22017-08-02 11:05:49 -07001689 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001690 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001691 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001692 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001693 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001694 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001695}
1696
Colin Cross1b16b0e2019-02-12 14:41:32 -08001697// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1698// module.
1699//
1700// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1701// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001702func ImportFactoryHost() android.Module {
1703 module := &Import{}
1704
1705 module.AddProperties(&module.properties)
1706
1707 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001708 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001709 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001710 return module
1711}
1712
Colin Cross42be7612019-02-21 18:12:14 -08001713// dex_import module
1714
1715type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001716 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001717
1718 // set the name of the output
1719 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001720}
1721
1722type DexImport struct {
1723 android.ModuleBase
1724 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001725 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001726 prebuilt android.Prebuilt
1727
1728 properties DexImportProperties
1729
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001730 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001731
1732 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001733
1734 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001735}
1736
1737func (j *DexImport) Prebuilt() *android.Prebuilt {
1738 return &j.prebuilt
1739}
1740
1741func (j *DexImport) PrebuiltSrcs() []string {
1742 return j.properties.Jars
1743}
1744
1745func (j *DexImport) Name() string {
1746 return j.prebuilt.Name(j.ModuleBase.Name())
1747}
1748
Jiyong Park0b238752019-10-29 11:23:10 +09001749func (j *DexImport) Stem() string {
1750 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1751}
1752
Jiyong Park77acec62020-06-01 21:39:15 +09001753func (a *DexImport) JacocoReportClassesFile() android.Path {
1754 return nil
1755}
1756
Colin Cross08dca382020-07-21 20:31:17 -07001757func (a *DexImport) LintDepSets() LintDepSets {
1758 return LintDepSets{}
1759}
1760
Martin Stjernholm6d415272020-01-31 17:10:36 +00001761func (j *DexImport) IsInstallable() bool {
1762 return true
1763}
1764
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001765func (j *DexImport) getStrictUpdatabilityLinting() bool {
1766 return false
1767}
1768
1769func (j *DexImport) setStrictUpdatabilityLinting(bool) {
1770}
1771
Colin Cross42be7612019-02-21 18:12:14 -08001772func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1773 if len(j.properties.Jars) != 1 {
1774 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
1775 }
1776
Colin Cross56a83212020-09-15 18:30:11 -07001777 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1778 if !apexInfo.IsForPlatform() {
1779 j.hideApexVariantFromMake = true
1780 }
1781
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001782 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1783 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08001784 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
1785
1786 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
1787 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
1788
1789 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08001790 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08001791
1792 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
1793 rule.Temporary(temporary)
1794
1795 // use zip2zip to uncompress classes*.dex files
1796 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08001797 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08001798 FlagWithInput("-i ", inputJar).
1799 FlagWithOutput("-o ", temporary).
1800 FlagWithArg("-0 ", "'classes*.dex'")
1801
1802 // use zipalign to align uncompressed classes*.dex files
1803 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08001804 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08001805 Flag("-f").
1806 Text("4").
1807 Input(temporary).
1808 Output(dexOutputFile)
1809
1810 rule.DeleteTemporaryFiles()
1811
Colin Crossf1a035e2020-11-16 17:32:30 -08001812 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08001813 } else {
1814 ctx.Build(pctx, android.BuildParams{
1815 Rule: android.Cp,
1816 Input: inputJar,
1817 Output: dexOutputFile,
1818 })
1819 }
1820
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001821 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08001822
Jaewoong Jung4b97a562020-12-17 09:43:28 -08001823 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08001824
Colin Cross56a83212020-09-15 18:30:11 -07001825 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09001826 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
1827 j.Stem()+".jar", dexOutputFile)
1828 }
Colin Cross42be7612019-02-21 18:12:14 -08001829}
1830
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001831func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08001832 return j.dexJarFile
1833}
1834
Jiyong Park45bf82e2020-12-15 22:29:02 +09001835var _ android.ApexModule = (*DexImport)(nil)
1836
1837// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001838func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1839 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001840 // we don't check prebuilt modules for sdk_version
1841 return nil
1842}
1843
Colin Cross42be7612019-02-21 18:12:14 -08001844// dex_import imports a `.jar` file containing classes.dex files.
1845//
1846// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
1847// to the device.
1848func DexImportFactory() android.Module {
1849 module := &DexImport{}
1850
1851 module.AddProperties(&module.properties)
1852
1853 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001854 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001855 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08001856 return module
1857}
1858
Colin Cross89536d42017-07-07 14:35:50 -07001859//
1860// Defaults
1861//
1862type Defaults struct {
1863 android.ModuleBase
1864 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001865 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07001866}
1867
Colin Cross1b16b0e2019-02-12 14:41:32 -08001868// java_defaults provides a set of properties that can be inherited by other java or android modules.
1869//
1870// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
1871// property in the defaults module that exists in the depending module will be prepended to the depending module's
1872// value for that property.
1873//
1874// Example:
1875//
1876// java_defaults {
1877// name: "example_defaults",
1878// srcs: ["common/**/*.java"],
1879// javacflags: ["-Xlint:all"],
1880// aaptflags: ["--auto-add-overlay"],
1881// }
1882//
1883// java_library {
1884// name: "example",
1885// defaults: ["example_defaults"],
1886// srcs: ["example/**/*.java"],
1887// }
1888//
1889// is functionally identical to:
1890//
1891// java_library {
1892// name: "example",
1893// srcs: [
1894// "common/**/*.java",
1895// "example/**/*.java",
1896// ],
1897// javacflags: ["-Xlint:all"],
1898// }
Paul Duffin47357662019-12-05 14:07:14 +00001899func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07001900 module := &Defaults{}
1901
Colin Cross89536d42017-07-07 14:35:50 -07001902 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08001903 &CommonProperties{},
1904 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09001905 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07001906 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08001907 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08001908 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07001909 &aaptProperties{},
1910 &androidLibraryProperties{},
1911 &appProperties{},
1912 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08001913 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00001914 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07001915 &ImportProperties{},
1916 &AARImportProperties{},
1917 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01001918 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08001919 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09001920 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07001921 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07001922 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08001923 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07001924 )
1925
1926 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07001927 return module
1928}
Nan Zhangea568a42017-11-08 21:20:04 -08001929
Sasha Smundak2a4549e2018-11-05 16:49:08 -08001930func kytheExtractJavaFactory() android.Singleton {
1931 return &kytheExtractJavaSingleton{}
1932}
1933
1934type kytheExtractJavaSingleton struct {
1935}
1936
1937func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
1938 var xrefTargets android.Paths
1939 ctx.VisitAllModules(func(module android.Module) {
1940 if javaModule, ok := module.(xref); ok {
1941 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
1942 }
1943 })
1944 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
1945 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07001946 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08001947 }
1948}
1949
Nan Zhangea568a42017-11-08 21:20:04 -08001950var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07001951var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08001952var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08001953var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001954
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001955// Add class loader context (CLC) of a given dependency to the current CLC.
1956func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
1957 clcMap dexpreopt.ClassLoaderContextMap) {
1958
1959 dep, ok := depModule.(UsesLibraryDependency)
1960 if !ok {
1961 return
1962 }
1963
Ulya Trafimovich840efb62021-07-15 14:34:40 +01001964 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
1965
1966 var sdkLib *string
1967 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
1968 // A shared SDK library. This should be added as a top-level CLC element.
1969 sdkLib = &depName
1970 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
1971 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
1972 // property. This should be handled in the same way as a shared SDK library.
1973 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001974 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001975
1976 depTag := ctx.OtherModuleDependencyTag(depModule)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +01001977 if depTag == libTag {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001978 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +01001979 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok &&
1980 tag.sdkVersion == dexpreopt.AnySdkVersion && tag.implicit {
1981 // Ok, propagate <uses-library> through non-compatibility implicit <uses-library>
1982 // dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001983 } else if depTag == staticLibTag {
1984 // Propagate <uses-library> through static library dependencies, unless it is a component
1985 // library (such as stubs). Component libraries have a dependency on their SDK library,
1986 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01001987 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001988 return
1989 }
1990 } else {
1991 // Don't propagate <uses-library> for other dependency tags.
1992 return
1993 }
1994
Ulya Trafimovich840efb62021-07-15 14:34:40 +01001995 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
1996 // and its CLC should be added as subtree of that node. Otherwise the library is not a
1997 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
1998 // from its CLC should be added to the current CLC.
1999 if sdkLib != nil {
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +01002000 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false, true,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002001 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002002 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002003 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2004 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002005}
Wei Libafb6d62021-12-10 03:14:59 -08002006
2007type javaLibraryAttributes struct {
2008 Srcs bazel.LabelListAttribute
2009 Deps bazel.LabelListAttribute
2010 Javacopts bazel.StringListAttribute
2011}
2012
Sam Delmericofde9fb52022-01-28 20:53:38 +00002013func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) *javaLibraryAttributes {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002014 var srcs bazel.LabelListAttribute
2015 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2016 for axis, configToProps := range archVariantProps {
2017 for config, _props := range configToProps {
2018 if archProps, ok := _props.(*CommonProperties); ok {
2019 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2020 srcs.SetSelectValue(axis, config, archSrcs)
2021 }
2022 }
2023 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002024
2025 javaSrcPartition := "java"
2026 protoSrcPartition := "proto"
2027 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
2028 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2029 protoSrcPartition: android.ProtoSrcLabelPartition,
2030 })
2031
Wei Libafb6d62021-12-10 03:14:59 -08002032 attrs := &javaLibraryAttributes{
Sam Delmericoc7681022022-02-04 21:01:20 +00002033 Srcs: srcPartitions[javaSrcPartition],
Wei Libafb6d62021-12-10 03:14:59 -08002034 }
2035
2036 if m.properties.Javacflags != nil {
2037 attrs.Javacopts = bazel.MakeStringListAttribute(m.properties.Javacflags)
2038 }
2039
Sam Delmericofde9fb52022-01-28 20:53:38 +00002040 var deps bazel.LabelList
Sam Delmerico881d7202022-02-23 15:18:56 +00002041 sdkVersion := m.SdkVersion(ctx)
2042 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2043 // TODO(b/220869005) remove forced dependency on current public android.jar
2044 deps.Add(&bazel.Label{Label: "//prebuilts/sdk:public_current_android_sdk_java_import"})
2045 }
Wei Libafb6d62021-12-10 03:14:59 -08002046 if m.properties.Libs != nil {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002047 deps.Append(android.BazelLabelForModuleDeps(ctx, m.properties.Libs))
Wei Libafb6d62021-12-10 03:14:59 -08002048 }
Sam Delmericofde9fb52022-01-28 20:53:38 +00002049 if m.properties.Static_libs != nil {
2050 //TODO(b/217236083) handle static libs similarly to Soong
2051 deps.Append(android.BazelLabelForModuleDeps(ctx, m.properties.Static_libs))
2052 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002053
2054 protoDeps := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2055 if protoDeps != nil {
2056 deps.Add(protoDeps)
2057 }
2058
Sam Delmericofde9fb52022-01-28 20:53:38 +00002059 attrs.Deps = bazel.MakeLabelListAttribute(deps)
2060
2061 return attrs
2062}
2063
2064func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
2065 attrs := m.convertLibraryAttrsBp2Build(ctx)
Wei Libafb6d62021-12-10 03:14:59 -08002066
2067 props := bazel.BazelTargetModuleProperties{
2068 Rule_class: "java_library",
2069 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2070 }
2071
2072 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2073}
2074
2075type javaBinaryHostAttributes struct {
2076 Srcs bazel.LabelListAttribute
2077 Deps bazel.LabelListAttribute
2078 Main_class string
2079 Jvm_flags bazel.StringListAttribute
Sam Delmerico4e272292022-01-06 20:03:51 +00002080 Javacopts bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002081}
2082
2083// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2084func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
2085 mainClass := ""
2086 if m.binaryProperties.Main_class != nil {
2087 mainClass = *m.binaryProperties.Main_class
2088 }
2089 if m.properties.Manifest != nil {
2090 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2091 if err != nil {
2092 return
2093 }
2094 mainClass = mainClassInManifest
2095 }
2096 srcs := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrcExcludes(ctx, m.properties.Srcs, m.properties.Exclude_srcs))
2097 attrs := &javaBinaryHostAttributes{
2098 Srcs: srcs,
2099 Main_class: mainClass,
2100 }
2101
Sam Delmerico4e272292022-01-06 20:03:51 +00002102 if m.properties.Javacflags != nil {
2103 attrs.Javacopts = bazel.MakeStringListAttribute(m.properties.Javacflags)
2104 }
2105
Wei Libafb6d62021-12-10 03:14:59 -08002106 // Attribute deps
2107 deps := []string{}
2108 if m.properties.Static_libs != nil {
2109 deps = append(deps, m.properties.Static_libs...)
2110 }
2111 if m.binaryProperties.Jni_libs != nil {
2112 deps = append(deps, m.binaryProperties.Jni_libs...)
2113 }
2114 if len(deps) > 0 {
2115 attrs.Deps = bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, deps))
2116 }
2117
2118 // Attribute jvm_flags
2119 if m.binaryProperties.Jni_libs != nil {
2120 jniLibPackages := map[string]bool{}
2121 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2122 jniLibPackage := jniLibLabel.Label
2123 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2124 if indexOfColon > 0 {
2125 // JNI lib from other package
2126 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2127 } else if indexOfColon == 0 {
2128 // JNI lib in the same package of java_binary
2129 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2130 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2131 }
2132 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2133 jniLibPackages[jniLibPackage] = true
2134 }
2135 }
2136 jniLibPaths := []string{}
2137 for jniLibPackage, _ := range jniLibPackages {
2138 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2139 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2140 }
2141 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2142 }
2143
2144 props := bazel.BazelTargetModuleProperties{
2145 Rule_class: "java_binary",
2146 }
2147
2148 // Create the BazelTargetModule.
2149 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2150}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002151
2152type bazelJavaImportAttributes struct {
2153 Jars bazel.LabelListAttribute
2154}
2155
2156// java_import bp2Build converter.
2157func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2158 //TODO(b/209577426): Support multiple arch variants
2159 jars := bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrcExcludes(ctx, i.properties.Jars, []string(nil)))
2160
2161 attrs := &bazelJavaImportAttributes{
2162 Jars: jars,
2163 }
2164 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2165
2166 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
2167
2168}