blob: 13f4c807ebd9c8a6ec23ff755441698ec120b911 [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 Trafimovichf5d91bb2022-05-04 12:00:02 +0100303 sdkVersion int // SDK version in which the library appared as a standalone library.
304 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100305}
306
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100307func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100308 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000309 dependencyTag: dependencyTag{
310 name: fmt.Sprintf("uses-library-%d", sdkVersion),
311 runtimeLinked: true,
312 },
313 sdkVersion: sdkVersion,
314 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100315 }
316}
317
Jiyong Park8be103b2019-11-08 15:53:48 +0900318func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700319 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900320}
321
Colin Crossbe1da472017-07-07 15:59:46 -0700322var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800323 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000324 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800325 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000326 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
327 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800328 pluginTag = dependencyTag{name: "plugin", toolchain: true}
329 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
330 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000331 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
332 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800333 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000334 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
335 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800336 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800337 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
338 certificateTag = dependencyTag{name: "certificate"}
339 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800340 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000341 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800342 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
343 jniInstallTag = installDependencyTag{name: "jni install"}
344 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100345 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
346 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
347 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
348 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
349 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700350)
Colin Cross2fe66872015-03-30 17:20:39 -0700351
Jiyong Park83dc74b2020-01-14 18:38:44 +0900352func IsLibDepTag(depTag blueprint.DependencyTag) bool {
353 return depTag == libTag
354}
355
356func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
357 return depTag == staticLibTag
358}
359
Colin Crossfc3674a2017-09-18 17:41:52 -0700360type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100361 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700362
Colin Cross6cef4812019-10-17 14:23:50 -0700363 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
364 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100365
366 // The default system modules to use. Will be an empty string if no system
367 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700368 systemModules string
369
Pete Gilline3d44b22020-06-29 11:28:51 +0100370 // The modules that will be added to the classpath regardless of the Java language level targeted
371 classpath []string
372
Colin Cross6cef4812019-10-17 14:23:50 -0700373 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100374 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700375 java9Classpath []string
376
Colin Crossa97c5d32018-03-28 14:58:31 -0700377 frameworkResModule string
378
Colin Cross86a60ae2018-05-29 14:44:55 -0700379 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700380 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100381
382 noStandardLibs, noFrameworksLibs bool
383}
384
385func (s sdkDep) hasStandardLibs() bool {
386 return !s.noStandardLibs
387}
388
389func (s sdkDep) hasFrameworkLibs() bool {
390 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700391}
392
Colin Crossa4f08812018-10-02 22:03:40 -0700393type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700394 name string
395 path android.Path
396 target android.Target
397 coverageFile android.OptionalPath
398 unstrippedFile android.Path
Colin Crossa4f08812018-10-02 22:03:40 -0700399}
400
Jiyong Parkf1691d22021-03-29 20:11:58 +0900401func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700402 sdkDep := decodeSdkDep(ctx, sdkContext)
403 if sdkDep.useModule {
404 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
405 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
406 ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
407 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
408 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.LegacyCorePlatformBootclasspathLibraries...)
409 }
410 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
411 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
412 }
413 }
414 if sdkDep.systemModules != "" {
415 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
416 }
417}
418
Colin Cross32f676a2017-09-06 13:41:06 -0700419type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700420 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
421 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
422 // systemModules and java9Classpath instead.
423 bootClasspath classpath
424
425 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
426 // contains header jars for all static and non-static dependencies.
427 classpath classpath
428
429 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
430 // header jars for all non-static dependencies. Static dependencies have already been
431 // combined into the program jar.
432 dexClasspath classpath
433
434 // java9Classpath is the list of jars that will be added to the classpath when targeting
435 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
436 // are provided by systemModules.
437 java9Classpath classpath
438
Colin Cross748b2d82020-11-19 13:52:06 -0800439 processorPath classpath
440 errorProneProcessorPath classpath
441 processorClasses []string
442 staticJars android.Paths
443 staticHeaderJars android.Paths
444 staticResourceJars android.Paths
445 aidlIncludeDirs android.Paths
446 srcs android.Paths
447 srcJars android.Paths
448 systemModules *systemModules
449 aidlPreprocess android.OptionalPath
450 kotlinStdlib android.Paths
451 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700452 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800453
454 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700455}
Colin Cross2fe66872015-03-30 17:20:39 -0700456
Colin Cross54250902017-12-05 09:28:08 -0800457func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
458 for _, f := range dep.Srcs() {
459 if f.Ext() != ".jar" {
460 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
461 ctx.OtherModuleName(dep.(blueprint.Module)))
462 }
463 }
464}
465
Jiyong Parkf1691d22021-03-29 20:11:58 +0900466func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700467 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700468 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700469 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900470 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca8d3e0bb2022-01-20 15:21:51 +0000471 } else {
Sorin Basca18ecf612022-01-23 09:01:07 +0000472 return JAVA_VERSION_11
Nan Zhang357466b2018-04-17 17:38:36 -0700473 }
Nan Zhang357466b2018-04-17 17:38:36 -0700474}
475
Colin Cross1e743852019-10-28 11:37:20 -0700476type javaVersion int
477
478const (
479 JAVA_VERSION_UNSUPPORTED = 0
480 JAVA_VERSION_6 = 6
481 JAVA_VERSION_7 = 7
482 JAVA_VERSION_8 = 8
483 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000484 JAVA_VERSION_11 = 11
Colin Cross1e743852019-10-28 11:37:20 -0700485)
486
487func (v javaVersion) String() string {
488 switch v {
489 case JAVA_VERSION_6:
490 return "1.6"
491 case JAVA_VERSION_7:
492 return "1.7"
493 case JAVA_VERSION_8:
494 return "1.8"
495 case JAVA_VERSION_9:
496 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000497 case JAVA_VERSION_11:
498 return "11"
Colin Cross1e743852019-10-28 11:37:20 -0700499 default:
500 return "unsupported"
501 }
502}
503
504// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
505func (v javaVersion) usesJavaModules() bool {
506 return v >= 9
507}
508
509func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100510 switch javaVersion {
511 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700512 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100513 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700514 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100515 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700516 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100517 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700518 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000519 case "11":
520 return JAVA_VERSION_11
521 case "10":
522 ctx.PropertyErrorf("java_version", "Java language levels 10 is not supported")
Colin Cross1e743852019-10-28 11:37:20 -0700523 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100524 default:
525 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700526 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100527 }
528}
529
Colin Cross2fe66872015-03-30 17:20:39 -0700530//
531// Java libraries (.jar file)
532//
533
Colin Crossf506d872017-07-19 15:53:04 -0700534type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700535 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700536
537 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.Paths)
Colin Cross2fe66872015-03-30 17:20:39 -0700538}
539
Jiyong Park45bf82e2020-12-15 22:29:02 +0900540var _ android.ApexModule = (*Library)(nil)
541
satayevd604b212021-07-21 14:23:52 +0100542// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100543type PermittedPackagesForUpdatableBootJars interface {
544 PermittedPackagesForUpdatableBootJars() []string
545}
546
547var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
548
549func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
550 return j.properties.Permitted_packages
551}
552
Colin Cross42be7612019-02-21 18:12:14 -0800553func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000554 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700555 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000556 return true
557 }
558
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000559 // Store uncompressed (and do not strip) dex files from boot class path jars.
560 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
561 return true
562 }
563
564 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000565 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000566 return true
567 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800568 if ctx.Config().UncompressPrivAppDex() &&
569 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
570 return true
571 }
572
Colin Cross2fc72f62018-12-21 12:59:54 -0800573 return false
574}
575
Jiakai Zhang22450f22021-10-11 03:05:20 +0000576// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
577func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
578 if dexer.dexProperties.Uncompress_dex == nil {
579 // If the value was not force-set by the user, use reasonable default based on the module.
580 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
581 }
582}
583
Colin Crossf506d872017-07-19 15:53:04 -0700584func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +0900585 j.sdkVersion = j.SdkVersion(ctx)
586 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000587 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900588
Colin Cross56a83212020-09-15 18:30:11 -0700589 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
590 if !apexInfo.IsForPlatform() {
591 j.hideApexVariantFromMake = true
592 }
593
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100594 j.checkSdkVersions(ctx)
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000595 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
596 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross43f08db2018-11-12 10:13:39 -0800597 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
Jiakai Zhang22450f22021-10-11 03:05:20 +0000598 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Liz Kammera7a64f32020-07-09 15:16:41 -0700599 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100600 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Jaewoong Junga24af3b2019-05-13 09:23:20 -0700601 j.compile(ctx, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700602
bralee1fbf4402020-05-21 10:11:59 +0800603 // Collect the module directory for IDE info in java/jdeps.go.
604 j.modulePaths = append(j.modulePaths, ctx.ModuleDir())
605
Colin Cross56a83212020-09-15 18:30:11 -0700606 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900607 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700608 var extraInstallDeps android.Paths
609 if j.InstallMixin != nil {
610 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
611 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700612 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
613 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800614 j.hostdexInstallFile = ctx.InstallFile(
615 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700616 j.Stem()+"-hostdex.jar", j.outputFile)
617 }
618 var installDir android.InstallPath
619 if ctx.InstallInTestcases() {
620 var archDir string
621 if !ctx.Host() {
622 archDir = ctx.DeviceConfig().DeviceArch()
623 }
624 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
625 } else {
626 installDir = android.PathForModuleInstall(ctx, "framework")
627 }
628 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700629 }
Colin Crossb7a63242015-04-16 14:09:14 -0700630}
631
Colin Crossf506d872017-07-19 15:53:04 -0700632func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700633 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100634 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700635}
636
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000637const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000638 aidlIncludeDir = "aidl"
639 javaDir = "java"
640 jarFileSuffix = ".jar"
641 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000642)
643
Paul Duffina0dbf432019-12-05 11:25:53 +0000644// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffina04c1072020-03-02 10:16:35 +0000645func sdkSnapshotFilePathForJar(osPrefix, name string) string {
646 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000647}
648
Paul Duffina04c1072020-03-02 10:16:35 +0000649func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
650 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000651}
652
Paul Duffin13879572019-11-28 14:31:38 +0000653type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000654 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000655
656 // Function to retrieve the appropriate output jar (implementation or header) from
657 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000658 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
659
660 // Function to compute the snapshot relative path to which the named library's
661 // jar should be copied.
662 snapshotPathGetter func(osPrefix, name string) string
663
664 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
665 // files like aidl files should also be copied.
666 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000667}
668
Paul Duffindb170e42020-12-08 17:48:25 +0000669const (
670 onlyCopyJarToSnapshot = true
671 copyEverythingToSnapshot = false
672)
673
Paul Duffin296701e2021-07-14 10:29:36 +0100674func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
675 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000676}
677
678func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
679 _, ok := module.(*Library)
680 return ok
681}
682
Paul Duffin3a4eb502020-03-19 16:11:18 +0000683func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
684 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000685}
Paul Duffina0dbf432019-12-05 11:25:53 +0000686
Paul Duffin14eb4672020-03-02 11:33:02 +0000687func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000688 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000689}
690
691type librarySdkMemberProperties struct {
692 android.SdkMemberPropertiesBase
693
Paul Duffin864e1b42020-05-06 10:23:19 +0100694 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000695 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100696
697 // The list of permitted packages that need to be passed to the prebuilts as they are used to
698 // create the updatable-bcp-packages.txt file.
699 PermittedPackages []string
Paul Duffin14eb4672020-03-02 11:33:02 +0000700}
701
Paul Duffin3a4eb502020-03-19 16:11:18 +0000702func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000703 j := variant.(*Library)
704
Paul Duffindb170e42020-12-08 17:48:25 +0000705 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
706
Paul Duffina551a1c2020-03-17 21:04:24 +0000707 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100708
709 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffin14eb4672020-03-02 11:33:02 +0000710}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000711
Paul Duffin3a4eb502020-03-19 16:11:18 +0000712func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000713 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000714
Paul Duffindb170e42020-12-08 17:48:25 +0000715 memberType := ctx.MemberType().(*librarySdkMemberType)
716
Paul Duffina551a1c2020-03-17 21:04:24 +0000717 exportedJar := p.JarToExport
718 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000719 // Delegate the creation of the snapshot relative path to the member type.
720 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(p.OsPrefix(), ctx.Name())
721
722 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000723 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
724
Paul Duffina551a1c2020-03-17 21:04:24 +0000725 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
726 }
727
Paul Duffin869de142021-07-15 14:14:41 +0100728 if len(p.PermittedPackages) > 0 {
729 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
730 }
731
Paul Duffindb170e42020-12-08 17:48:25 +0000732 // Do not copy anything else to the snapshot.
733 if memberType.onlyCopyJarToSnapshot {
734 return
735 }
736
Paul Duffina551a1c2020-03-17 21:04:24 +0000737 aidlIncludeDirs := p.AidlIncludeDirs
738 if len(aidlIncludeDirs) != 0 {
739 sdkModuleContext := ctx.SdkModuleContext()
740 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000741 // TODO(jiyong): copy parcelable declarations only
742 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
743 for _, file := range aidlFiles {
744 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
745 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000746 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000747
Paul Duffina551a1c2020-03-17 21:04:24 +0000748 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000749 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000750}
751
Colin Cross1b16b0e2019-02-12 14:41:32 -0800752// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
753//
754// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
755// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
756// as a `static_libs` dependency of another module.
757//
758// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
759// a device.
760//
761// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
762// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700763func LibraryFactory() android.Module {
764 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700765
Colin Crossce6734e2020-06-15 16:09:53 -0700766 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700767
Paul Duffin71b33cc2021-06-23 11:39:47 +0100768 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100769
Jiyong Park7f7766d2019-07-25 22:02:35 +0900770 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +0900771 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800772 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900773 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700774 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700775}
776
Colin Cross1b16b0e2019-02-12 14:41:32 -0800777// java_library_static is an obsolete alias for java_library.
778func LibraryStaticFactory() android.Module {
779 return LibraryFactory()
780}
781
782// java_library_host builds and links sources into a `.jar` file for the host.
783//
784// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
785// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700786func LibraryHostFactory() android.Module {
787 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700788
Colin Crossce6734e2020-06-15 16:09:53 -0700789 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700790
Colin Cross9ae1b922018-06-26 17:59:05 -0700791 module.Module.properties.Installable = proptools.BoolPtr(true)
792
Jiyong Park7f7766d2019-07-25 22:02:35 +0900793 android.InitApexModule(module)
Paul Duffinb6b89a42021-05-06 16:33:43 +0100794 android.InitSdkAwareModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800795 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900796 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700797 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700798}
799
800//
Colin Crossb628ea52018-08-14 16:42:33 -0700801// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700802//
803
Dan Shi95d19422020-08-15 12:24:26 -0700804// Test option struct.
805type TestOptions struct {
806 // a list of extra test configuration files that should be installed with the module.
807 Extra_test_configs []string `android:"path,arch_variant"`
Dan Shid79572f2020-11-13 14:33:46 -0800808
809 // If the test is a hostside(no device required) unittest that shall be run during presubmit check.
810 Unit_test *bool
Dan Shi95d19422020-08-15 12:24:26 -0700811}
812
Colin Cross05638fc2018-04-09 18:40:24 -0700813type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700814 // list of compatibility suites (for example "cts", "vts") that the module should be
815 // installed into.
816 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700817
818 // the name of the test configuration (for example "AndroidTest.xml") that should be
819 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800820 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700821
Jack He33338892018-09-19 02:21:28 -0700822 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
823 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800824 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700825
Colin Crossd96ca352018-08-10 16:06:24 -0700826 // list of files or filegroup modules that provide data that should be installed alongside
827 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900828 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700829
830 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
831 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
832 // explicitly.
833 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800834
835 // Add parameterized mainline modules to auto generated test config. The options will be
836 // handled by TradeFed to do downloading and installing the specified modules on the device.
837 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700838
839 // Test options.
840 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800841
842 // Names of modules containing JNI libraries that should be installed alongside the test.
843 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700844
845 // Install the test into a folder named for the module in all test suites.
846 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700847}
848
Liz Kammerdd849a82020-06-12 16:38:45 -0700849type hostTestProperties struct {
850 // list of native binary modules that should be installed alongside the test
851 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000852
853 // list of device binary modules that should be installed alongside the test
854 Data_device_bins []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -0700855}
856
Paul Duffin42df1442019-03-20 12:45:53 +0000857type testHelperLibraryProperties struct {
858 // list of compatibility suites (for example "cts", "vts") that the module should be
859 // installed into.
860 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700861
862 // Install the test into a folder named for the module in all test suites.
863 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +0000864}
865
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000866type prebuiltTestProperties struct {
867 // list of compatibility suites (for example "cts", "vts") that the module should be
868 // installed into.
869 Test_suites []string `android:"arch_variant"`
870
871 // the name of the test configuration (for example "AndroidTest.xml") that should be
872 // installed with the module.
873 Test_config *string `android:"path,arch_variant"`
874}
875
Colin Cross05638fc2018-04-09 18:40:24 -0700876type Test struct {
877 Library
878
879 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -0700880
Dan Shi95d19422020-08-15 12:24:26 -0700881 testConfig android.Path
882 extraTestConfigs android.Paths
883 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -0700884}
885
Liz Kammerdd849a82020-06-12 16:38:45 -0700886type TestHost struct {
887 Test
888
889 testHostProperties hostTestProperties
890}
891
Paul Duffin42df1442019-03-20 12:45:53 +0000892type TestHelperLibrary struct {
893 Library
894
895 testHelperLibraryProperties testHelperLibraryProperties
896}
897
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000898type JavaTestImport struct {
899 Import
900
901 prebuiltTestProperties prebuiltTestProperties
902
903 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -0700904 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000905}
906
Colin Cross24cc4be62021-11-03 14:09:41 -0700907func (j *Test) InstallInTestcases() bool {
908 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
909 // testcases by base_rules.mk.
910 return !j.Host()
911}
912
913func (j *TestHelperLibrary) InstallInTestcases() bool {
914 return true
915}
916
917func (j *JavaTestImport) InstallInTestcases() bool {
918 return true
919}
920
Liz Kammerdd849a82020-06-12 16:38:45 -0700921func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
922 if len(j.testHostProperties.Data_native_bins) > 0 {
923 for _, target := range ctx.MultiTargets() {
924 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
925 }
926 }
927
Sam Delmericob3342ce2022-01-20 21:10:28 +0000928 if len(j.testHostProperties.Data_device_bins) > 0 {
929 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
930 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins...)
931 }
932
Colin Crossf8d9c492021-01-26 11:01:43 -0800933 if len(j.testProperties.Jni_libs) > 0 {
934 for _, target := range ctx.MultiTargets() {
935 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
936 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
937 }
938 }
939
Liz Kammerdd849a82020-06-12 16:38:45 -0700940 j.deps(ctx)
941}
942
Yuexi Ma627263f2021-03-04 13:47:56 -0800943func (j *TestHost) AddExtraResource(p android.Path) {
944 j.extraResources = append(j.extraResources, p)
945}
946
Sam Delmericob3342ce2022-01-20 21:10:28 +0000947func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
948 var configs []tradefed.Config
949 if len(j.testHostProperties.Data_device_bins) > 0 {
950 // add Tradefed configuration to push device bins to device for testing
951 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
952 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
953 for _, bin := range j.testHostProperties.Data_device_bins {
954 fullPath := filepath.Join(remoteDir, bin)
955 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
956 }
957 configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.PushFilePreparer", options})
958 }
959
960 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
961}
962
Colin Cross303e21f2018-08-07 16:49:25 -0700963func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +0000964 j.generateAndroidBuildActionsWithConfig(ctx, nil)
965}
966
967func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +0000968 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
969 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -0700970 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +0000971 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
972 }
Sam Delmericob3342ce2022-01-20 21:10:28 +0000973
Dan Shi6ffaaa82019-09-26 11:41:36 -0700974 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.testProperties.Test_config, j.testProperties.Test_config_template,
Sam Delmericob3342ce2022-01-20 21:10:28 +0000975 j.testProperties.Test_suites, configs, j.testProperties.Auto_gen_config, j.testProperties.Test_options.Unit_test)
Liz Kammerdd849a82020-06-12 16:38:45 -0700976
Colin Cross8a497952019-03-05 22:25:09 -0800977 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -0700978
Dan Shi95d19422020-08-15 12:24:26 -0700979 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
980
Liz Kammerdd849a82020-06-12 16:38:45 -0700981 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
982 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
983 })
984
Sam Delmericob3342ce2022-01-20 21:10:28 +0000985 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
986 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
987 })
988
Colin Crossf8d9c492021-01-26 11:01:43 -0800989 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
990 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
991 if sharedLibInfo.SharedLibrary != nil {
992 // Copy to an intermediate output directory to append "lib[64]" to the path,
993 // so that it's compatible with the default rpath values.
994 var relPath string
995 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
996 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
997 } else {
998 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
999 }
1000 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1001 ctx.Build(pctx, android.BuildParams{
1002 Rule: android.Cp,
1003 Input: sharedLibInfo.SharedLibrary,
1004 Output: relocatedLib,
1005 })
1006 j.data = append(j.data, relocatedLib)
1007 } else {
1008 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1009 }
1010 })
1011
Colin Cross303e21f2018-08-07 16:49:25 -07001012 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001013}
1014
Paul Duffin42df1442019-03-20 12:45:53 +00001015func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1016 j.Library.GenerateAndroidBuildActions(ctx)
1017}
1018
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001019func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1020 j.testConfig = tradefed.AutoGenJavaTestConfig(ctx, j.prebuiltTestProperties.Test_config, nil,
Sam Delmericob3342ce2022-01-20 21:10:28 +00001021 j.prebuiltTestProperties.Test_suites, nil, nil, nil)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001022
1023 j.Import.GenerateAndroidBuildActions(ctx)
1024}
1025
1026type testSdkMemberType struct {
1027 android.SdkMemberTypeBase
1028}
1029
Paul Duffin296701e2021-07-14 10:29:36 +01001030func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1031 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001032}
1033
1034func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1035 _, ok := module.(*Test)
1036 return ok
1037}
1038
Paul Duffin3a4eb502020-03-19 16:11:18 +00001039func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1040 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001041}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001042
Paul Duffin14eb4672020-03-02 11:33:02 +00001043func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1044 return &testSdkMemberProperties{}
1045}
1046
1047type testSdkMemberProperties struct {
1048 android.SdkMemberPropertiesBase
1049
Paul Duffina551a1c2020-03-17 21:04:24 +00001050 JarToExport android.Path
1051 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001052}
1053
Paul Duffin3a4eb502020-03-19 16:11:18 +00001054func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001055 test := variant.(*Test)
1056
1057 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001058 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001059 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001060 }
1061
Paul Duffina551a1c2020-03-17 21:04:24 +00001062 p.JarToExport = implementationJars[0]
1063 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001064}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001065
Paul Duffin3a4eb502020-03-19 16:11:18 +00001066func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001067 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001068
Paul Duffina551a1c2020-03-17 21:04:24 +00001069 exportedJar := p.JarToExport
1070 if exportedJar != nil {
1071 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(p.OsPrefix(), ctx.Name())
1072 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001073
1074 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001075 }
1076
1077 testConfig := p.TestConfig
1078 if testConfig != nil {
1079 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1080 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001081 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1082 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001083}
1084
Colin Cross1b16b0e2019-02-12 14:41:32 -08001085// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1086// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1087//
1088// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1089// compiled against the device bootclasspath.
1090//
1091// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1092// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001093func TestFactory() android.Module {
1094 module := &Test{}
1095
Colin Crossce6734e2020-06-15 16:09:53 -07001096 module.addHostAndDeviceProperties()
1097 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001098
Colin Cross9ae1b922018-06-26 17:59:05 -07001099 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001100 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001101 module.Module.linter.test = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001102
Paul Duffinb6b89a42021-05-06 16:33:43 +01001103 android.InitSdkAwareModule(module)
Colin Cross05638fc2018-04-09 18:40:24 -07001104 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001105 return module
1106}
1107
Paul Duffin42df1442019-03-20 12:45:53 +00001108// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1109func TestHelperLibraryFactory() android.Module {
1110 module := &TestHelperLibrary{}
1111
Colin Crossce6734e2020-06-15 16:09:53 -07001112 module.addHostAndDeviceProperties()
1113 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001114
Colin Cross9a4abed2019-04-24 13:19:28 -07001115 module.Module.properties.Installable = proptools.BoolPtr(true)
1116 module.Module.dexpreopter.isTest = true
Colin Cross014489c2020-06-02 20:09:13 -07001117 module.Module.linter.test = true
Colin Cross9a4abed2019-04-24 13:19:28 -07001118
Paul Duffin42df1442019-03-20 12:45:53 +00001119 InitJavaModule(module, android.HostAndDeviceSupported)
1120 return module
1121}
1122
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001123// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1124// and makes sure that it is added to the appropriate test suite.
1125//
1126// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1127// compiled against an Android classpath.
1128//
1129// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1130// for host modules.
1131func JavaTestImportFactory() android.Module {
1132 module := &JavaTestImport{}
1133
1134 module.AddProperties(
1135 &module.Import.properties,
1136 &module.prebuiltTestProperties)
1137
1138 module.Import.properties.Installable = proptools.BoolPtr(true)
1139
1140 android.InitPrebuiltModule(module, &module.properties.Jars)
1141 android.InitApexModule(module)
1142 android.InitSdkAwareModule(module)
1143 InitJavaModule(module, android.HostAndDeviceSupported)
1144 return module
1145}
1146
Colin Cross1b16b0e2019-02-12 14:41:32 -08001147// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1148// allow running the test with `atest` or a `TEST_MAPPING` file.
1149//
1150// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1151// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001152func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001153 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001154
Colin Crossce6734e2020-06-15 16:09:53 -07001155 module.addHostProperties()
1156 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001157 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001158
Yuexi Ma627263f2021-03-04 13:47:56 -08001159 InitTestHost(
1160 module,
1161 proptools.BoolPtr(true),
1162 nil,
1163 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001164
Liz Kammerdd849a82020-06-12 16:38:45 -07001165 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001166
Colin Cross05638fc2018-04-09 18:40:24 -07001167 return module
1168}
1169
Yuexi Ma627263f2021-03-04 13:47:56 -08001170func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1171 th.properties.Installable = installable
1172 th.testProperties.Auto_gen_config = autoGenConfig
1173 th.testProperties.Test_suites = testSuites
1174}
1175
Colin Cross05638fc2018-04-09 18:40:24 -07001176//
Colin Cross2fe66872015-03-30 17:20:39 -07001177// Java Binaries (.jar file plus wrapper script)
1178//
1179
Colin Crossf506d872017-07-19 15:53:04 -07001180type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001181 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001182 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001183
1184 // Name of the class containing main to be inserted into the manifest as Main-Class.
1185 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001186
1187 // Names of modules containing JNI libraries that should be installed alongside the host
1188 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001189 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001190}
1191
Colin Crossf506d872017-07-19 15:53:04 -07001192type Binary struct {
1193 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001194
Colin Crossf506d872017-07-19 15:53:04 -07001195 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001196
Colin Cross6b4a32d2017-12-05 13:42:45 -08001197 isWrapperVariant bool
1198
Colin Crossc3315992017-12-08 19:12:36 -08001199 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001200 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001201}
1202
Alex Light24237172017-10-26 09:46:21 -07001203func (j *Binary) HostToolPath() android.OptionalPath {
1204 return android.OptionalPathForPath(j.binaryFile)
1205}
1206
Colin Crossf506d872017-07-19 15:53:04 -07001207func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001208 if ctx.Arch().ArchType == android.Common {
1209 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001210 if j.binaryProperties.Main_class != nil {
1211 if j.properties.Manifest != nil {
1212 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1213 }
1214 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1215 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1216 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1217 }
1218
Colin Cross6b4a32d2017-12-05 13:42:45 -08001219 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001220 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001221 // Handle the binary wrapper
1222 j.isWrapperVariant = true
1223
Colin Cross366938f2017-12-11 16:29:02 -08001224 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001225 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001226 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001227 if ctx.Windows() {
1228 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1229 }
1230
Colin Cross6b4a32d2017-12-05 13:42:45 -08001231 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1232 }
1233
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001234 ext := ""
1235 if ctx.Windows() {
1236 ext = ".bat"
1237 }
1238
Colin Crossc179ea62020-10-09 10:54:15 -07001239 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001240 // of the wrapper variant, which will include the common variant's jar file and any JNI
1241 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001242 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001243 ctx.ModuleName()+ext, j.wrapperFile)
1244 }
Colin Cross2fe66872015-03-30 17:20:39 -07001245}
1246
Colin Crossf506d872017-07-19 15:53:04 -07001247func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer356f7d42021-01-26 09:18:53 -05001248 if ctx.Arch().ArchType == android.Common || ctx.BazelConversionMode() {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001249 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001250 }
1251 if ctx.Arch().ArchType != android.Common || ctx.BazelConversionMode() {
Colin Crosse9fe2942020-11-10 18:12:15 -08001252 // These dependencies ensure the host installation rules will install the jar file and
1253 // the jni libraries when the wrapper is installed.
1254 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1255 ctx.AddVariationDependencies(
1256 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1257 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001258 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001259}
1260
Colin Cross1b16b0e2019-02-12 14:41:32 -08001261// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1262// as well.
1263//
1264// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1265// compiled against the device bootclasspath.
1266//
1267// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1268// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001269func BinaryFactory() android.Module {
1270 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001271
Colin Crossce6734e2020-06-15 16:09:53 -07001272 module.addHostAndDeviceProperties()
1273 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001274
Colin Cross9ae1b922018-06-26 17:59:05 -07001275 module.Module.properties.Installable = proptools.BoolPtr(true)
1276
Colin Cross6b4a32d2017-12-05 13:42:45 -08001277 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1278 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001279 android.InitBazelModule(module)
1280
Colin Cross36242852017-06-23 15:06:31 -07001281 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001282}
1283
Colin Cross1b16b0e2019-02-12 14:41:32 -08001284// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1285//
1286// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1287// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001288func BinaryHostFactory() android.Module {
1289 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001290
Colin Crossce6734e2020-06-15 16:09:53 -07001291 module.addHostProperties()
1292 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001293
Colin Cross9ae1b922018-06-26 17:59:05 -07001294 module.Module.properties.Installable = proptools.BoolPtr(true)
1295
Colin Cross6b4a32d2017-12-05 13:42:45 -08001296 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1297 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001298 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001299 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001300}
1301
1302//
1303// Java prebuilts
1304//
1305
Colin Cross74d73e22017-08-02 11:05:49 -07001306type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00001307 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07001308
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001309 // The version of the SDK that the source prebuilt file was built against. Defaults to the
1310 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08001311 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07001312
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001313 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
1314 // specified.
1315 Min_sdk_version *string
1316
Colin Cross535e2cf2017-10-20 17:57:49 -07001317 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09001318
Paul Duffin869de142021-07-15 14:14:41 +01001319 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01001320 Permitted_packages []string
1321
Jiyong Park1be96912018-05-28 18:02:19 +09001322 // List of shared java libs that this module has dependencies to
1323 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07001324
1325 // List of files to remove from the jar file(s)
1326 Exclude_files []string
1327
1328 // List of directories to remove from the jar file(s)
1329 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07001330
1331 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07001332 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09001333
1334 // set the name of the output
1335 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09001336
1337 Aidl struct {
1338 // directories that should be added as include directories for any aidl sources of modules
1339 // that depend on this module, as well as to aidl for this module.
1340 Export_include_dirs []string
1341 }
Colin Cross74d73e22017-08-02 11:05:49 -07001342}
1343
1344type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07001345 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07001346 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001347 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001348 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07001349 prebuilt android.Prebuilt
Jiyong Parkd1063c12019-07-17 20:08:41 +09001350 android.SdkBase
Colin Cross2fe66872015-03-30 17:20:39 -07001351
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001352 // Functionality common to Module and Import.
1353 embeddableInModuleAndImport
1354
Liz Kammerd6c31d22020-08-05 15:40:41 -07001355 hiddenAPI
1356 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001357 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07001358
Colin Cross74d73e22017-08-02 11:05:49 -07001359 properties ImportProperties
1360
Liz Kammerd6c31d22020-08-05 15:40:41 -07001361 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001362 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09001363 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001364
Colin Cross0a6e0072017-08-30 14:24:55 -07001365 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001366 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09001367 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07001368
1369 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09001370
1371 sdkVersion android.SdkSpec
1372 minSdkVersion android.SdkSpec
Colin Cross2fe66872015-03-30 17:20:39 -07001373}
1374
Paul Duffin630b11e2021-07-15 13:35:26 +01001375var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
1376
1377func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
1378 return j.properties.Permitted_packages
1379}
1380
Jiyong Park92315372021-04-02 08:45:46 +09001381func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1382 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07001383}
1384
Jiyong Parkf1691d22021-03-29 20:11:58 +09001385func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001386 return "none"
1387}
1388
Jiyong Park92315372021-04-02 08:45:46 +09001389func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001390 if j.properties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +09001391 return android.SdkSpecFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001392 }
Jiyong Park92315372021-04-02 08:45:46 +09001393 return j.SdkVersion(ctx)
Colin Cross83bb3162018-06-25 15:48:06 -07001394}
1395
Jiyong Park92315372021-04-02 08:45:46 +09001396func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
1397 return j.SdkVersion(ctx)
Artur Satayev480e25b2020-04-27 18:53:18 +01001398}
1399
Colin Cross74d73e22017-08-02 11:05:49 -07001400func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07001401 return &j.prebuilt
1402}
1403
Colin Cross74d73e22017-08-02 11:05:49 -07001404func (j *Import) PrebuiltSrcs() []string {
1405 return j.properties.Jars
1406}
1407
1408func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07001409 return j.prebuilt.Name(j.ModuleBase.Name())
1410}
1411
Jiyong Park0b238752019-10-29 11:23:10 +09001412func (j *Import) Stem() string {
1413 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1414}
1415
Jiyong Park618922e2020-01-08 13:35:43 +09001416func (a *Import) JacocoReportClassesFile() android.Path {
1417 return nil
1418}
1419
Bill Peckhama41a6962021-01-11 10:58:54 -08001420func (j *Import) LintDepSets() LintDepSets {
1421 return LintDepSets{}
1422}
1423
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001424func (j *Import) getStrictUpdatabilityLinting() bool {
1425 return false
1426}
1427
1428func (j *Import) setStrictUpdatabilityLinting(bool) {
1429}
1430
Colin Cross74d73e22017-08-02 11:05:49 -07001431func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07001432 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001433
1434 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001435 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001436 }
Colin Cross1e676be2016-10-12 14:38:15 -07001437}
1438
Colin Cross74d73e22017-08-02 11:05:49 -07001439func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09001440 j.sdkVersion = j.SdkVersion(ctx)
1441 j.minSdkVersion = j.MinSdkVersion(ctx)
1442
Colin Cross56a83212020-09-15 18:30:11 -07001443 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
1444 j.hideApexVariantFromMake = true
1445 }
1446
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001447 if ctx.Windows() {
1448 j.HideFromMake()
1449 }
1450
Colin Cross8a497952019-03-05 22:25:09 -08001451 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07001452
Jiyong Park0b238752019-10-29 11:23:10 +09001453 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07001454 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07001455 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
1456 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07001457 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07001458 inputFile := outputFile
1459 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
1460 TransformJetifier(ctx, outputFile, inputFile)
1461 }
Colin Crosse9a275b2017-10-16 17:09:48 -07001462 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001463 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01001464
Liz Kammerd6c31d22020-08-05 15:40:41 -07001465 var flags javaBuilderFlags
1466
Jiyong Park1be96912018-05-28 18:02:19 +09001467 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09001468 tag := ctx.OtherModuleDependencyTag(module)
1469
Colin Crossdcf71b22021-02-01 13:59:03 -08001470 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1471 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09001472 switch tag {
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001473 case libTag:
1474 flags.classpath = append(flags.classpath, dep.HeaderJars...)
1475 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
1476 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001477 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001478 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08001479 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09001480 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001481 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09001482 switch tag {
1483 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001484 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09001485 }
1486 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001487
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001488 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09001489 })
1490
Nan Zhang4973ecf2018-08-10 13:42:12 -07001491 if Bool(j.properties.Installable) {
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001492 var installDir android.InstallPath
1493 if ctx.InstallInTestcases() {
1494 var archDir string
1495 if !ctx.Host() {
1496 archDir = ctx.DeviceConfig().DeviceArch()
1497 }
1498 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
1499 } else {
1500 installDir = android.PathForModuleInstall(ctx, "framework")
1501 }
1502 ctx.InstallFile(installDir, jarName, outputFile)
Nan Zhang4973ecf2018-08-10 13:42:12 -07001503 }
Jiyong Park19604de2020-03-24 16:44:11 +09001504
1505 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001506
Paul Duffin064b70c2020-11-02 17:32:38 +00001507 if ctx.Device() {
1508 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
1509 // obtained from the associated deapexer module.
1510 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1511 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00001512 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01001513 di := android.FindDeapexerProviderForModule(ctx)
1514 if di == nil {
1515 return // An error has been reported by FindDeapexerProviderForModule.
1516 }
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001517 if dexOutputPath := di.PrebuiltExportPath(apexRootRelativePathToJavaLib(j.BaseModuleName())); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001518 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
1519 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001520 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
1521 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01001522
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001523 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001524 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00001525 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1526 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00001527
1528 // Initialize the hiddenapi structure.
1529 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00001530 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00001531 // This should never happen as a variant for a prebuilt_apex is only created if the
1532 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01001533 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00001534 }
1535 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001536 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00001537 if sdkDep.invalidVersion {
1538 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1539 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1540 } else if sdkDep.useFiles {
1541 // sdkDep.jar is actually equivalent to turbine header.jar.
1542 flags.classpath = append(flags.classpath, sdkDep.jars...)
1543 }
1544
1545 // Dex compilation
1546
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001547 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1548 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00001549 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00001550 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1551
Paul Duffin612e6102021-02-02 13:38:13 +00001552 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001553 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Paul Duffin064b70c2020-11-02 17:32:38 +00001554 if ctx.Failed() {
1555 return
1556 }
1557
Paul Duffin74d18d12021-05-14 14:18:47 +01001558 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001559 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01001560
1561 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01001562 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00001563
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001564 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09001565 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07001566 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07001567 }
Colin Crossdcf71b22021-02-01 13:59:03 -08001568
1569 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1570 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
1571 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
1572 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
1573 AidlIncludeDirs: j.exportAidlIncludeDirs,
1574 })
Colin Cross2fe66872015-03-30 17:20:39 -07001575}
1576
Paul Duffinaa55f742020-10-06 17:20:13 +01001577func (j *Import) OutputFiles(tag string) (android.Paths, error) {
1578 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00001579 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01001580 return android.Paths{j.combinedClasspathFile}, nil
1581 default:
1582 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
1583 }
1584}
1585
1586var _ android.OutputFileProducer = (*Import)(nil)
1587
Nan Zhanged19fc32017-10-19 13:06:22 -07001588func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001589 if j.combinedClasspathFile == nil {
1590 return nil
1591 }
Colin Cross37f6d792018-07-12 12:28:41 -07001592 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07001593}
1594
Colin Cross331a1212018-08-15 20:40:52 -07001595func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08001596 if j.combinedClasspathFile == nil {
1597 return nil
1598 }
Colin Cross331a1212018-08-15 20:40:52 -07001599 return android.Paths{j.combinedClasspathFile}
1600}
1601
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001602func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07001603 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08001604}
1605
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001606func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09001607 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01001608}
1609
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01001610func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1611 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09001612}
1613
Jiyong Park45bf82e2020-12-15 22:29:02 +09001614var _ android.ApexModule = (*Import)(nil)
1615
1616// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09001617func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01001618 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09001619}
1620
Jiyong Park45bf82e2020-12-15 22:29:02 +09001621// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001622func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1623 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001624 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001625 if !sdkSpec.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001626 return fmt.Errorf("min_sdk_version is not specified")
1627 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001628 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001629 return nil
1630 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001631 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1632 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00001633 }
Jooyung Han749dc692020-04-15 11:03:39 +09001634 return nil
1635}
1636
Paul Duffinfef55002021-06-17 14:56:05 +01001637// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
1638// java_sdk_library_import with the specified base module name requires to be exported from a
1639// prebuilt_apex/apex_set.
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001640func requiredFilesFromPrebuiltApexForImport(name string) []string {
1641 // Add the dex implementation jar to the set of exported files.
1642 return []string{
1643 apexRootRelativePathToJavaLib(name),
Paul Duffinfef55002021-06-17 14:56:05 +01001644 }
1645}
1646
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001647// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
1648// the java library with the specified name.
1649func apexRootRelativePathToJavaLib(name string) string {
1650 return filepath.Join("javalib", name+".jar")
1651}
1652
Paul Duffinfef55002021-06-17 14:56:05 +01001653var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
1654
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01001655func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01001656 name := j.BaseModuleName()
1657 return requiredFilesFromPrebuiltApexForImport(name)
1658}
1659
albaltai36ff7dc2018-12-25 14:35:23 +08001660// Add compile time check for interface implementation
1661var _ android.IDEInfo = (*Import)(nil)
1662var _ android.IDECustomizedModuleName = (*Import)(nil)
1663
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001664// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001665
1666func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
1667 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
1668}
1669
1670func (j *Import) IDECustomizedModuleName() string {
1671 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
1672 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
1673 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01001674 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07001675}
1676
Colin Cross74d73e22017-08-02 11:05:49 -07001677var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07001678
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001679func (j *Import) IsInstallable() bool {
1680 return Bool(j.properties.Installable)
1681}
1682
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001683var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08001684
Colin Cross1b16b0e2019-02-12 14:41:32 -08001685// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
1686//
1687// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
1688// compiled against an Android classpath.
1689//
1690// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1691// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07001692func ImportFactory() android.Module {
1693 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07001694
Liz Kammerd6c31d22020-08-05 15:40:41 -07001695 module.AddProperties(
1696 &module.properties,
1697 &module.dexer.dexProperties,
1698 )
Colin Cross74d73e22017-08-02 11:05:49 -07001699
Paul Duffin71b33cc2021-06-23 11:39:47 +01001700 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001701
Liz Kammerd6c31d22020-08-05 15:40:41 -07001702 module.dexProperties.Optimize.EnabledByDefault = false
1703
Colin Cross74d73e22017-08-02 11:05:49 -07001704 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001705 android.InitApexModule(module)
Jiyong Parkd1063c12019-07-17 20:08:41 +09001706 android.InitSdkAwareModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05001707 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001708 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07001709 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001710}
1711
Colin Cross1b16b0e2019-02-12 14:41:32 -08001712// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
1713// module.
1714//
1715// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
1716// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07001717func ImportFactoryHost() android.Module {
1718 module := &Import{}
1719
1720 module.AddProperties(&module.properties)
1721
1722 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001723 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00001724 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001725 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07001726 return module
1727}
1728
Colin Cross42be7612019-02-21 18:12:14 -08001729// dex_import module
1730
1731type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07001732 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09001733
1734 // set the name of the output
1735 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08001736}
1737
1738type DexImport struct {
1739 android.ModuleBase
1740 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001741 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08001742 prebuilt android.Prebuilt
1743
1744 properties DexImportProperties
1745
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001746 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08001747
1748 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07001749
1750 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08001751}
1752
1753func (j *DexImport) Prebuilt() *android.Prebuilt {
1754 return &j.prebuilt
1755}
1756
1757func (j *DexImport) PrebuiltSrcs() []string {
1758 return j.properties.Jars
1759}
1760
1761func (j *DexImport) Name() string {
1762 return j.prebuilt.Name(j.ModuleBase.Name())
1763}
1764
Jiyong Park0b238752019-10-29 11:23:10 +09001765func (j *DexImport) Stem() string {
1766 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
1767}
1768
Jiyong Park77acec62020-06-01 21:39:15 +09001769func (a *DexImport) JacocoReportClassesFile() android.Path {
1770 return nil
1771}
1772
Colin Cross08dca382020-07-21 20:31:17 -07001773func (a *DexImport) LintDepSets() LintDepSets {
1774 return LintDepSets{}
1775}
1776
Martin Stjernholm6d415272020-01-31 17:10:36 +00001777func (j *DexImport) IsInstallable() bool {
1778 return true
1779}
1780
Jaewoong Jung476b9d62021-05-10 15:30:00 -07001781func (j *DexImport) getStrictUpdatabilityLinting() bool {
1782 return false
1783}
1784
1785func (j *DexImport) setStrictUpdatabilityLinting(bool) {
1786}
1787
Colin Cross42be7612019-02-21 18:12:14 -08001788func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1789 if len(j.properties.Jars) != 1 {
1790 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
1791 }
1792
Colin Cross56a83212020-09-15 18:30:11 -07001793 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1794 if !apexInfo.IsForPlatform() {
1795 j.hideApexVariantFromMake = true
1796 }
1797
Jiakai Zhang519c5c82021-09-16 06:15:39 +00001798 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
1799 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08001800 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
1801
1802 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
1803 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
1804
1805 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08001806 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08001807
1808 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
1809 rule.Temporary(temporary)
1810
1811 // use zip2zip to uncompress classes*.dex files
1812 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08001813 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08001814 FlagWithInput("-i ", inputJar).
1815 FlagWithOutput("-o ", temporary).
1816 FlagWithArg("-0 ", "'classes*.dex'")
1817
1818 // use zipalign to align uncompressed classes*.dex files
1819 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08001820 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08001821 Flag("-f").
1822 Text("4").
1823 Input(temporary).
1824 Output(dexOutputFile)
1825
1826 rule.DeleteTemporaryFiles()
1827
Colin Crossf1a035e2020-11-16 17:32:30 -08001828 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08001829 } else {
1830 ctx.Build(pctx, android.BuildParams{
1831 Rule: android.Cp,
1832 Input: inputJar,
1833 Output: dexOutputFile,
1834 })
1835 }
1836
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001837 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08001838
Jaewoong Jung4b97a562020-12-17 09:43:28 -08001839 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08001840
Colin Cross56a83212020-09-15 18:30:11 -07001841 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09001842 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
1843 j.Stem()+".jar", dexOutputFile)
1844 }
Colin Cross42be7612019-02-21 18:12:14 -08001845}
1846
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001847func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08001848 return j.dexJarFile
1849}
1850
Jiyong Park45bf82e2020-12-15 22:29:02 +09001851var _ android.ApexModule = (*DexImport)(nil)
1852
1853// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07001854func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1855 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09001856 // we don't check prebuilt modules for sdk_version
1857 return nil
1858}
1859
Colin Cross42be7612019-02-21 18:12:14 -08001860// dex_import imports a `.jar` file containing classes.dex files.
1861//
1862// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
1863// to the device.
1864func DexImportFactory() android.Module {
1865 module := &DexImport{}
1866
1867 module.AddProperties(&module.properties)
1868
1869 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09001870 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001871 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08001872 return module
1873}
1874
Colin Cross89536d42017-07-07 14:35:50 -07001875//
1876// Defaults
1877//
1878type Defaults struct {
1879 android.ModuleBase
1880 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09001881 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07001882}
1883
Colin Cross1b16b0e2019-02-12 14:41:32 -08001884// java_defaults provides a set of properties that can be inherited by other java or android modules.
1885//
1886// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
1887// property in the defaults module that exists in the depending module will be prepended to the depending module's
1888// value for that property.
1889//
1890// Example:
1891//
1892// java_defaults {
1893// name: "example_defaults",
1894// srcs: ["common/**/*.java"],
1895// javacflags: ["-Xlint:all"],
1896// aaptflags: ["--auto-add-overlay"],
1897// }
1898//
1899// java_library {
1900// name: "example",
1901// defaults: ["example_defaults"],
1902// srcs: ["example/**/*.java"],
1903// }
1904//
1905// is functionally identical to:
1906//
1907// java_library {
1908// name: "example",
1909// srcs: [
1910// "common/**/*.java",
1911// "example/**/*.java",
1912// ],
1913// javacflags: ["-Xlint:all"],
1914// }
Paul Duffin47357662019-12-05 14:07:14 +00001915func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07001916 module := &Defaults{}
1917
Colin Cross89536d42017-07-07 14:35:50 -07001918 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08001919 &CommonProperties{},
1920 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09001921 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07001922 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08001923 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08001924 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07001925 &aaptProperties{},
1926 &androidLibraryProperties{},
1927 &appProperties{},
1928 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08001929 &overridableAppProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00001930 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07001931 &ImportProperties{},
1932 &AARImportProperties{},
1933 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01001934 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08001935 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09001936 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07001937 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07001938 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08001939 &appTestHelperAppProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07001940 )
1941
1942 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07001943 return module
1944}
Nan Zhangea568a42017-11-08 21:20:04 -08001945
Sasha Smundak2a4549e2018-11-05 16:49:08 -08001946func kytheExtractJavaFactory() android.Singleton {
1947 return &kytheExtractJavaSingleton{}
1948}
1949
1950type kytheExtractJavaSingleton struct {
1951}
1952
1953func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
1954 var xrefTargets android.Paths
1955 ctx.VisitAllModules(func(module android.Module) {
1956 if javaModule, ok := module.(xref); ok {
1957 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
1958 }
1959 })
1960 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
1961 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07001962 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08001963 }
1964}
1965
Nan Zhangea568a42017-11-08 21:20:04 -08001966var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07001967var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08001968var String = proptools.String
Colin Cross0d0ba592018-02-20 13:33:42 -08001969var inList = android.InList
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001970
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001971// Add class loader context (CLC) of a given dependency to the current CLC.
1972func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
1973 clcMap dexpreopt.ClassLoaderContextMap) {
1974
1975 dep, ok := depModule.(UsesLibraryDependency)
1976 if !ok {
1977 return
1978 }
1979
Ulya Trafimovich840efb62021-07-15 14:34:40 +01001980 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
1981
1982 var sdkLib *string
1983 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
1984 // A shared SDK library. This should be added as a top-level CLC element.
1985 sdkLib = &depName
1986 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
1987 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
1988 // property. This should be handled in the same way as a shared SDK library.
1989 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00001990 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001991
1992 depTag := ctx.OtherModuleDependencyTag(depModule)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +01001993 if depTag == libTag {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001994 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01001995 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
1996 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00001997 } else if depTag == staticLibTag {
1998 // Propagate <uses-library> through static library dependencies, unless it is a component
1999 // library (such as stubs). Component libraries have a dependency on their SDK library,
2000 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002001 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002002 return
2003 }
2004 } else {
2005 // Don't propagate <uses-library> for other dependency tags.
2006 return
2007 }
2008
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002009 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2010 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2011 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2012 // from its CLC should be added to the current CLC.
2013 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002014 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002015 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002016 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002017 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2018 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002019}
Wei Libafb6d62021-12-10 03:14:59 -08002020
Sam Delmericoc0161432022-02-25 21:34:51 +00002021type javaCommonAttributes struct {
Wei Libafb6d62021-12-10 03:14:59 -08002022 Srcs bazel.LabelListAttribute
Sam Delmerico77267c72022-03-18 14:11:07 +00002023 Plugins bazel.LabelListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002024 Javacopts bazel.StringListAttribute
2025}
2026
Sam Delmericoc0161432022-02-25 21:34:51 +00002027type javaDependencyLabels struct {
2028 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2029 Deps bazel.LabelListAttribute
2030 // Dependencies which DO contribute to the API visible to upstream dependencies.
2031 StaticDeps bazel.LabelListAttribute
2032}
2033
2034// convertLibraryAttrsBp2Build converts a few shared attributes from java_* modules
2035// and also separates dependencies into dynamic dependencies and static dependencies.
2036// Each corresponding Bazel target type, can have a different method for handling
2037// dynamic vs. static dependencies, and so these are returned to the calling function.
Sam Delmerico24da73c2022-03-16 20:36:54 +00002038type eventLogTagsAttributes struct {
2039 Srcs bazel.LabelListAttribute
2040}
2041
Sam Delmericoc0161432022-02-25 21:34:51 +00002042func (m *Library) convertLibraryAttrsBp2Build(ctx android.TopDownMutatorContext) (*javaCommonAttributes, *javaDependencyLabels) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002043 var srcs bazel.LabelListAttribute
2044 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2045 for axis, configToProps := range archVariantProps {
2046 for config, _props := range configToProps {
2047 if archProps, ok := _props.(*CommonProperties); ok {
2048 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
2049 srcs.SetSelectValue(axis, config, archSrcs)
2050 }
2051 }
2052 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002053
2054 javaSrcPartition := "java"
2055 protoSrcPartition := "proto"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002056 logtagSrcPartition := "logtag"
Sam Delmericoc7681022022-02-04 21:01:20 +00002057 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002058 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
2059 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
2060 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmericoc7681022022-02-04 21:01:20 +00002061 })
2062
Sam Delmerico24da73c2022-03-16 20:36:54 +00002063 javaSrcs := srcPartitions[javaSrcPartition]
2064
2065 var logtagsSrcs bazel.LabelList
2066 if !srcPartitions[logtagSrcPartition].IsEmpty() {
2067 logtagsLibName := m.Name() + "_logtags"
2068 logtagsSrcs = bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
2069 ctx.CreateBazelTargetModule(
2070 bazel.BazelTargetModuleProperties{
2071 Rule_class: "event_log_tags",
2072 Bzl_load_location: "//build/make/tools:event_log_tags.bzl",
2073 },
2074 android.CommonAttributes{Name: logtagsLibName},
2075 &eventLogTagsAttributes{
2076 Srcs: srcPartitions[logtagSrcPartition],
2077 },
2078 )
2079 }
2080 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
2081
Sam Delmerico58614c02022-03-15 21:02:09 +00002082 var javacopts []string
2083 if m.properties.Javacflags != nil {
2084 javacopts = append(javacopts, m.properties.Javacflags...)
2085 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04002086 if m.properties.Java_version != nil {
2087 javaVersion := normalizeJavaVersion(ctx, *m.properties.Java_version).String()
2088 javacopts = append(javacopts, fmt.Sprintf("-source %s -target %s", javaVersion, javaVersion))
2089 }
2090
Sam Delmerico58614c02022-03-15 21:02:09 +00002091 epEnabled := m.properties.Errorprone.Enabled
2092 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
2093 if Bool(epEnabled) {
2094 javacopts = append(javacopts, m.properties.Errorprone.Javacflags...)
2095 }
2096
Sam Delmericoc0161432022-02-25 21:34:51 +00002097 commonAttrs := &javaCommonAttributes{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002098 Srcs: javaSrcs,
Sam Delmerico77267c72022-03-18 14:11:07 +00002099 Plugins: bazel.MakeLabelListAttribute(
2100 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
2101 ),
Sam Delmerico58614c02022-03-15 21:02:09 +00002102 Javacopts: bazel.MakeStringListAttribute(javacopts),
Wei Libafb6d62021-12-10 03:14:59 -08002103 }
2104
Sam Delmericoc0161432022-02-25 21:34:51 +00002105 depLabels := &javaDependencyLabels{}
2106
Sam Delmericofde9fb52022-01-28 20:53:38 +00002107 var deps bazel.LabelList
Wei Libafb6d62021-12-10 03:14:59 -08002108 if m.properties.Libs != nil {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002109 deps.Append(android.BazelLabelForModuleDeps(ctx, m.properties.Libs))
Wei Libafb6d62021-12-10 03:14:59 -08002110 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002111
2112 var staticDeps bazel.LabelList
Sam Delmericofde9fb52022-01-28 20:53:38 +00002113 if m.properties.Static_libs != nil {
Sam Delmericoc0161432022-02-25 21:34:51 +00002114 staticDeps.Append(android.BazelLabelForModuleDeps(ctx, m.properties.Static_libs))
Sam Delmericofde9fb52022-01-28 20:53:38 +00002115 }
Sam Delmericoc7681022022-02-04 21:01:20 +00002116
Sam Delmericoc0161432022-02-25 21:34:51 +00002117 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition])
2118 // Soong does not differentiate between a java_library and the Bazel equivalent of
2119 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
2120 // listed directly in the srcs of a java_library, and the classes produced
2121 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
2122 // that depend on a java_library with proto sources can link directly to the protobuf API,
2123 // and so this should be a static dependency.
2124 staticDeps.Add(protoDepLabel)
Sam Delmericoc7681022022-02-04 21:01:20 +00002125
Sam Delmericoc0161432022-02-25 21:34:51 +00002126 depLabels.Deps = bazel.MakeLabelListAttribute(deps)
2127 depLabels.StaticDeps = bazel.MakeLabelListAttribute(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00002128
Sam Delmericoc0161432022-02-25 21:34:51 +00002129 return commonAttrs, depLabels
2130}
2131
2132type javaLibraryAttributes struct {
2133 *javaCommonAttributes
2134 Deps bazel.LabelListAttribute
2135 Exports bazel.LabelListAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00002136}
2137
2138func javaLibraryBp2Build(ctx android.TopDownMutatorContext, m *Library) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002139 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2140
2141 deps := depLabels.Deps
2142 if !commonAttrs.Srcs.IsEmpty() {
2143 deps.Append(depLabels.StaticDeps) // we should only append these if there are sources to use them
2144
2145 sdkVersion := m.SdkVersion(ctx)
2146 if sdkVersion.Kind == android.SdkPublic && sdkVersion.ApiLevel == android.FutureApiLevel {
2147 // TODO(b/220869005) remove forced dependency on current public android.jar
2148 deps.Add(bazel.MakeLabelAttribute("//prebuilts/sdk:public_current_android_sdk_java_import"))
2149 }
2150 } else if !depLabels.Deps.IsEmpty() {
2151 ctx.ModuleErrorf("Module has direct dependencies but no sources. Bazel will not allow this.")
2152 }
2153
2154 attrs := &javaLibraryAttributes{
2155 javaCommonAttributes: commonAttrs,
2156 Deps: deps,
2157 Exports: depLabels.StaticDeps,
2158 }
Wei Libafb6d62021-12-10 03:14:59 -08002159
2160 props := bazel.BazelTargetModuleProperties{
2161 Rule_class: "java_library",
2162 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
2163 }
2164
2165 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2166}
2167
2168type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00002169 *javaCommonAttributes
2170 Deps bazel.LabelListAttribute
2171 Runtime_deps bazel.LabelListAttribute
2172 Main_class string
2173 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08002174}
2175
2176// JavaBinaryHostBp2Build is for java_binary_host bp2build.
2177func javaBinaryHostBp2Build(ctx android.TopDownMutatorContext, m *Binary) {
Sam Delmericoc0161432022-02-25 21:34:51 +00002178 commonAttrs, depLabels := m.convertLibraryAttrsBp2Build(ctx)
2179
2180 deps := depLabels.Deps
2181 deps.Append(depLabels.StaticDeps)
2182 if m.binaryProperties.Jni_libs != nil {
2183 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
2184 }
2185
2186 var runtimeDeps bazel.LabelListAttribute
2187 if commonAttrs.Srcs.IsEmpty() {
2188 // if there are no sources, then the dependencies can only be used at runtime
2189 runtimeDeps = deps
2190 deps = bazel.LabelListAttribute{}
2191 }
2192
Wei Libafb6d62021-12-10 03:14:59 -08002193 mainClass := ""
2194 if m.binaryProperties.Main_class != nil {
2195 mainClass = *m.binaryProperties.Main_class
2196 }
2197 if m.properties.Manifest != nil {
2198 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
2199 if err != nil {
2200 return
2201 }
2202 mainClass = mainClassInManifest
2203 }
Sam Delmericoc0161432022-02-25 21:34:51 +00002204
Wei Libafb6d62021-12-10 03:14:59 -08002205 attrs := &javaBinaryHostAttributes{
Sam Delmericoc0161432022-02-25 21:34:51 +00002206 javaCommonAttributes: commonAttrs,
2207 Deps: deps,
2208 Runtime_deps: runtimeDeps,
2209 Main_class: mainClass,
Wei Libafb6d62021-12-10 03:14:59 -08002210 }
2211
2212 // Attribute jvm_flags
2213 if m.binaryProperties.Jni_libs != nil {
2214 jniLibPackages := map[string]bool{}
2215 for _, jniLibLabel := range android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs).Includes {
2216 jniLibPackage := jniLibLabel.Label
2217 indexOfColon := strings.Index(jniLibLabel.Label, ":")
2218 if indexOfColon > 0 {
2219 // JNI lib from other package
2220 jniLibPackage = jniLibLabel.Label[2:indexOfColon]
2221 } else if indexOfColon == 0 {
2222 // JNI lib in the same package of java_binary
2223 packageOfCurrentModule := m.GetBazelLabel(ctx, m)
2224 jniLibPackage = packageOfCurrentModule[2:strings.Index(packageOfCurrentModule, ":")]
2225 }
2226 if _, inMap := jniLibPackages[jniLibPackage]; !inMap {
2227 jniLibPackages[jniLibPackage] = true
2228 }
2229 }
2230 jniLibPaths := []string{}
2231 for jniLibPackage, _ := range jniLibPackages {
2232 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
2233 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
2234 }
2235 attrs.Jvm_flags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
2236 }
2237
2238 props := bazel.BazelTargetModuleProperties{
2239 Rule_class: "java_binary",
2240 }
2241
2242 // Create the BazelTargetModule.
2243 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
2244}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002245
2246type bazelJavaImportAttributes struct {
2247 Jars bazel.LabelListAttribute
2248}
2249
2250// java_import bp2Build converter.
2251func (i *Import) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00002252 var jars bazel.LabelListAttribute
2253 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
2254 for axis, configToProps := range archVariantProps {
2255 for config, _props := range configToProps {
2256 if archProps, ok := _props.(*ImportProperties); ok {
2257 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
2258 jars.SetSelectValue(axis, config, archJars)
2259 }
2260 }
2261 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002262
2263 attrs := &bazelJavaImportAttributes{
2264 Jars: jars,
2265 }
2266 props := bazel.BazelTargetModuleProperties{Rule_class: "java_import"}
2267
2268 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: android.RemoveOptionalPrebuiltPrefix(i.Name())}, attrs)
2269
2270}