blob: 4962698de1da792349de80c7f90ca7a47b1fa0af [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"
Alix289e9c62023-08-16 15:06:31 +000024 "sort"
Wei Libafb6d62021-12-10 03:14:59 -080025 "strings"
Colin Cross2fe66872015-03-30 17:20:39 -070026
Wei Libafb6d62021-12-10 03:14:59 -080027 "android/soong/bazel"
Sam Delmerico277795c2022-02-25 17:04:37 +000028 "android/soong/bazel/cquery"
Jihoon Kang0ac87c22022-11-15 19:06:14 +000029 "android/soong/remoteexec"
Aditya Choudhary9b593522023-10-06 19:54:58 +000030 "android/soong/testing"
Liz Kammer7f375862023-08-04 16:37:42 -040031 "android/soong/ui/metrics/bp2build_metrics_proto"
Sam Delmerico4e272292022-01-06 20:03:51 +000032
Colin Cross2fe66872015-03-30 17:20:39 -070033 "github.com/google/blueprint"
Colin Cross76b5f0c2017-08-29 16:02:06 -070034 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070035
Colin Cross635c3b02016-05-18 15:37:25 -070036 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080037 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010038 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070039 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070040 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070041)
42
Colin Cross463a90e2015-06-17 14:20:06 -070043func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010044 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000045
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080046 RegisterJavaSdkMemberTypes()
47}
48
Paul Duffin535e0a12021-03-30 23:34:32 +010049func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080050 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
51
52 ctx.RegisterModuleType("java_library", LibraryFactory)
53 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
54 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
55 ctx.RegisterModuleType("java_binary", BinaryFactory)
56 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
57 ctx.RegisterModuleType("java_test", TestFactory)
58 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
59 ctx.RegisterModuleType("java_test_host", TestHostFactory)
60 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
61 ctx.RegisterModuleType("java_import", ImportFactory)
62 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
63 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
64 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
65 ctx.RegisterModuleType("dex_import", DexImportFactory)
Jihoon Kang0ac87c22022-11-15 19:06:14 +000066 ctx.RegisterModuleType("java_api_library", ApiLibraryFactory)
67 ctx.RegisterModuleType("java_api_contribution", ApiContributionFactory)
Jihoon Kangfdf32362023-09-12 00:36:43 +000068 ctx.RegisterModuleType("java_api_contribution_import", ApiContributionImportFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080069
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010070 // This mutator registers dependencies on dex2oat for modules that should be
71 // dexpreopted. This is done late when the final variants have been
72 // established, to not get the dependencies split into the wrong variants and
73 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080074 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
75 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040076 // needs access to ApexInfoProvider which is available after variant creation
77 ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080078 })
79
LaMont Jones0c10e4d2023-05-16 00:58:37 +000080 ctx.RegisterParallelSingletonType("logtags", LogtagsSingleton)
81 ctx.RegisterParallelSingletonType("kythe_java_extract", kytheExtractJavaFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080082}
83
84func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000085 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000086 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010087 android.RegisterSdkMemberType(javaLibsSdkMemberType)
88 android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
Jiakai Zhangea180332021-09-26 08:58:02 +000089 android.RegisterSdkMemberType(javaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010090 android.RegisterSdkMemberType(javaTestSdkMemberType)
91}
92
93var (
94 // Supports adding java header libraries to module_exports and sdk.
95 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +000096 android.SdkMemberTypeBase{
Paul Duffin2da04242021-04-23 19:43:28 +010097 PropertyName: "java_header_libs",
98 SupportsSdk: true,
99 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000100 func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin2da04242021-04-23 19:43:28 +0100101 headerJars := j.HeaderJars()
102 if len(headerJars) != 1 {
103 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
104 }
105
106 return headerJars[0]
107 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000108 sdkSnapshotFilePathForJar,
109 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100110 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000111
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000112 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100113 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000114 implementationJars := j.ImplementationAndResourcesJars()
115 if len(implementationJars) != 1 {
116 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
117 }
118 return implementationJars[0]
119 }
120
Paul Duffin2da04242021-04-23 19:43:28 +0100121 // Supports adding java implementation libraries to module_exports but not sdk.
122 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000123 android.SdkMemberTypeBase{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000124 PropertyName: "java_libs",
125 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000126 exportImplementationClassesJar,
127 sdkSnapshotFilePathForJar,
128 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100129 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000130
Paul Duffin13648912022-07-15 13:12:35 +0000131 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
132 // In the S build the build will break if updatable-media does not provide a full implementation
133 // jar. That issue was fixed in Tiramisu by b/229932396.
134 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
135 return true
136 }
137
138 return false
139 }
140
Paul Duffin2da04242021-04-23 19:43:28 +0100141 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000142 //
143 // The build has some implicit dependencies (via the boot jars configuration) on a number of
144 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
145 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
146 // used outside those mainline modules.
147 //
148 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
149 // either java_libs, or java_header_libs would end up exporting more information than was strictly
150 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
151 // sdk/module_exports without exposing any unnecessary information.
Paul Duffin2da04242021-04-23 19:43:28 +0100152 javaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000153 android.SdkMemberTypeBase{
Paul Duffindb170e42020-12-08 17:48:25 +0000154 PropertyName: "java_boot_libs",
155 SupportsSdk: true,
156 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000157 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000158 if snapshotRequiresImplementationJar(ctx) {
159 return exportImplementationClassesJar(ctx, j)
160 }
161
Paul Duffin5c211452021-07-15 12:42:44 +0100162 // Java boot libs are only provided in the SDK to provide access to their dex implementation
163 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
164 // actual implementation jar but the java_import will need a file that exists so just copy an
165 // empty file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000166 return ctx.SnapshotBuilder().EmptyFile()
Paul Duffin5c211452021-07-15 12:42:44 +0100167 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000168 func(ctx android.SdkMemberContext, osPrefix, name string) string {
Paul Duffin13648912022-07-15 13:12:35 +0000169 if snapshotRequiresImplementationJar(ctx) {
170 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
171 }
172
Paul Duffin5c211452021-07-15 12:42:44 +0100173 // Create a special name for the implementation jar to try and provide some useful information
174 // to a developer that attempts to compile against this.
175 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
176 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
177 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000178 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100179 }
Paul Duffindb170e42020-12-08 17:48:25 +0000180
Jiakai Zhangea180332021-09-26 08:58:02 +0000181 // Supports adding java systemserver libraries to module_exports and sdk.
182 //
183 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
184 // of modules that are part of the java systemserver classpath and which are provided by mainline
185 // modules but which are not otherwise used outside those mainline modules.
186 //
187 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
188 // either java_libs, or java_header_libs would end up exporting more information than was strictly
189 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
190 // the sdk/module_exports without exposing any unnecessary information.
191 javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000192 android.SdkMemberTypeBase{
Jiakai Zhangea180332021-09-26 08:58:02 +0000193 PropertyName: "java_systemserver_libs",
194 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000195
196 // This was only added in Tiramisu.
197 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000198 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000199 func(ctx android.SdkMemberContext, j *Library) android.Path {
Jiakai Zhangea180332021-09-26 08:58:02 +0000200 // Java systemserver libs are only provided in the SDK to provide access to their dex
201 // implementation jar for use by dexpreopting. They do not need to provide an actual
202 // implementation jar but the java_import will need a file that exists so just copy an empty
203 // file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000204 return ctx.SnapshotBuilder().EmptyFile()
Jiakai Zhangea180332021-09-26 08:58:02 +0000205 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000206 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000207 // Create a special name for the implementation jar to try and provide some useful information
208 // to a developer that attempts to compile against this.
209 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
210 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
211 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000212 onlyCopyJarToSnapshot,
Jiakai Zhangea180332021-09-26 08:58:02 +0000213 }
214
Paul Duffin2da04242021-04-23 19:43:28 +0100215 // Supports adding java test libraries to module_exports but not sdk.
216 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000217 SdkMemberTypeBase: android.SdkMemberTypeBase{
218 PropertyName: "java_tests",
219 },
Paul Duffin2da04242021-04-23 19:43:28 +0100220 }
Zi Wangca65b402022-10-10 13:45:06 -0700221
222 // Rule for generating device binary default wrapper
223 deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
224 Command: `echo -e '#!/system/bin/sh\n` +
225 `export CLASSPATH=/system/framework/$jar_name\n` +
226 `exec app_process /$partition/bin $main_class "$$@"'> ${out}`,
227 Description: "Generating device binary wrapper ${jar_name}",
228 }, "jar_name", "partition", "main_class")
Paul Duffin2da04242021-04-23 19:43:28 +0100229)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900230
Sam Delmerico95d70942023-08-02 18:00:35 -0400231type ProguardSpecInfo struct {
232 // If true, proguard flags files will be exported to reverse dependencies across libs edges
233 // If false, proguard flags files will only be exported to reverse dependencies across
234 // static_libs edges.
235 Export_proguard_flags_files bool
236
237 // TransitiveDepsProguardSpecFiles is a depset of paths to proguard flags files that are exported from
238 // all transitive deps. This list includes all proguard flags files from transitive static dependencies,
239 // and all proguard flags files from transitive libs dependencies which set `export_proguard_spec: true`.
240 ProguardFlagsFiles *android.DepSet[android.Path]
241
242 // implementation detail to store transitive proguard flags files from exporting shared deps
243 UnconditionallyExportedProguardFlags *android.DepSet[android.Path]
244}
245
246var ProguardSpecInfoProvider = blueprint.NewProvider(ProguardSpecInfo{})
247
Colin Crossdcf71b22021-02-01 13:59:03 -0800248// JavaInfo contains information about a java module for use by modules that depend on it.
249type JavaInfo struct {
250 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
251 // against this module. If empty, ImplementationJars should be used instead.
252 HeaderJars android.Paths
253
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500254 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700255 TransitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500256
257 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700258 TransitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500259
Colin Crossdcf71b22021-02-01 13:59:03 -0800260 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
261 // in the module as well as any resources included in the module.
262 ImplementationAndResourcesJars android.Paths
263
264 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000265 //module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800266 ImplementationJars android.Paths
267
268 // ResourceJars is a list of jars that contain the resources included in the module.
269 ResourceJars android.Paths
270
271 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
272 // depending on this module.
273 AidlIncludeDirs android.Paths
274
275 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
276 // module.
277 SrcJarArgs []string
278
279 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
280 SrcJarDeps android.Paths
281
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000282 // The source files of this module and all its transitive static dependencies.
283 TransitiveSrcFiles *android.DepSet[android.Path]
284
Colin Crossdcf71b22021-02-01 13:59:03 -0800285 // ExportedPlugins is a list of paths that should be used as annotation processors for any
286 // module that depends on this module.
287 ExportedPlugins android.Paths
288
289 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
290 // any module that depends on this module.
291 ExportedPluginClasses []string
292
293 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
294 // requiring disbling turbine for any modules that depend on it.
295 ExportedPluginDisableTurbine bool
296
297 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
298 // instrumented by jacoco.
299 JacocoReportClassesFile android.Path
300}
301
302var JavaInfoProvider = blueprint.NewProvider(JavaInfo{})
303
Colin Cross75ce9ec2021-02-26 16:20:32 -0800304// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
305// the sysprop implementation library.
306type SyspropPublicStubInfo struct {
307 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
308 // the sysprop implementation library.
309 JavaInfo JavaInfo
310}
311
312var SyspropPublicStubInfoProvider = blueprint.NewProvider(SyspropPublicStubInfo{})
313
Paul Duffin44b481b2020-06-17 16:59:43 +0100314// Methods that need to be implemented for a module that is added to apex java_libs property.
315type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700316 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100317 ImplementationAndResourcesJars() android.Paths
318}
319
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100320// Provides build path and install path to DEX jars.
321type UsesLibraryDependency interface {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100322 DexJarBuildPath() OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100323 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000324 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100325}
326
Jaewoong Jung26342642021-03-17 15:56:23 -0700327// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800328type xref interface {
329 XrefJavaFiles() android.Paths
330}
331
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800332func (j *Module) XrefJavaFiles() android.Paths {
333 return j.kytheFiles
334}
335
Colin Crossbe1da472017-07-07 15:59:46 -0700336type dependencyTag struct {
337 blueprint.BaseDependencyTag
338 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000339
340 // True if the dependency is relinked at runtime.
341 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800342
343 // True if the dependency is a toolchain, for example an annotation processor.
344 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700345}
346
Colin Crosse9fe2942020-11-10 18:12:15 -0800347// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
348// dependency to be installed when the parent module is installed.
349type installDependencyTag struct {
350 blueprint.BaseDependencyTag
351 android.InstallAlwaysNeededDependencyTag
352 name string
353}
354
Colin Cross65cb3142021-12-10 23:05:02 +0000355func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
356 if d.runtimeLinked {
357 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800358 } else if d.toolchain {
359 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000360 }
361 return nil
362}
363
364var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
365
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100366type usesLibraryDependencyTag struct {
367 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100368 sdkVersion int // SDK version in which the library appared as a standalone library.
369 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100370}
371
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100372func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100373 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000374 dependencyTag: dependencyTag{
375 name: fmt.Sprintf("uses-library-%d", sdkVersion),
376 runtimeLinked: true,
377 },
378 sdkVersion: sdkVersion,
379 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100380 }
381}
382
Jiyong Park8be103b2019-11-08 15:53:48 +0900383func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700384 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900385}
386
Colin Crossbe1da472017-07-07 15:59:46 -0700387var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800388 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000389 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800390 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000391 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400392 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000393 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800394 pluginTag = dependencyTag{name: "plugin", toolchain: true}
395 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
396 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000397 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
398 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800399 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000400 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
401 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800402 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800403 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
404 certificateTag = dependencyTag{name: "certificate"}
405 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800406 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000407 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500408 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800409 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000410 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
411 depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800412 jniInstallTag = installDependencyTag{name: "jni install"}
413 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100414 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
415 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
416 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
417 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
418 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700419)
Colin Cross2fe66872015-03-30 17:20:39 -0700420
Jiyong Park83dc74b2020-01-14 18:38:44 +0900421func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400422 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900423}
424
425func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
426 return depTag == staticLibTag
427}
428
Colin Crossfc3674a2017-09-18 17:41:52 -0700429type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100430 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700431
Colin Cross6cef4812019-10-17 14:23:50 -0700432 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
433 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100434
435 // The default system modules to use. Will be an empty string if no system
436 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700437 systemModules string
438
Pete Gilline3d44b22020-06-29 11:28:51 +0100439 // The modules that will be added to the classpath regardless of the Java language level targeted
440 classpath []string
441
Colin Cross6cef4812019-10-17 14:23:50 -0700442 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100443 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700444 java9Classpath []string
445
Colin Crossa97c5d32018-03-28 14:58:31 -0700446 frameworkResModule string
447
Colin Cross86a60ae2018-05-29 14:44:55 -0700448 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700449 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100450
451 noStandardLibs, noFrameworksLibs bool
452}
453
454func (s sdkDep) hasStandardLibs() bool {
455 return !s.noStandardLibs
456}
457
458func (s sdkDep) hasFrameworkLibs() bool {
459 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700460}
461
Colin Crossa4f08812018-10-02 22:03:40 -0700462type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700463 name string
464 path android.Path
465 target android.Target
466 coverageFile android.OptionalPath
467 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000468 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700469}
470
Jiyong Parkf1691d22021-03-29 20:11:58 +0900471func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700472 sdkDep := decodeSdkDep(ctx, sdkContext)
473 if sdkDep.useModule {
474 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
475 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400476 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700477 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000478 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000479 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000480 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700481 }
482 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
483 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
484 }
485 }
486 if sdkDep.systemModules != "" {
487 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
488 }
489}
490
Colin Cross32f676a2017-09-06 13:41:06 -0700491type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700492 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
493 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
494 // systemModules and java9Classpath instead.
495 bootClasspath classpath
496
497 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
498 // contains header jars for all static and non-static dependencies.
499 classpath classpath
500
501 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
502 // header jars for all non-static dependencies. Static dependencies have already been
503 // combined into the program jar.
504 dexClasspath classpath
505
506 // java9Classpath is the list of jars that will be added to the classpath when targeting
507 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
508 // are provided by systemModules.
509 java9Classpath classpath
510
Colin Cross748b2d82020-11-19 13:52:06 -0800511 processorPath classpath
512 errorProneProcessorPath classpath
513 processorClasses []string
514 staticJars android.Paths
515 staticHeaderJars android.Paths
516 staticResourceJars android.Paths
517 aidlIncludeDirs android.Paths
518 srcs android.Paths
519 srcJars android.Paths
520 systemModules *systemModules
521 aidlPreprocess android.OptionalPath
522 kotlinStdlib android.Paths
523 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700524 kotlinPlugins android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800525
526 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700527}
Colin Cross2fe66872015-03-30 17:20:39 -0700528
Colin Cross54250902017-12-05 09:28:08 -0800529func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
530 for _, f := range dep.Srcs() {
531 if f.Ext() != ".jar" {
532 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
533 ctx.OtherModuleName(dep.(blueprint.Module)))
534 }
535 }
536}
537
Jiyong Parkf1691d22021-03-29 20:11:58 +0900538func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700539 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700540 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700541 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900542 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca384250c2023-02-02 17:56:19 +0000543 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000544 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700545 }
Nan Zhang357466b2018-04-17 17:38:36 -0700546}
547
Jihoon Kangff878bf2022-12-22 21:26:06 +0000548// Java version for stubs generation
549func getStubsJavaVersion() javaVersion {
550 return JAVA_VERSION_8
551}
552
Colin Cross1e743852019-10-28 11:37:20 -0700553type javaVersion int
554
555const (
556 JAVA_VERSION_UNSUPPORTED = 0
557 JAVA_VERSION_6 = 6
558 JAVA_VERSION_7 = 7
559 JAVA_VERSION_8 = 8
560 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000561 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100562 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700563)
564
565func (v javaVersion) String() string {
566 switch v {
567 case JAVA_VERSION_6:
568 return "1.6"
569 case JAVA_VERSION_7:
570 return "1.7"
571 case JAVA_VERSION_8:
572 return "1.8"
573 case JAVA_VERSION_9:
574 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000575 case JAVA_VERSION_11:
576 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100577 case JAVA_VERSION_17:
578 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700579 default:
580 return "unsupported"
581 }
582}
583
Cole Faustd96eebf2022-06-28 14:41:27 -0700584func (v javaVersion) StringForKotlinc() string {
585 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
586 // error: unknown JVM target version: foo
587 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
588 switch v {
589 case JAVA_VERSION_7:
590 return "1.6"
591 case JAVA_VERSION_9:
592 return "9"
593 default:
594 return v.String()
595 }
596}
597
Colin Cross1e743852019-10-28 11:37:20 -0700598// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
599func (v javaVersion) usesJavaModules() bool {
600 return v >= 9
601}
602
603func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100604 switch javaVersion {
605 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700606 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100607 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700608 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100609 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700610 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100611 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700612 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000613 case "11":
614 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100615 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100616 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100617 case "10", "12", "13", "14", "15", "16":
618 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700619 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100620 default:
621 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700622 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100623 }
624}
625
Colin Cross2fe66872015-03-30 17:20:39 -0700626//
627// Java libraries (.jar file)
628//
629
Colin Crossf506d872017-07-19 15:53:04 -0700630type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700631 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700632
Jared Duke5979b302022-12-19 21:08:39 +0000633 exportedProguardFlagFiles android.Paths
634
Colin Cross09ad3a62023-11-15 12:29:33 -0800635 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Colin Cross2fe66872015-03-30 17:20:39 -0700636}
637
Jiyong Park45bf82e2020-12-15 22:29:02 +0900638var _ android.ApexModule = (*Library)(nil)
639
satayevd604b212021-07-21 14:23:52 +0100640// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100641type PermittedPackagesForUpdatableBootJars interface {
642 PermittedPackagesForUpdatableBootJars() []string
643}
644
645var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
646
647func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
648 return j.properties.Permitted_packages
649}
650
Colin Cross42be7612019-02-21 18:12:14 -0800651func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000652 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Cross56a83212020-09-15 18:30:11 -0700653 if apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000654 return true
655 }
656
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000657 // Store uncompressed (and do not strip) dex files from boot class path jars.
658 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
659 return true
660 }
661
662 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000663 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000664 return true
665 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800666 if ctx.Config().UncompressPrivAppDex() &&
667 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
668 return true
669 }
670
Colin Cross2fc72f62018-12-21 12:59:54 -0800671 return false
672}
673
Jiakai Zhang22450f22021-10-11 03:05:20 +0000674// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
675func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
676 if dexer.dexProperties.Uncompress_dex == nil {
677 // If the value was not force-set by the user, use reasonable default based on the module.
678 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
679 }
680}
681
Colin Crossf506d872017-07-19 15:53:04 -0700682func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000683
684 j.provideHiddenAPIPropertyInfo(ctx)
685
Jiyong Park92315372021-04-02 08:45:46 +0900686 j.sdkVersion = j.SdkVersion(ctx)
687 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000688 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900689
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000690 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
691
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000692 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
693 ctx.SetProvider(ProguardSpecInfoProvider, proguardSpecInfo)
694 j.exportedProguardFlagFiles = proguardSpecInfo.ProguardFlagsFiles.ToList()
695 j.extraProguardFlagFiles = append(j.extraProguardFlagFiles, j.exportedProguardFlagFiles...)
696
Colin Cross56a83212020-09-15 18:30:11 -0700697 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
698 if !apexInfo.IsForPlatform() {
699 j.hideApexVariantFromMake = true
700 }
701
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100702 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +0000703 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800704 if ctx.Device() {
705 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
706 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
707 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
708 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
709 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
710 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
711 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700712 j.compile(ctx, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700713
Colin Cross56a83212020-09-15 18:30:11 -0700714 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900715 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Cross09ad3a62023-11-15 12:29:33 -0800716 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700717 if j.InstallMixin != nil {
718 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
719 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700720 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
721 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800722 j.hostdexInstallFile = ctx.InstallFile(
723 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700724 j.Stem()+"-hostdex.jar", j.outputFile)
725 }
726 var installDir android.InstallPath
727 if ctx.InstallInTestcases() {
728 var archDir string
729 if !ctx.Host() {
730 archDir = ctx.DeviceConfig().DeviceArch()
731 }
732 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
733 } else {
734 installDir = android.PathForModuleInstall(ctx, "framework")
735 }
736 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700737 }
Colin Crossb7a63242015-04-16 14:09:14 -0700738}
739
Colin Crossf506d872017-07-19 15:53:04 -0700740func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700741 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100742 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700743}
744
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000745const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000746 aidlIncludeDir = "aidl"
747 javaDir = "java"
748 jarFileSuffix = ".jar"
749 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000750)
751
Paul Duffina0dbf432019-12-05 11:25:53 +0000752// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000753func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000754 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000755}
756
Paul Duffina04c1072020-03-02 10:16:35 +0000757func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
758 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000759}
760
Paul Duffin13879572019-11-28 14:31:38 +0000761type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000762 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000763
764 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000765 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000766 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
767
768 // Function to compute the snapshot relative path to which the named library's
769 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000770 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000771
772 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
773 // files like aidl files should also be copied.
774 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000775}
776
Paul Duffindb170e42020-12-08 17:48:25 +0000777const (
778 onlyCopyJarToSnapshot = true
779 copyEverythingToSnapshot = false
780)
781
Paul Duffin296701e2021-07-14 10:29:36 +0100782func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
783 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000784}
785
786func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
787 _, ok := module.(*Library)
788 return ok
789}
790
Paul Duffin3a4eb502020-03-19 16:11:18 +0000791func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
792 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000793}
Paul Duffina0dbf432019-12-05 11:25:53 +0000794
Paul Duffin14eb4672020-03-02 11:33:02 +0000795func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000796 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000797}
798
799type librarySdkMemberProperties struct {
800 android.SdkMemberPropertiesBase
801
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000802 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000803 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100804
805 // The list of permitted packages that need to be passed to the prebuilts as they are used to
806 // create the updatable-bcp-packages.txt file.
807 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +0000808
809 // The value of the min_sdk_version property, translated into a number where possible.
810 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800811
812 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +0000813}
814
Paul Duffin3a4eb502020-03-19 16:11:18 +0000815func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000816 j := variant.(*Library)
817
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000818 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +0000819
Paul Duffina551a1c2020-03-17 21:04:24 +0000820 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100821
822 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +0000823
824 // If the min_sdk_version was set then add the canonical representation of the API level to the
825 // snapshot.
826 if j.deviceProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -0700827 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
828 if err != nil {
829 ctx.ModuleErrorf("%s", err)
830 }
Paul Duffinbb638eb2022-11-26 13:36:38 +0000831 p.MinSdkVersion = proptools.StringPtr(canonical)
832 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800833
834 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
835 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
836 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000837}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000838
Paul Duffin3a4eb502020-03-19 16:11:18 +0000839func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000840 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000841
Paul Duffindb170e42020-12-08 17:48:25 +0000842 memberType := ctx.MemberType().(*librarySdkMemberType)
843
Paul Duffina551a1c2020-03-17 21:04:24 +0000844 exportedJar := p.JarToExport
845 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000846 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000847 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000848
849 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000850 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
851
Paul Duffina551a1c2020-03-17 21:04:24 +0000852 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
853 }
854
Paul Duffinbb638eb2022-11-26 13:36:38 +0000855 if p.MinSdkVersion != nil {
856 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
857 }
858
Paul Duffin869de142021-07-15 14:14:41 +0100859 if len(p.PermittedPackages) > 0 {
860 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
861 }
862
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800863 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
864 if p.DexPreoptProfileGuided != nil {
865 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
866 }
867
Paul Duffindb170e42020-12-08 17:48:25 +0000868 // Do not copy anything else to the snapshot.
869 if memberType.onlyCopyJarToSnapshot {
870 return
871 }
872
Paul Duffina551a1c2020-03-17 21:04:24 +0000873 aidlIncludeDirs := p.AidlIncludeDirs
874 if len(aidlIncludeDirs) != 0 {
875 sdkModuleContext := ctx.SdkModuleContext()
876 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000877 // TODO(jiyong): copy parcelable declarations only
878 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
879 for _, file := range aidlFiles {
880 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
881 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000882 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000883
Paul Duffina551a1c2020-03-17 21:04:24 +0000884 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000885 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000886}
887
Colin Cross1b16b0e2019-02-12 14:41:32 -0800888// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
889//
890// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
891// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
892// as a `static_libs` dependency of another module.
893//
894// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
895// a device.
896//
897// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
898// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700899func LibraryFactory() android.Module {
900 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700901
Colin Crossce6734e2020-06-15 16:09:53 -0700902 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700903
Paul Duffin71b33cc2021-06-23 11:39:47 +0100904 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100905
Jiyong Park7f7766d2019-07-25 22:02:35 +0900906 android.InitApexModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800907 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900908 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700909 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700910}
911
Colin Cross1b16b0e2019-02-12 14:41:32 -0800912// java_library_static is an obsolete alias for java_library.
913func LibraryStaticFactory() android.Module {
914 return LibraryFactory()
915}
916
917// java_library_host builds and links sources into a `.jar` file for the host.
918//
919// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
920// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700921func LibraryHostFactory() android.Module {
922 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700923
Colin Crossce6734e2020-06-15 16:09:53 -0700924 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700925
Colin Cross9ae1b922018-06-26 17:59:05 -0700926 module.Module.properties.Installable = proptools.BoolPtr(true)
927
Jiyong Park7f7766d2019-07-25 22:02:35 +0900928 android.InitApexModule(module)
Wei Libafb6d62021-12-10 03:14:59 -0800929 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900930 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700931 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700932}
933
934//
Colin Crossb628ea52018-08-14 16:42:33 -0700935// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700936//
937
Dan Shi95d19422020-08-15 12:24:26 -0700938// Test option struct.
939type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800940 android.CommonTestOptions
941
Dan Shi95d19422020-08-15 12:24:26 -0700942 // a list of extra test configuration files that should be installed with the module.
943 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -0800944
945 // Extra <option> tags to add to the auto generated test xml file. The "key"
946 // is optional in each of these.
947 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +0000948
949 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
950 // The "key" is optional in each of these.
951 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -0700952}
953
Colin Cross05638fc2018-04-09 18:40:24 -0700954type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700955 // list of compatibility suites (for example "cts", "vts") that the module should be
956 // installed into.
957 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700958
959 // the name of the test configuration (for example "AndroidTest.xml") that should be
960 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800961 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700962
Jack He33338892018-09-19 02:21:28 -0700963 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
964 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800965 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700966
Colin Crossd96ca352018-08-10 16:06:24 -0700967 // list of files or filegroup modules that provide data that should be installed alongside
968 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900969 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700970
971 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
972 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
973 // explicitly.
974 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800975
976 // Add parameterized mainline modules to auto generated test config. The options will be
977 // handled by TradeFed to do downloading and installing the specified modules on the device.
978 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700979
980 // Test options.
981 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800982
983 // Names of modules containing JNI libraries that should be installed alongside the test.
984 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700985
986 // Install the test into a folder named for the module in all test suites.
987 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700988}
989
Liz Kammerdd849a82020-06-12 16:38:45 -0700990type hostTestProperties struct {
991 // list of native binary modules that should be installed alongside the test
992 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000993
994 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000995 // This property only adds the first variant of the dependency
996 Data_device_bins_first []string `android:"arch_variant"`
997
998 // list of device binary modules that should be installed alongside the test
999 // This property adds 64bit AND 32bit variants of the dependency
1000 Data_device_bins_both []string `android:"arch_variant"`
1001
1002 // list of device binary modules that should be installed alongside the test
1003 // This property only adds 64bit variants of the dependency
1004 Data_device_bins_64 []string `android:"arch_variant"`
1005
1006 // list of device binary modules that should be installed alongside the test
1007 // This property adds 32bit variants of the dependency if available, or else
1008 // defaults to the 64bit variant
1009 Data_device_bins_prefer32 []string `android:"arch_variant"`
1010
1011 // list of device binary modules that should be installed alongside the test
1012 // This property only adds 32bit variants of the dependency
1013 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001014}
1015
Paul Duffin42df1442019-03-20 12:45:53 +00001016type testHelperLibraryProperties struct {
1017 // list of compatibility suites (for example "cts", "vts") that the module should be
1018 // installed into.
1019 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001020
1021 // Install the test into a folder named for the module in all test suites.
1022 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001023}
1024
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001025type prebuiltTestProperties struct {
1026 // list of compatibility suites (for example "cts", "vts") that the module should be
1027 // installed into.
1028 Test_suites []string `android:"arch_variant"`
1029
1030 // the name of the test configuration (for example "AndroidTest.xml") that should be
1031 // installed with the module.
1032 Test_config *string `android:"path,arch_variant"`
1033}
1034
Colin Cross05638fc2018-04-09 18:40:24 -07001035type Test struct {
1036 Library
1037
1038 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001039
Dan Shi95d19422020-08-15 12:24:26 -07001040 testConfig android.Path
1041 extraTestConfigs android.Paths
1042 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001043}
1044
Liz Kammerdd849a82020-06-12 16:38:45 -07001045type TestHost struct {
1046 Test
1047
1048 testHostProperties hostTestProperties
1049}
1050
Paul Duffin42df1442019-03-20 12:45:53 +00001051type TestHelperLibrary struct {
1052 Library
1053
1054 testHelperLibraryProperties testHelperLibraryProperties
1055}
1056
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001057type JavaTestImport struct {
1058 Import
1059
1060 prebuiltTestProperties prebuiltTestProperties
1061
1062 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001063 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001064}
1065
Colin Cross24cc4be62021-11-03 14:09:41 -07001066func (j *Test) InstallInTestcases() bool {
1067 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1068 // testcases by base_rules.mk.
1069 return !j.Host()
1070}
1071
1072func (j *TestHelperLibrary) InstallInTestcases() bool {
1073 return true
1074}
1075
1076func (j *JavaTestImport) InstallInTestcases() bool {
1077 return true
1078}
1079
Yu Liud8aa2002023-10-05 11:40:06 -07001080func (j *TestHost) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
1081 return ctx.DeviceConfig().NativeCoverageEnabled()
1082}
1083
Sam Delmericocc271e22022-06-01 15:45:02 +00001084func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1085 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1086 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1087 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1088 }
1089
1090 var maybeAndroid32Target *android.Target
1091 var maybeAndroid64Target *android.Target
1092 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1093 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1094 if len(android32TargetList) > 0 {
1095 maybeAndroid32Target = &android32TargetList[0]
1096 }
1097 if len(android64TargetList) > 0 {
1098 maybeAndroid64Target = &android64TargetList[0]
1099 }
1100
1101 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1102 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1103 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1104 return
1105 }
1106 if maybeAndroid32Target != nil {
1107 ctx.AddFarVariationDependencies(
1108 maybeAndroid32Target.Variations(),
1109 dataDeviceBinsTag,
1110 j.testHostProperties.Data_device_bins_both...,
1111 )
1112 }
1113 if maybeAndroid64Target != nil {
1114 ctx.AddFarVariationDependencies(
1115 maybeAndroid64Target.Variations(),
1116 dataDeviceBinsTag,
1117 j.testHostProperties.Data_device_bins_both...,
1118 )
1119 }
1120 }
1121
1122 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1123 if maybeAndroid32Target != nil {
1124 ctx.AddFarVariationDependencies(
1125 maybeAndroid32Target.Variations(),
1126 dataDeviceBinsTag,
1127 j.testHostProperties.Data_device_bins_prefer32...,
1128 )
1129 } else {
1130 if maybeAndroid64Target == nil {
1131 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1132 return
1133 }
1134 ctx.AddFarVariationDependencies(
1135 maybeAndroid64Target.Variations(),
1136 dataDeviceBinsTag,
1137 j.testHostProperties.Data_device_bins_prefer32...,
1138 )
1139 }
1140 }
1141
1142 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1143 if maybeAndroid32Target == nil {
1144 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1145 return
1146 }
1147 deviceVariations := maybeAndroid32Target.Variations()
1148 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1149 }
1150
1151 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1152 if maybeAndroid64Target == nil {
1153 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1154 return
1155 }
1156 deviceVariations := maybeAndroid64Target.Variations()
1157 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1158 }
1159}
1160
Liz Kammerdd849a82020-06-12 16:38:45 -07001161func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1162 if len(j.testHostProperties.Data_native_bins) > 0 {
1163 for _, target := range ctx.MultiTargets() {
1164 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1165 }
1166 }
1167
Colin Crossf8d9c492021-01-26 11:01:43 -08001168 if len(j.testProperties.Jni_libs) > 0 {
1169 for _, target := range ctx.MultiTargets() {
1170 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1171 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1172 }
1173 }
1174
Sam Delmericocc271e22022-06-01 15:45:02 +00001175 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001176 j.deps(ctx)
1177}
1178
Yuexi Ma627263f2021-03-04 13:47:56 -08001179func (j *TestHost) AddExtraResource(p android.Path) {
1180 j.extraResources = append(j.extraResources, p)
1181}
1182
Sam Delmericocc271e22022-06-01 15:45:02 +00001183func (j *TestHost) dataDeviceBins() []string {
1184 ret := make([]string, 0,
1185 len(j.testHostProperties.Data_device_bins_first)+
1186 len(j.testHostProperties.Data_device_bins_both)+
1187 len(j.testHostProperties.Data_device_bins_prefer32)+
1188 len(j.testHostProperties.Data_device_bins_32)+
1189 len(j.testHostProperties.Data_device_bins_64),
1190 )
1191
1192 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1193 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1194 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1195 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1196 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1197
1198 return ret
1199}
1200
Sam Delmericob3342ce2022-01-20 21:10:28 +00001201func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1202 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001203 dataDeviceBins := j.dataDeviceBins()
1204 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001205 // add Tradefed configuration to push device bins to device for testing
1206 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1207 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001208 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001209 fullPath := filepath.Join(remoteDir, bin)
1210 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1211 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001212 configs = append(configs, tradefed.Object{
1213 Type: "target_preparer",
1214 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1215 Options: options,
1216 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001217 }
1218
1219 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Aditya Choudhary9b593522023-10-06 19:54:58 +00001220 ctx.SetProvider(testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001221}
1222
Colin Cross303e21f2018-08-07 16:49:25 -07001223func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001224 j.generateAndroidBuildActionsWithConfig(ctx, nil)
Aditya Choudhary9b593522023-10-06 19:54:58 +00001225 ctx.SetProvider(testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001226}
1227
1228func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001229 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1230 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001231 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001232 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1233 }
Cole Faust21680542022-12-07 18:18:37 -08001234 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1235 TestConfigProp: j.testProperties.Test_config,
1236 TestConfigTemplateProp: j.testProperties.Test_config_template,
1237 TestSuites: j.testProperties.Test_suites,
1238 Config: configs,
1239 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001240 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001241 AutoGenConfig: j.testProperties.Auto_gen_config,
1242 UnitTest: j.testProperties.Test_options.Unit_test,
1243 DeviceTemplate: "${JavaTestConfigTemplate}",
1244 HostTemplate: "${JavaHostTestConfigTemplate}",
1245 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1246 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001247
Colin Cross8a497952019-03-05 22:25:09 -08001248 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001249
Dan Shi95d19422020-08-15 12:24:26 -07001250 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1251
Liz Kammerdd849a82020-06-12 16:38:45 -07001252 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1253 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1254 })
1255
Sam Delmericob3342ce2022-01-20 21:10:28 +00001256 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1257 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1258 })
1259
Colin Crossf8d9c492021-01-26 11:01:43 -08001260 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
1261 sharedLibInfo := ctx.OtherModuleProvider(dep, cc.SharedLibraryInfoProvider).(cc.SharedLibraryInfo)
1262 if sharedLibInfo.SharedLibrary != nil {
1263 // Copy to an intermediate output directory to append "lib[64]" to the path,
1264 // so that it's compatible with the default rpath values.
1265 var relPath string
1266 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1267 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1268 } else {
1269 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1270 }
1271 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1272 ctx.Build(pctx, android.BuildParams{
1273 Rule: android.Cp,
1274 Input: sharedLibInfo.SharedLibrary,
1275 Output: relocatedLib,
1276 })
1277 j.data = append(j.data, relocatedLib)
1278 } else {
1279 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1280 }
1281 })
1282
Colin Cross303e21f2018-08-07 16:49:25 -07001283 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001284}
1285
Paul Duffin42df1442019-03-20 12:45:53 +00001286func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1287 j.Library.GenerateAndroidBuildActions(ctx)
1288}
1289
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001290func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001291 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1292 TestConfigProp: j.prebuiltTestProperties.Test_config,
1293 TestSuites: j.prebuiltTestProperties.Test_suites,
1294 DeviceTemplate: "${JavaTestConfigTemplate}",
1295 HostTemplate: "${JavaHostTestConfigTemplate}",
1296 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1297 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001298
1299 j.Import.GenerateAndroidBuildActions(ctx)
1300}
1301
1302type testSdkMemberType struct {
1303 android.SdkMemberTypeBase
1304}
1305
Paul Duffin296701e2021-07-14 10:29:36 +01001306func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1307 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001308}
1309
1310func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1311 _, ok := module.(*Test)
1312 return ok
1313}
1314
Paul Duffin3a4eb502020-03-19 16:11:18 +00001315func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1316 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001317}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001318
Paul Duffin14eb4672020-03-02 11:33:02 +00001319func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1320 return &testSdkMemberProperties{}
1321}
1322
1323type testSdkMemberProperties struct {
1324 android.SdkMemberPropertiesBase
1325
Paul Duffina551a1c2020-03-17 21:04:24 +00001326 JarToExport android.Path
1327 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001328}
1329
Paul Duffin3a4eb502020-03-19 16:11:18 +00001330func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001331 test := variant.(*Test)
1332
1333 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001334 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001335 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001336 }
1337
Paul Duffina551a1c2020-03-17 21:04:24 +00001338 p.JarToExport = implementationJars[0]
1339 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001340}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001341
Paul Duffin3a4eb502020-03-19 16:11:18 +00001342func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001343 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001344
Paul Duffina551a1c2020-03-17 21:04:24 +00001345 exportedJar := p.JarToExport
1346 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001347 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001348 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001349
1350 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001351 }
1352
1353 testConfig := p.TestConfig
1354 if testConfig != nil {
1355 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1356 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001357 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1358 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001359}
1360
Colin Cross1b16b0e2019-02-12 14:41:32 -08001361// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1362// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1363//
1364// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1365// compiled against the device bootclasspath.
1366//
1367// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1368// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001369func TestFactory() android.Module {
1370 module := &Test{}
1371
Colin Crossce6734e2020-06-15 16:09:53 -07001372 module.addHostAndDeviceProperties()
1373 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001374
Colin Cross9ae1b922018-06-26 17:59:05 -07001375 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001376 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001377 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001378
Colin Cross05638fc2018-04-09 18:40:24 -07001379 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001380 return module
1381}
1382
Paul Duffin42df1442019-03-20 12:45:53 +00001383// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1384func TestHelperLibraryFactory() android.Module {
1385 module := &TestHelperLibrary{}
1386
Colin Crossce6734e2020-06-15 16:09:53 -07001387 module.addHostAndDeviceProperties()
1388 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001389
Colin Cross9a4abed2019-04-24 13:19:28 -07001390 module.Module.properties.Installable = proptools.BoolPtr(true)
1391 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001392 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001393
Paul Duffin42df1442019-03-20 12:45:53 +00001394 InitJavaModule(module, android.HostAndDeviceSupported)
1395 return module
1396}
1397
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001398// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1399// and makes sure that it is added to the appropriate test suite.
1400//
1401// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1402// compiled against an Android classpath.
1403//
1404// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1405// for host modules.
1406func JavaTestImportFactory() android.Module {
1407 module := &JavaTestImport{}
1408
1409 module.AddProperties(
1410 &module.Import.properties,
1411 &module.prebuiltTestProperties)
1412
1413 module.Import.properties.Installable = proptools.BoolPtr(true)
1414
1415 android.InitPrebuiltModule(module, &module.properties.Jars)
1416 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001417 InitJavaModule(module, android.HostAndDeviceSupported)
1418 return module
1419}
1420
Colin Cross1b16b0e2019-02-12 14:41:32 -08001421// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1422// allow running the test with `atest` or a `TEST_MAPPING` file.
1423//
1424// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1425// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001426func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001427 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001428
Colin Crossce6734e2020-06-15 16:09:53 -07001429 module.addHostProperties()
1430 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001431 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001432
Yuexi Ma627263f2021-03-04 13:47:56 -08001433 InitTestHost(
1434 module,
1435 proptools.BoolPtr(true),
1436 nil,
1437 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001438
Zi Wang65b36722023-05-23 15:18:33 -07001439 android.InitBazelModule(module)
1440
Liz Kammerdd849a82020-06-12 16:38:45 -07001441 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001442
Colin Cross05638fc2018-04-09 18:40:24 -07001443 return module
1444}
1445
Yuexi Ma627263f2021-03-04 13:47:56 -08001446func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1447 th.properties.Installable = installable
1448 th.testProperties.Auto_gen_config = autoGenConfig
1449 th.testProperties.Test_suites = testSuites
1450}
1451
Colin Cross05638fc2018-04-09 18:40:24 -07001452//
Colin Cross2fe66872015-03-30 17:20:39 -07001453// Java Binaries (.jar file plus wrapper script)
1454//
1455
Colin Crossf506d872017-07-19 15:53:04 -07001456type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001457 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001458 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001459
1460 // Name of the class containing main to be inserted into the manifest as Main-Class.
1461 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001462
1463 // Names of modules containing JNI libraries that should be installed alongside the host
1464 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001465 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001466}
1467
Colin Crossf506d872017-07-19 15:53:04 -07001468type Binary struct {
1469 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001470
Colin Crossf506d872017-07-19 15:53:04 -07001471 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001472
Colin Cross6b4a32d2017-12-05 13:42:45 -08001473 isWrapperVariant bool
1474
Colin Crossc3315992017-12-08 19:12:36 -08001475 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001476 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001477}
1478
Alex Light24237172017-10-26 09:46:21 -07001479func (j *Binary) HostToolPath() android.OptionalPath {
1480 return android.OptionalPathForPath(j.binaryFile)
1481}
1482
Colin Crossf506d872017-07-19 15:53:04 -07001483func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001484 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
1485
Colin Cross6b4a32d2017-12-05 13:42:45 -08001486 if ctx.Arch().ArchType == android.Common {
1487 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001488 if j.binaryProperties.Main_class != nil {
1489 if j.properties.Manifest != nil {
1490 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1491 }
1492 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1493 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1494 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1495 }
1496
Colin Cross6b4a32d2017-12-05 13:42:45 -08001497 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001498 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001499 // Handle the binary wrapper
1500 j.isWrapperVariant = true
1501
Colin Cross366938f2017-12-11 16:29:02 -08001502 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001503 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001504 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001505 if ctx.Windows() {
1506 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1507 }
1508
Zi Wangca65b402022-10-10 13:45:06 -07001509 if ctx.Device() {
1510 // device binary should have a main_class property if it does not
1511 // have a specific wrapper, so that a default wrapper can
1512 // be generated for it.
1513 if j.binaryProperties.Main_class == nil {
1514 ctx.PropertyErrorf("main_class", "main_class property "+
1515 "is required for device binary if no default wrapper is assigned")
1516 } else {
1517 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1518 jarName := j.Stem() + ".jar"
1519 partition := j.PartitionTag(ctx.DeviceConfig())
1520 ctx.Build(pctx, android.BuildParams{
1521 Rule: deviceBinaryWrapper,
1522 Output: wrapper,
1523 Args: map[string]string{
1524 "jar_name": jarName,
1525 "partition": partition,
1526 "main_class": String(j.binaryProperties.Main_class),
1527 },
1528 })
1529 j.wrapperFile = wrapper
1530 }
1531 } else {
1532 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1533 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001534 }
1535
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001536 ext := ""
1537 if ctx.Windows() {
1538 ext = ".bat"
1539 }
1540
Colin Crossc179ea62020-10-09 10:54:15 -07001541 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001542 // of the wrapper variant, which will include the common variant's jar file and any JNI
1543 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001544 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001545 ctx.ModuleName()+ext, j.wrapperFile)
1546 }
Colin Cross2fe66872015-03-30 17:20:39 -07001547}
1548
Colin Crossf506d872017-07-19 15:53:04 -07001549func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001550 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001551 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001552 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001553 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001554 // These dependencies ensure the host installation rules will install the jar file and
1555 // the jni libraries when the wrapper is installed.
1556 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1557 ctx.AddVariationDependencies(
1558 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1559 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001560 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001561}
1562
Colin Cross1b16b0e2019-02-12 14:41:32 -08001563// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1564// as well.
1565//
1566// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1567// compiled against the device bootclasspath.
1568//
1569// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1570// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001571func BinaryFactory() android.Module {
1572 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001573
Colin Crossce6734e2020-06-15 16:09:53 -07001574 module.addHostAndDeviceProperties()
1575 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001576
Colin Cross9ae1b922018-06-26 17:59:05 -07001577 module.Module.properties.Installable = proptools.BoolPtr(true)
1578
Colin Cross6b4a32d2017-12-05 13:42:45 -08001579 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1580 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001581 android.InitBazelModule(module)
1582
Colin Cross36242852017-06-23 15:06:31 -07001583 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001584}
1585
Colin Cross1b16b0e2019-02-12 14:41:32 -08001586// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1587//
1588// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1589// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001590func BinaryHostFactory() android.Module {
1591 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001592
Colin Crossce6734e2020-06-15 16:09:53 -07001593 module.addHostProperties()
1594 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001595
Colin Cross9ae1b922018-06-26 17:59:05 -07001596 module.Module.properties.Installable = proptools.BoolPtr(true)
1597
Colin Cross6b4a32d2017-12-05 13:42:45 -08001598 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1599 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001600 android.InitBazelModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001601 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001602}
1603
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001604type JavaApiContribution struct {
1605 android.ModuleBase
1606 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00001607 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001608
1609 properties struct {
1610 // name of the API surface
1611 Api_surface *string
1612
1613 // relative path to the API signature text file
1614 Api_file *string `android:"path"`
1615 }
1616}
1617
1618func ApiContributionFactory() android.Module {
1619 module := &JavaApiContribution{}
1620 android.InitAndroidModule(module)
1621 android.InitDefaultableModule(module)
1622 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001623 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001624 return module
1625}
1626
1627type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00001628 ApiFile android.Path
1629 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001630}
1631
1632var JavaApiImportProvider = blueprint.NewProvider(JavaApiImportInfo{})
1633
1634func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001635 var apiFile android.Path = nil
1636 if apiFileString := ap.properties.Api_file; apiFileString != nil {
1637 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
1638 }
1639
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001640 ctx.SetProvider(JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00001641 ApiFile: apiFile,
1642 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001643 })
1644}
1645
1646type ApiLibrary struct {
1647 android.ModuleBase
1648 android.DefaultableModuleBase
1649
Spandan Dascb368ea2023-03-22 04:27:05 +00001650 hiddenAPI
1651 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00001652 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00001653
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001654 properties JavaApiLibraryProperties
1655
Jihoon Kang01e522c2023-03-14 01:09:34 +00001656 stubsSrcJar android.WritablePath
1657 stubsJar android.WritablePath
1658 stubsJarWithoutStaticLibs android.WritablePath
1659 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00001660 // .dex of stubs, used for hiddenapi processing
1661 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00001662
1663 validationPaths android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001664}
1665
1666type JavaApiLibraryProperties struct {
1667 // name of the API surface
1668 Api_surface *string
1669
Jihoon Kang60d4a092022-11-17 23:47:43 +00001670 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00001671 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00001672 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001673
1674 // List of flags to be passed to the javac compiler to generate jar file
1675 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001676
1677 // List of shared java libs that this module has dependencies to and
1678 // should be passed as classpath in javac invocation
1679 Libs []string
Jihoon Kange30fff02023-02-14 20:18:20 +00001680
1681 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00001682 // merge zipped after metalava invocation
Jihoon Kange30fff02023-02-14 20:18:20 +00001683 Static_libs []string
Jihoon Kang01e522c2023-03-14 01:09:34 +00001684
Jihoon Kangca198c22023-06-22 23:13:51 +00001685 // Java Api library to provide the full API surface stub jar file.
1686 // If this property is set, the stub jar of this module is created by
1687 // extracting the compiled class files provided by the
1688 // full_api_surface_stub module.
1689 Full_api_surface_stub *string
Jihoon Kang862da6f2023-08-01 06:28:51 +00001690
1691 // Version of previously released API file for compatibility check.
1692 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00001693
1694 // java_system_modules module providing the jar to be added to the
1695 // bootclasspath when compiling the stubs.
1696 // The jar will also be passed to metalava as a classpath to
1697 // generate compilable stubs.
1698 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00001699
1700 // If true, the module runs validation on the API signature files provided
1701 // by the modules passed via api_contributions by checking if the files are
1702 // in sync with the source Java files. However, the environment variable
1703 // DISABLE_STUB_VALIDATION has precedence over this property.
1704 Enable_validation *bool
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001705}
1706
1707func ApiLibraryFactory() android.Module {
1708 module := &ApiLibrary{}
1709 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001710 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001711 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00001712 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001713 return module
1714}
1715
1716func (al *ApiLibrary) ApiSurface() *string {
1717 return al.properties.Api_surface
1718}
1719
1720func (al *ApiLibrary) StubsJar() android.Path {
1721 return al.stubsJar
1722}
1723
1724func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00001725 srcs android.Paths, homeDir android.WritablePath,
1726 classpath android.Paths) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001727 rule.Command().Text("rm -rf").Flag(homeDir.String())
1728 rule.Command().Text("mkdir -p").Flag(homeDir.String())
1729
1730 cmd := rule.Command()
1731 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
1732
1733 if metalavaUseRbe(ctx) {
1734 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
1735 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
1736 labels := map[string]string{"type": "tool", "name": "metalava"}
1737
1738 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
1739 rule.Rewrapper(&remoteexec.REParams{
1740 Labels: labels,
1741 ExecStrategy: execStrategy,
1742 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
1743 Platform: map[string]string{remoteexec.PoolKey: pool},
1744 })
1745 }
1746
1747 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
1748 Flag(config.JavacVmFlags).
1749 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001750 FlagWithInputList("--source-files ", srcs, " ")
1751
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02001752 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001753 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00001754 Flag("--include-annotations").
1755 // The flag makes nullability issues as warnings rather than errors by replacing
1756 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
1757 // and these packages are meant to have everything annotated
1758 // @RecentlyNullable/@RecentlyNonNull.
1759 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001760 FlagWithArg("--repeat-errors-max ", "10").
1761 FlagWithArg("--hide ", "UnresolvedImport").
1762 FlagWithArg("--hide ", "InvalidNullabilityOverride").
1763 FlagWithArg("--hide ", "ChangedDefault")
1764
Jihoon Kang4ec24872023-10-05 17:26:09 +00001765 if len(classpath) == 0 {
1766 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
1767 // classes on the classpath when an API file contains missing classes. However, as this command
1768 // does not specify `--classpath` this is not needed for that. However, this is also used as a
1769 // signal to the special metalava code for generating stubs from text files that it needs to add
1770 // some additional items into the API (e.g. default constructors).
1771 cmd.FlagWithArg("--api-class-resolution ", "api")
1772 } else {
1773 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
1774 cmd.FlagWithInputList("--classpath ", classpath, ":")
1775 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01001776
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001777 return cmd
1778}
1779
Jihoon Kang1bff0342023-01-17 20:40:22 +00001780func (al *ApiLibrary) HeaderJars() android.Paths {
1781 return android.Paths{al.stubsJar}
1782}
1783
1784func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
1785 return nil, nil
1786}
1787
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001788func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
1789 if stubsDir.Valid() {
1790 cmd.FlagWithArg("--stubs ", stubsDir.String())
1791 }
1792}
1793
Jihoon Kang063ec002023-06-28 01:16:23 +00001794func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
1795 for _, validationPath := range validationPaths {
1796 cmd.Validation(validationPath)
1797 }
1798}
1799
Jihoon Kangca198c22023-06-22 23:13:51 +00001800// This method extracts the stub class files from the stub jar file provided
1801// from full_api_surface_stub module instead of compiling the srcjar generated from invoking metalava.
Jihoon Kang01e522c2023-03-14 01:09:34 +00001802// This method is used because metalava can generate compilable from-text stubs only when
Jihoon Kangca198c22023-06-22 23:13:51 +00001803// the codebase encompasses all classes listed in the input API text file, and a class can extend
Jihoon Kang01e522c2023-03-14 01:09:34 +00001804// a class that is not within the same API domain.
Jihoon Kangca198c22023-06-22 23:13:51 +00001805func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, fullApiSurfaceStubJar android.Path) {
1806 classFilesList := android.PathForModuleOut(ctx, "metalava", "classes.txt")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001807 unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
1808
1809 rule.Command().
1810 BuiltTool("list_files").
1811 Text(stubsDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001812 FlagWithOutput("--out ", classFilesList).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001813 FlagWithArg("--extensions ", ".java").
Jihoon Kangca198c22023-06-22 23:13:51 +00001814 FlagWithArg("--root ", unzippedSrcJarDir.String()).
1815 Flag("--classes")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001816
1817 rule.Command().
1818 Text("unzip").
1819 Flag("-q").
Jihoon Kangca198c22023-06-22 23:13:51 +00001820 Input(fullApiSurfaceStubJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001821 FlagWithArg("-d ", unzippedSrcJarDir.String())
1822
1823 rule.Command().
1824 BuiltTool("soong_zip").
Jihoon Kangca198c22023-06-22 23:13:51 +00001825 Flag("-jar").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001826 Flag("-write_if_changed").
Jihoon Kangca198c22023-06-22 23:13:51 +00001827 Flag("-ignore_missing_files").
Jihoon Kangd02a4362023-09-12 23:54:43 +00001828 Flag("-quiet").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001829 FlagWithArg("-C ", unzippedSrcJarDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001830 FlagWithInput("-l ", classFilesList).
1831 FlagWithOutput("-o ", al.stubsJarWithoutStaticLibs)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001832}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001833
1834func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00001835 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00001836 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
1837 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00001838 for _, apiContributionName := range apiContributions {
1839 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00001840
1841 // Add the java_api_contribution module generating droidstubs module
1842 // as dependency when validation adding conditions are met and
1843 // the java_api_contribution module name has ".api.contribution" suffix.
1844 // All droidstubs-generated modules possess the suffix in the name,
1845 // but there is no such guarantee for tests.
1846 if addValidations {
1847 if strings.HasSuffix(apiContributionName, ".api.contribution") {
1848 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
1849 } else {
1850 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
1851 "current timestamp provider is not found for the api "+
1852 "contribution %s",
1853 ctx.ModuleName(),
1854 apiContributionName,
1855 )
1856 }
1857 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001858 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001859 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001860 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
Jihoon Kangca198c22023-06-22 23:13:51 +00001861 if al.properties.Full_api_surface_stub != nil {
1862 ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Full_api_surface_stub))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001863 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00001864 if al.properties.System_modules != nil {
1865 ctx.AddVariationDependencies(nil, systemModulesTag, String(al.properties.System_modules))
1866 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001867}
1868
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001869// Map where key is the api scope name and value is the int value
1870// representing the order of the api scope, narrowest to the widest
1871var scopeOrderMap = allApiScopes.MapToIndex(
1872 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00001873
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001874func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
1875 for _, srcFileInfo := range srcFilesInfo {
1876 if srcFileInfo.ApiSurface == "" {
1877 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00001878 }
1879 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001880 sort.Slice(srcFilesInfo, func(i, j int) bool {
1881 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
1882 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00001883
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001884 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00001885}
1886
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001887func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1888
1889 rule := android.NewRuleBuilder(pctx, ctx)
1890
1891 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
1892 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
1893 SandboxInputs()
1894
Jihoon Kang063ec002023-06-28 01:16:23 +00001895 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001896 rule.Command().Text("rm -rf").Text(stubsDir.String())
1897 rule.Command().Text("mkdir -p").Text(stubsDir.String())
1898
1899 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
1900
Jihoon Kang8fe19822023-09-14 06:27:36 +00001901 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001902 var classPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00001903 var staticLibs android.Paths
Jihoon Kangca198c22023-06-22 23:13:51 +00001904 var depApiSrcsStubsJar android.Path
Jihoon Kang4ec24872023-10-05 17:26:09 +00001905 var systemModulesPaths android.Paths
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001906 ctx.VisitDirectDeps(func(dep android.Module) {
1907 tag := ctx.OtherModuleDependencyTag(dep)
1908 switch tag {
1909 case javaApiContributionTag:
1910 provider := ctx.OtherModuleProvider(dep, JavaApiImportProvider).(JavaApiImportInfo)
Jihoon Kang8fe19822023-09-14 06:27:36 +00001911 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001912 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
1913 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00001914 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001915 case libTag:
1916 provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
1917 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001918 case staticLibTag:
1919 provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
1920 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001921 case depApiSrcsTag:
Jihoon Kangca198c22023-06-22 23:13:51 +00001922 provider := ctx.OtherModuleProvider(dep, JavaInfoProvider).(JavaInfo)
1923 depApiSrcsStubsJar = provider.HeaderJars[0]
Jihoon Kang4ec24872023-10-05 17:26:09 +00001924 case systemModulesTag:
1925 module := dep.(SystemModulesProvider)
1926 systemModulesPaths = append(systemModulesPaths, module.HeaderJars()...)
Jihoon Kang063ec002023-06-28 01:16:23 +00001927 case metalavaCurrentApiTimestampTag:
1928 if currentApiTimestampProvider, ok := dep.(currentApiTimestampProvider); ok {
1929 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp())
1930 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001931 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00001932 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001933
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001934 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
1935 var srcFiles android.Paths
1936 for _, srcFileInfo := range srcFilesInfo {
1937 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00001938 }
1939
Jihoon Kang160634c2023-05-25 05:28:29 +00001940 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00001941 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
1942 }
1943
Jihoon Kang4ec24872023-10-05 17:26:09 +00001944 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001945
1946 al.stubsFlags(ctx, cmd, stubsDir)
1947
Jihoon Kang862da6f2023-08-01 06:28:51 +00001948 migratingNullability := String(al.properties.Previous_api) != ""
1949 if migratingNullability {
1950 previousApi := android.PathForModuleSrc(ctx, String(al.properties.Previous_api))
1951 cmd.FlagWithInput("--migrate-nullness ", previousApi)
1952 }
1953
Jihoon Kang063ec002023-06-28 01:16:23 +00001954 al.addValidation(ctx, cmd, al.validationPaths)
1955
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001956 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00001957 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
1958 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001959
Jihoon Kangca198c22023-06-22 23:13:51 +00001960 if depApiSrcsStubsJar != nil {
1961 al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsJar)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001962 }
Jihoon Kangca198c22023-06-22 23:13:51 +00001963 rule.Command().
1964 BuiltTool("soong_zip").
1965 Flag("-write_if_changed").
1966 Flag("-jar").
1967 FlagWithOutput("-o ", al.stubsSrcJar).
1968 FlagWithArg("-C ", stubsDir.String()).
1969 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001970
Paul Duffin336b16a2023-08-15 23:10:13 +01001971 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001972
Jihoon Kangca198c22023-06-22 23:13:51 +00001973 if depApiSrcsStubsJar == nil {
1974 var flags javaBuilderFlags
1975 flags.javaVersion = getStubsJavaVersion()
1976 flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
1977 flags.classpath = classpath(classPaths)
Jihoon Kang4ec24872023-10-05 17:26:09 +00001978 flags.bootClasspath = classpath(systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001979
Vadim Spivak3c496f02023-06-08 06:14:59 +00001980 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
1981
Jihoon Kangca198c22023-06-22 23:13:51 +00001982 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
Vadim Spivak3c496f02023-06-08 06:14:59 +00001983 android.Paths{al.stubsSrcJar}, annoSrcJar, flags, android.Paths{})
Jihoon Kangca198c22023-06-22 23:13:51 +00001984 }
Jihoon Kang423d2292022-11-29 23:10:10 +00001985
Jihoon Kange30fff02023-02-14 20:18:20 +00001986 builder := android.NewRuleBuilder(pctx, ctx)
1987 builder.Command().
1988 BuiltTool("merge_zips").
1989 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001990 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00001991 Inputs(staticLibs)
1992 builder.Build("merge_zips", "merge jar files")
1993
Spandan Dascb368ea2023-03-22 04:27:05 +00001994 // compile stubs to .dex for hiddenapi processing
1995 dexParams := &compileDexParams{
1996 flags: javaBuilderFlags{},
1997 sdkVersion: al.SdkVersion(ctx),
1998 minSdkVersion: al.MinSdkVersion(ctx),
1999 classesJar: al.stubsJar,
2000 jarName: ctx.ModuleName() + ".jar",
2001 }
2002 dexOutputFile := al.dexer.compileDex(ctx, dexParams)
2003 uncompressed := true
2004 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2005 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2006 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2007
Jihoon Kang423d2292022-11-29 23:10:10 +00002008 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002009
2010 ctx.SetProvider(JavaInfoProvider, JavaInfo{
Jihoon Kang1bff0342023-01-17 20:40:22 +00002011 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2012 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2013 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2014 AidlIncludeDirs: android.Paths{},
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002015 // No aconfig libraries on api libraries
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002016 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002017}
2018
Spandan Dascb368ea2023-03-22 04:27:05 +00002019func (al *ApiLibrary) DexJarBuildPath() OptionalDexJarPath {
2020 return al.dexJarFile
2021}
2022
2023func (al *ApiLibrary) DexJarInstallPath() android.Path {
2024 return al.dexJarFile.Path()
2025}
2026
2027func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2028 return nil
2029}
2030
2031// java_api_library constitutes the sdk, and does not build against one
2032func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2033 return android.SdkSpecNone
2034}
2035
2036// java_api_library is always at "current". Return FutureApiLevel
2037func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2038 return android.FutureApiLevel
2039}
2040
2041// implement the following interfaces for hiddenapi processing
2042var _ hiddenAPIModule = (*ApiLibrary)(nil)
2043var _ UsesLibraryDependency = (*ApiLibrary)(nil)
2044
Colin Cross2fe66872015-03-30 17:20:39 -07002045//
2046// Java prebuilts
2047//
2048
Colin Cross74d73e22017-08-02 11:05:49 -07002049type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002050 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002051
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002052 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2053 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002054 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002055
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002056 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2057 // specified.
2058 Min_sdk_version *string
2059
William Loh5a082f92022-05-17 20:21:50 +00002060 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2061 // and uses-permission tags in manifest_fixer.
2062 Replace_max_sdk_version_placeholder *string
2063
Colin Cross535e2cf2017-10-20 17:57:49 -07002064 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002065
Paul Duffin869de142021-07-15 14:14:41 +01002066 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002067 Permitted_packages []string
2068
Jiyong Park1be96912018-05-28 18:02:19 +09002069 // List of shared java libs that this module has dependencies to
2070 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002071
2072 // List of files to remove from the jar file(s)
2073 Exclude_files []string
2074
2075 // List of directories to remove from the jar file(s)
2076 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002077
2078 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002079 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002080
2081 // set the name of the output
2082 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002083
2084 Aidl struct {
2085 // directories that should be added as include directories for any aidl sources of modules
2086 // that depend on this module, as well as to aidl for this module.
2087 Export_include_dirs []string
2088 }
Colin Cross74d73e22017-08-02 11:05:49 -07002089}
2090
2091type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002092 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002093 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002094 android.ApexModuleBase
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002095 android.BazelModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002096 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002097
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002098 // Functionality common to Module and Import.
2099 embeddableInModuleAndImport
2100
Liz Kammerd6c31d22020-08-05 15:40:41 -07002101 hiddenAPI
2102 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002103 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002104
Colin Cross74d73e22017-08-02 11:05:49 -07002105 properties ImportProperties
2106
Liz Kammerd6c31d22020-08-05 15:40:41 -07002107 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002108 dexJarFile OptionalDexJarPath
Jeongik Chad5fe8782021-07-08 01:13:11 +09002109 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002110
Colin Cross0a6e0072017-08-30 14:24:55 -07002111 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002112 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09002113 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002114
2115 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002116
2117 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002118 minSdkVersion android.ApiLevel
Colin Cross2fe66872015-03-30 17:20:39 -07002119}
2120
Paul Duffin630b11e2021-07-15 13:35:26 +01002121var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2122
2123func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2124 return j.properties.Permitted_packages
2125}
2126
Jiyong Park92315372021-04-02 08:45:46 +09002127func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2128 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002129}
2130
Jiyong Parkf1691d22021-03-29 20:11:58 +09002131func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002132 return "none"
2133}
2134
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002135func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002136 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002137 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002138 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002139 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002140}
2141
Spandan Dasa26eda72023-03-02 00:56:06 +00002142func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002143 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002144 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002145 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002146 // Default is PrivateApiLevel
2147 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002148}
2149
Spandan Dasca70fc42023-03-01 23:38:49 +00002150func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2151 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002152}
2153
Colin Cross74d73e22017-08-02 11:05:49 -07002154func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002155 return &j.prebuilt
2156}
2157
Colin Cross74d73e22017-08-02 11:05:49 -07002158func (j *Import) PrebuiltSrcs() []string {
2159 return j.properties.Jars
2160}
2161
2162func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002163 return j.prebuilt.Name(j.ModuleBase.Name())
2164}
2165
Jiyong Park0b238752019-10-29 11:23:10 +09002166func (j *Import) Stem() string {
2167 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2168}
2169
Jiyong Park618922e2020-01-08 13:35:43 +09002170func (a *Import) JacocoReportClassesFile() android.Path {
2171 return nil
2172}
2173
Bill Peckhama41a6962021-01-11 10:58:54 -08002174func (j *Import) LintDepSets() LintDepSets {
2175 return LintDepSets{}
2176}
2177
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002178func (j *Import) getStrictUpdatabilityLinting() bool {
2179 return false
2180}
2181
2182func (j *Import) setStrictUpdatabilityLinting(bool) {
2183}
2184
Colin Cross74d73e22017-08-02 11:05:49 -07002185func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002186 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002187
2188 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002189 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002190 }
Colin Cross1e676be2016-10-12 14:38:15 -07002191}
2192
Sam Delmerico277795c2022-02-25 17:04:37 +00002193func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00002194 //TODO(b/231322772) these should come from Bazel once available
Jiyong Park92315372021-04-02 08:45:46 +09002195 j.sdkVersion = j.SdkVersion(ctx)
2196 j.minSdkVersion = j.MinSdkVersion(ctx)
2197
Colin Cross56a83212020-09-15 18:30:11 -07002198 if !ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).IsForPlatform() {
2199 j.hideApexVariantFromMake = true
2200 }
2201
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002202 if ctx.Windows() {
2203 j.HideFromMake()
2204 }
Sam Delmerico277795c2022-02-25 17:04:37 +00002205}
2206
2207func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2208 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002209
Colin Cross8a497952019-03-05 22:25:09 -08002210 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07002211
Jiyong Park0b238752019-10-29 11:23:10 +09002212 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07002213 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07002214 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
2215 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07002216 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07002217 inputFile := outputFile
2218 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
2219 TransformJetifier(ctx, outputFile, inputFile)
2220 }
Colin Crosse9a275b2017-10-16 17:09:48 -07002221 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002222 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01002223
Liz Kammerd6c31d22020-08-05 15:40:41 -07002224 var flags javaBuilderFlags
2225
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002226 j.collectTransitiveHeaderJars(ctx)
Jiyong Park1be96912018-05-28 18:02:19 +09002227 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09002228 tag := ctx.OtherModuleDependencyTag(module)
Colin Crossdcf71b22021-02-01 13:59:03 -08002229 if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2230 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Jiyong Park1be96912018-05-28 18:02:19 +09002231 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002232 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002233 flags.classpath = append(flags.classpath, dep.HeaderJars...)
2234 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
2235 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002236 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002237 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002238 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09002239 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002240 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002241 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002242 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09002243 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09002244 }
2245 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002246
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002247 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09002248 })
2249
Sam Delmerico277795c2022-02-25 17:04:37 +00002250 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09002251
2252 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002253
Paul Duffin064b70c2020-11-02 17:32:38 +00002254 if ctx.Device() {
2255 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
2256 // obtained from the associated deapexer module.
2257 ai := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
2258 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00002259 // Get the path of the dex implementation jar from the `deapexer` module.
Martin Stjernholm44825602021-09-17 01:44:12 +01002260 di := android.FindDeapexerProviderForModule(ctx)
2261 if di == nil {
2262 return // An error has been reported by FindDeapexerProviderForModule.
2263 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08002264 dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(j.BaseModuleName())
2265 if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002266 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
2267 j.dexJarFile = dexJarFile
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002268 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, apexRootRelativePathToJavaLib(j.BaseModuleName()))
2269 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01002270
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002271 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002272 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002273 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Jiakai Zhang81e46812023-02-08 21:56:07 +08002274
2275 if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
2276 j.dexpreopter.inputProfilePathOnHost = profilePath
2277 }
2278
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002279 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002280
2281 // Initialize the hiddenapi structure.
2282 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00002283 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00002284 // This should never happen as a variant for a prebuilt_apex is only created if the
2285 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01002286 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00002287 }
2288 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002289 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00002290 if sdkDep.invalidVersion {
2291 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2292 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2293 } else if sdkDep.useFiles {
2294 // sdkDep.jar is actually equivalent to turbine header.jar.
2295 flags.classpath = append(flags.classpath, sdkDep.jars...)
2296 }
2297
2298 // Dex compilation
2299
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002300 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2301 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00002302 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00002303 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
2304
Paul Duffin612e6102021-02-02 13:38:13 +00002305 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00002306 dexParams := &compileDexParams{
2307 flags: flags,
2308 sdkVersion: j.SdkVersion(ctx),
2309 minSdkVersion: j.MinSdkVersion(ctx),
2310 classesJar: outputFile,
2311 jarName: jarName,
2312 }
2313
2314 dexOutputFile = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00002315 if ctx.Failed() {
2316 return
2317 }
2318
Paul Duffin74d18d12021-05-14 14:18:47 +01002319 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002320 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01002321
2322 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01002323 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002324
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002325 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09002326 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002327 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002328 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002329
2330 ctx.SetProvider(JavaInfoProvider, JavaInfo{
2331 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002332 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
2333 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08002334 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
2335 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
2336 AidlIncludeDirs: j.exportAidlIncludeDirs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002337 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08002338 })
Colin Cross2fe66872015-03-30 17:20:39 -07002339}
2340
Sam Delmerico277795c2022-02-25 17:04:37 +00002341func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
2342 if !Bool(j.properties.Installable) {
2343 return
2344 }
2345
2346 var installDir android.InstallPath
2347 if ctx.InstallInTestcases() {
2348 var archDir string
2349 if !ctx.Host() {
2350 archDir = ctx.DeviceConfig().DeviceArch()
2351 }
2352 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
2353 } else {
2354 installDir = android.PathForModuleInstall(ctx, "framework")
2355 }
2356 ctx.InstallFile(installDir, jarName, outputFile)
2357}
2358
Paul Duffinaa55f742020-10-06 17:20:13 +01002359func (j *Import) OutputFiles(tag string) (android.Paths, error) {
2360 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00002361 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01002362 return android.Paths{j.combinedClasspathFile}, nil
2363 default:
2364 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
2365 }
2366}
2367
2368var _ android.OutputFileProducer = (*Import)(nil)
2369
Nan Zhanged19fc32017-10-19 13:06:22 -07002370func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002371 if j.combinedClasspathFile == nil {
2372 return nil
2373 }
Colin Cross37f6d792018-07-12 12:28:41 -07002374 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07002375}
2376
Colin Cross331a1212018-08-15 20:40:52 -07002377func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002378 if j.combinedClasspathFile == nil {
2379 return nil
2380 }
Colin Cross331a1212018-08-15 20:40:52 -07002381 return android.Paths{j.combinedClasspathFile}
2382}
2383
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002384func (j *Import) DexJarBuildPath() OptionalDexJarPath {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002385 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08002386}
2387
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002388func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09002389 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002390}
2391
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002392func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2393 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09002394}
2395
Jiyong Park45bf82e2020-12-15 22:29:02 +09002396var _ android.ApexModule = (*Import)(nil)
2397
2398// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09002399func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002400 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09002401}
2402
Jiyong Park45bf82e2020-12-15 22:29:02 +09002403// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002404func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2405 sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002406 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002407 minSdkVersion := j.MinSdkVersion(ctx)
2408 if !minSdkVersion.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002409 return fmt.Errorf("min_sdk_version is not specified")
2410 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002411 // If the module is compiling against core (via sdk_version), skip comparison check.
2412 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002413 return nil
2414 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002415 if minSdkVersion.GreaterThan(sdkVersion) {
2416 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002417 }
Jooyung Han749dc692020-04-15 11:03:39 +09002418 return nil
2419}
2420
Paul Duffinfef55002021-06-17 14:56:05 +01002421// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
2422// java_sdk_library_import with the specified base module name requires to be exported from a
2423// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002424func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
2425 dexJarFileApexRootRelative := apexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002426 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002427 files := []string{
2428 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01002429 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08002430 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
2431 files = append(files, dexJarFileApexRootRelative+".prof")
2432 }
2433 return files
Paul Duffinfef55002021-06-17 14:56:05 +01002434}
2435
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002436// apexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
2437// the java library with the specified name.
2438func apexRootRelativePathToJavaLib(name string) string {
2439 return filepath.Join("javalib", name+".jar")
2440}
2441
Paul Duffinfef55002021-06-17 14:56:05 +01002442var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
2443
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002444func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01002445 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08002446 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01002447}
2448
albaltai36ff7dc2018-12-25 14:35:23 +08002449// Add compile time check for interface implementation
2450var _ android.IDEInfo = (*Import)(nil)
2451var _ android.IDECustomizedModuleName = (*Import)(nil)
2452
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002453// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002454
2455func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
2456 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
2457}
2458
2459func (j *Import) IDECustomizedModuleName() string {
2460 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
2461 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
2462 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01002463 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002464}
2465
Colin Cross74d73e22017-08-02 11:05:49 -07002466var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07002467
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002468func (j *Import) IsInstallable() bool {
2469 return Bool(j.properties.Installable)
2470}
2471
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002472var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002473
Colin Cross1b16b0e2019-02-12 14:41:32 -08002474// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
2475//
2476// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
2477// compiled against an Android classpath.
2478//
2479// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
2480// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07002481func ImportFactory() android.Module {
2482 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07002483
Liz Kammerd6c31d22020-08-05 15:40:41 -07002484 module.AddProperties(
2485 &module.properties,
2486 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08002487 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07002488 )
Colin Cross74d73e22017-08-02 11:05:49 -07002489
Paul Duffin71b33cc2021-06-23 11:39:47 +01002490 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01002491
Liz Kammerd6c31d22020-08-05 15:40:41 -07002492 module.dexProperties.Optimize.EnabledByDefault = false
2493
Colin Cross74d73e22017-08-02 11:05:49 -07002494 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002495 android.InitApexModule(module)
Romain Jobredeaux428a3662022-01-28 11:12:52 -05002496 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002497 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07002498 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002499}
2500
Colin Cross1b16b0e2019-02-12 14:41:32 -08002501// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
2502// module.
2503//
2504// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
2505// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07002506func ImportFactoryHost() android.Module {
2507 module := &Import{}
2508
2509 module.AddProperties(&module.properties)
2510
2511 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002512 android.InitApexModule(module)
Sam Delmerico5f83b492022-02-28 18:50:56 +00002513 android.InitBazelModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002514 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07002515 return module
2516}
2517
Colin Cross42be7612019-02-21 18:12:14 -08002518// dex_import module
2519
2520type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07002521 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09002522
2523 // set the name of the output
2524 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08002525}
2526
2527type DexImport struct {
2528 android.ModuleBase
2529 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002530 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08002531 prebuilt android.Prebuilt
2532
2533 properties DexImportProperties
2534
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002535 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08002536
2537 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07002538
2539 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08002540}
2541
2542func (j *DexImport) Prebuilt() *android.Prebuilt {
2543 return &j.prebuilt
2544}
2545
2546func (j *DexImport) PrebuiltSrcs() []string {
2547 return j.properties.Jars
2548}
2549
2550func (j *DexImport) Name() string {
2551 return j.prebuilt.Name(j.ModuleBase.Name())
2552}
2553
Jiyong Park0b238752019-10-29 11:23:10 +09002554func (j *DexImport) Stem() string {
2555 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2556}
2557
Jiyong Park77acec62020-06-01 21:39:15 +09002558func (a *DexImport) JacocoReportClassesFile() android.Path {
2559 return nil
2560}
2561
Colin Cross08dca382020-07-21 20:31:17 -07002562func (a *DexImport) LintDepSets() LintDepSets {
2563 return LintDepSets{}
2564}
2565
Martin Stjernholm6d415272020-01-31 17:10:36 +00002566func (j *DexImport) IsInstallable() bool {
2567 return true
2568}
2569
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002570func (j *DexImport) getStrictUpdatabilityLinting() bool {
2571 return false
2572}
2573
2574func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2575}
2576
Colin Cross42be7612019-02-21 18:12:14 -08002577func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2578 if len(j.properties.Jars) != 1 {
2579 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2580 }
2581
Colin Cross56a83212020-09-15 18:30:11 -07002582 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
2583 if !apexInfo.IsForPlatform() {
2584 j.hideApexVariantFromMake = true
2585 }
2586
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002587 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2588 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08002589 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
2590
2591 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2592 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2593
2594 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002595 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002596
2597 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2598 rule.Temporary(temporary)
2599
2600 // use zip2zip to uncompress classes*.dex files
2601 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002602 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002603 FlagWithInput("-i ", inputJar).
2604 FlagWithOutput("-o ", temporary).
2605 FlagWithArg("-0 ", "'classes*.dex'")
2606
2607 // use zipalign to align uncompressed classes*.dex files
2608 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002609 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002610 Flag("-f").
2611 Text("4").
2612 Input(temporary).
2613 Output(dexOutputFile)
2614
2615 rule.DeleteTemporaryFiles()
2616
Colin Crossf1a035e2020-11-16 17:32:30 -08002617 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002618 } else {
2619 ctx.Build(pctx, android.BuildParams{
2620 Rule: android.Cp,
2621 Input: inputJar,
2622 Output: dexOutputFile,
2623 })
2624 }
2625
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002626 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002627
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002628 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002629
Colin Cross56a83212020-09-15 18:30:11 -07002630 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002631 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2632 j.Stem()+".jar", dexOutputFile)
2633 }
Colin Cross42be7612019-02-21 18:12:14 -08002634}
2635
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002636func (j *DexImport) DexJarBuildPath() OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002637 return j.dexJarFile
2638}
2639
Jiyong Park45bf82e2020-12-15 22:29:02 +09002640var _ android.ApexModule = (*DexImport)(nil)
2641
2642// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002643func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2644 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002645 // we don't check prebuilt modules for sdk_version
2646 return nil
2647}
2648
Colin Cross42be7612019-02-21 18:12:14 -08002649// dex_import imports a `.jar` file containing classes.dex files.
2650//
2651// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2652// to the device.
2653func DexImportFactory() android.Module {
2654 module := &DexImport{}
2655
2656 module.AddProperties(&module.properties)
2657
2658 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002659 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002660 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002661 return module
2662}
2663
Colin Cross89536d42017-07-07 14:35:50 -07002664// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002665type Defaults struct {
2666 android.ModuleBase
2667 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002668 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002669}
2670
Colin Cross1b16b0e2019-02-12 14:41:32 -08002671// java_defaults provides a set of properties that can be inherited by other java or android modules.
2672//
2673// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2674// property in the defaults module that exists in the depending module will be prepended to the depending module's
2675// value for that property.
2676//
2677// Example:
2678//
Sam Delmerico277795c2022-02-25 17:04:37 +00002679// java_defaults {
2680// name: "example_defaults",
2681// srcs: ["common/**/*.java"],
2682// javacflags: ["-Xlint:all"],
2683// aaptflags: ["--auto-add-overlay"],
2684// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002685//
Sam Delmerico277795c2022-02-25 17:04:37 +00002686// java_library {
2687// name: "example",
2688// defaults: ["example_defaults"],
2689// srcs: ["example/**/*.java"],
2690// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002691//
2692// is functionally identical to:
2693//
Sam Delmerico277795c2022-02-25 17:04:37 +00002694// java_library {
2695// name: "example",
2696// srcs: [
2697// "common/**/*.java",
2698// "example/**/*.java",
2699// ],
2700// javacflags: ["-Xlint:all"],
2701// }
Paul Duffin47357662019-12-05 14:07:14 +00002702func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002703 module := &Defaults{}
2704
Colin Cross89536d42017-07-07 14:35:50 -07002705 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002706 &CommonProperties{},
2707 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002708 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002709 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002710 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002711 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002712 &aaptProperties{},
2713 &androidLibraryProperties{},
2714 &appProperties{},
2715 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002716 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00002717 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002718 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002719 &ImportProperties{},
2720 &AARImportProperties{},
2721 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002722 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002723 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002724 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002725 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002726 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002727 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00002728 &JavaApiLibraryProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002729 )
2730
2731 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002732 return module
2733}
Nan Zhangea568a42017-11-08 21:20:04 -08002734
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002735func kytheExtractJavaFactory() android.Singleton {
2736 return &kytheExtractJavaSingleton{}
2737}
2738
2739type kytheExtractJavaSingleton struct {
2740}
2741
2742func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2743 var xrefTargets android.Paths
2744 ctx.VisitAllModules(func(module android.Module) {
2745 if javaModule, ok := module.(xref); ok {
2746 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2747 }
2748 })
2749 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2750 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002751 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002752 }
2753}
2754
Nan Zhangea568a42017-11-08 21:20:04 -08002755var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002756var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002757var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04002758var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002759
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002760// Add class loader context (CLC) of a given dependency to the current CLC.
2761func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2762 clcMap dexpreopt.ClassLoaderContextMap) {
2763
2764 dep, ok := depModule.(UsesLibraryDependency)
2765 if !ok {
2766 return
2767 }
2768
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002769 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2770
2771 var sdkLib *string
2772 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2773 // A shared SDK library. This should be added as a top-level CLC element.
2774 sdkLib = &depName
2775 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2776 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2777 // property. This should be handled in the same way as a shared SDK library.
2778 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002779 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002780
2781 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002782 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002783 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002784 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2785 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002786 } else if depTag == staticLibTag {
2787 // Propagate <uses-library> through static library dependencies, unless it is a component
2788 // library (such as stubs). Component libraries have a dependency on their SDK library,
2789 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002790 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002791 return
2792 }
2793 } else {
2794 // Don't propagate <uses-library> for other dependency tags.
2795 return
2796 }
2797
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002798 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2799 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2800 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2801 // from its CLC should be added to the current CLC.
2802 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002803 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002804 dep.DexJarBuildPath().PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002805 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002806 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2807 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002808}
Wei Libafb6d62021-12-10 03:14:59 -08002809
Sam Delmerico79985812022-03-23 20:20:42 +00002810type javaResourcesAttributes struct {
2811 Resources bazel.LabelListAttribute
2812 Resource_strip_prefix *string
Liz Kammer93b7e952023-10-09 14:07:46 -04002813 Additional_resources bazel.LabelListAttribute `blueprint:"mutated"`
Sam Delmerico79985812022-03-23 20:20:42 +00002814}
2815
Chris Parsons637458d2023-09-19 20:09:00 +00002816func (m *Library) getResourceFilegroupStripPrefix(ctx android.Bp2buildMutatorContext, resourceFilegroup string) (*string, bool) {
Alix289e9c62023-08-16 15:06:31 +00002817 if otherM, ok := ctx.ModuleFromName(resourceFilegroup); ok {
Alixb29a3cd2023-05-09 20:37:49 +00002818 if fg, isFilegroup := otherM.(android.FileGroupPath); isFilegroup {
Alix289e9c62023-08-16 15:06:31 +00002819 return proptools.StringPtr(filepath.Join(ctx.OtherModuleDir(otherM), fg.GetPath(ctx))), true
Alixb29a3cd2023-05-09 20:37:49 +00002820 }
2821 }
Alix289e9c62023-08-16 15:06:31 +00002822 return proptools.StringPtr(""), false
Alixb29a3cd2023-05-09 20:37:49 +00002823}
2824
Chris Parsons637458d2023-09-19 20:09:00 +00002825func (m *Library) convertJavaResourcesAttributes(ctx android.Bp2buildMutatorContext) *javaResourcesAttributes {
Sam Delmerico79985812022-03-23 20:20:42 +00002826 var resources bazel.LabelList
2827 var resourceStripPrefix *string
2828
Alix289e9c62023-08-16 15:06:31 +00002829 additionalJavaResourcesMap := make(map[string]*javaResourcesAttributes)
Romain Jobredeauxd5fe1332023-05-04 14:54:45 -04002830
Sam Delmerico79985812022-03-23 20:20:42 +00002831 if m.properties.Java_resources != nil {
Alix289e9c62023-08-16 15:06:31 +00002832 for _, res := range m.properties.Java_resources {
2833 if prefix, isFilegroup := m.getResourceFilegroupStripPrefix(ctx, res); isFilegroup {
2834 otherM, _ := ctx.ModuleFromName(res)
2835 resourcesTargetName := ctx.ModuleName() + "_filegroup_resources_" + otherM.Name()
2836 additionalJavaResourcesMap[resourcesTargetName] = &javaResourcesAttributes{
2837 Resources: bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, []string{res})),
2838 Resource_strip_prefix: prefix,
2839 }
2840 } else {
2841 resources.Append(android.BazelLabelForModuleSrc(ctx, []string{res}))
2842 }
2843 }
2844
2845 if !resources.IsEmpty() {
Alixb29a3cd2023-05-09 20:37:49 +00002846 resourceStripPrefix = proptools.StringPtr(ctx.ModuleDir())
2847 }
Sam Delmerico79985812022-03-23 20:20:42 +00002848 }
2849
Paul Duffin7ed6ff82022-11-21 10:57:30 +00002850 //TODO(b/179889880) handle case where glob includes files outside package
Sam Delmerico79985812022-03-23 20:20:42 +00002851 resDeps := ResourceDirsToFiles(
2852 ctx,
2853 m.properties.Java_resource_dirs,
2854 m.properties.Exclude_java_resource_dirs,
2855 m.properties.Exclude_java_resources,
2856 )
2857
Alix289e9c62023-08-16 15:06:31 +00002858 for _, resDep := range resDeps {
Sam Delmerico79985812022-03-23 20:20:42 +00002859 dir, files := resDep.dir, resDep.files
2860
Sam Delmerico79985812022-03-23 20:20:42 +00002861 // Bazel includes the relative path from the WORKSPACE root when placing the resource
2862 // inside the JAR file, so we need to remove that prefix
Alix289e9c62023-08-16 15:06:31 +00002863 prefix := proptools.StringPtr(dir.String())
2864 resourcesTargetName := ctx.ModuleName() + "_resource_dir_" + dir.String()
2865 additionalJavaResourcesMap[resourcesTargetName] = &javaResourcesAttributes{
2866 Resources: bazel.MakeLabelListAttribute(bazel.MakeLabelList(android.RootToModuleRelativePaths(ctx, files))),
2867 Resource_strip_prefix: prefix,
Sam Delmerico79985812022-03-23 20:20:42 +00002868 }
2869 }
2870
Alix289e9c62023-08-16 15:06:31 +00002871 var additionalResourceLabels bazel.LabelList
2872 if len(additionalJavaResourcesMap) > 0 {
2873 var additionalResources []string
2874 for resName, _ := range additionalJavaResourcesMap {
2875 additionalResources = append(additionalResources, resName)
2876 }
2877 sort.Strings(additionalResources)
2878
2879 for i, resName := range additionalResources {
2880 resAttr := additionalJavaResourcesMap[resName]
2881 if resourceStripPrefix == nil && i == 0 {
2882 resourceStripPrefix = resAttr.Resource_strip_prefix
2883 resources = resAttr.Resources.Value
Liz Kammer33dddf52023-09-07 14:54:41 -04002884 } else if !resAttr.Resources.IsEmpty() {
Alix289e9c62023-08-16 15:06:31 +00002885 ctx.CreateBazelTargetModule(
2886 bazel.BazelTargetModuleProperties{
2887 Rule_class: "java_resources",
2888 Bzl_load_location: "//build/bazel/rules/java:java_resources.bzl",
2889 },
2890 android.CommonAttributes{Name: resName},
2891 resAttr,
2892 )
2893 additionalResourceLabels.Append(android.BazelLabelForModuleSrc(ctx, []string{resName}))
2894 }
2895 }
2896
2897 }
2898
Sam Delmerico79985812022-03-23 20:20:42 +00002899 return &javaResourcesAttributes{
2900 Resources: bazel.MakeLabelListAttribute(resources),
2901 Resource_strip_prefix: resourceStripPrefix,
Alix289e9c62023-08-16 15:06:31 +00002902 Additional_resources: bazel.MakeLabelListAttribute(additionalResourceLabels),
Sam Delmerico79985812022-03-23 20:20:42 +00002903 }
2904}
2905
Sam Delmericoc0161432022-02-25 21:34:51 +00002906type javaCommonAttributes struct {
Sam Delmerico79985812022-03-23 20:20:42 +00002907 *javaResourcesAttributes
Alix75db7842023-03-06 22:08:49 +00002908 *kotlinAttributes
Alixb1e5c6a2023-06-20 21:00:40 +00002909 Srcs bazel.LabelListAttribute
2910 Plugins bazel.LabelListAttribute
2911 Javacopts bazel.StringListAttribute
2912 Sdk_version bazel.StringAttribute
2913 Java_version bazel.StringAttribute
2914 Errorprone_force_enable bazel.BoolAttribute
usta15ab5502023-09-26 18:25:57 -04002915 Javac_shard_size *int64
Wei Libafb6d62021-12-10 03:14:59 -08002916}
2917
Sam Delmericoc0161432022-02-25 21:34:51 +00002918type javaDependencyLabels struct {
2919 // Dependencies which DO NOT contribute to the API visible to upstream dependencies.
2920 Deps bazel.LabelListAttribute
2921 // Dependencies which DO contribute to the API visible to upstream dependencies.
2922 StaticDeps bazel.LabelListAttribute
2923}
2924
Sam Delmerico24da73c2022-03-16 20:36:54 +00002925type eventLogTagsAttributes struct {
2926 Srcs bazel.LabelListAttribute
2927}
2928
Sam Delmerico97bd1272022-08-25 14:45:31 -04002929type aidlLibraryAttributes struct {
2930 Srcs bazel.LabelListAttribute
Liz Kammer2b3f56e2023-03-23 11:51:49 -04002931 Tags bazel.StringListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002932}
2933
2934type javaAidlLibraryAttributes struct {
2935 Deps bazel.LabelListAttribute
Liz Kammer2b3f56e2023-03-23 11:51:49 -04002936 Tags bazel.StringListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002937}
2938
Alix8062f4d2022-11-14 21:38:07 +00002939// bp2BuildJavaInfo has information needed for the conversion of java*_modules
2940// that is needed bor Bp2Build conversion but that requires different handling
2941// depending on the module type.
2942type bp2BuildJavaInfo struct {
2943 // separates dependencies into dynamic dependencies and static dependencies.
Zi Wangdd936362023-09-15 09:46:17 -07002944 DepLabels *javaDependencyLabels
2945 hasKotlin bool
Alix8062f4d2022-11-14 21:38:07 +00002946}
2947
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002948func javaXsdTargetName(xsd android.XsdConfigBp2buildTargets) string {
2949 return xsd.JavaBp2buildTargetName()
Spandan Das370f13c2023-05-31 22:03:33 +00002950}
2951
Alix8062f4d2022-11-14 21:38:07 +00002952// convertLibraryAttrsBp2Build returns a javaCommonAttributes struct with
2953// converted attributes shared across java_* modules and a bp2BuildJavaInfo struct
2954// which has other non-attribute information needed for bp2build conversion
2955// that needs different handling depending on the module types, and thus needs
2956// to be returned to the calling function.
Chris Parsons637458d2023-09-19 20:09:00 +00002957func (m *Library) convertLibraryAttrsBp2Build(ctx android.Bp2buildMutatorContext) (*javaCommonAttributes, *bp2BuildJavaInfo, bool) {
Sam Delmericoe91d0302022-02-23 15:28:33 +00002958 var srcs bazel.LabelListAttribute
Alix495cc8a2023-01-12 18:20:32 +00002959 var deps bazel.LabelListAttribute
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002960 var staticDeps bazel.LabelListAttribute
Sam Delmerico97bd1272022-08-25 14:45:31 -04002961
Liz Kammer02914402023-08-07 13:38:18 -04002962 if proptools.String(m.deviceProperties.Sdk_version) == "" && m.DeviceSupported() {
Liz Kammer65942c82023-09-07 15:59:42 -04002963 // TODO(b/297356704): handle platform apis in bp2build
Liz Kammer02914402023-08-07 13:38:18 -04002964 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "sdk_version unset")
2965 return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false
Liz Kammer65942c82023-09-07 15:59:42 -04002966 } else if proptools.String(m.deviceProperties.Sdk_version) == "core_platform" {
2967 // TODO(b/297356582): handle core_platform in bp2build
2968 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "sdk_version core_platform")
2969 return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false
Liz Kammer02914402023-08-07 13:38:18 -04002970 }
2971
Sam Delmericoe91d0302022-02-23 15:28:33 +00002972 archVariantProps := m.GetArchVariantProperties(ctx, &CommonProperties{})
2973 for axis, configToProps := range archVariantProps {
Liz Kammer9f52f6b2023-10-06 16:47:00 -04002974 for config, p := range configToProps {
2975 if archProps, ok := p.(*CommonProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002976 archSrcs := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Srcs, archProps.Exclude_srcs)
Sam Delmericoe91d0302022-02-23 15:28:33 +00002977 srcs.SetSelectValue(axis, config, archSrcs)
Liz Kammer7f375862023-08-04 16:37:42 -04002978 if archProps.Jarjar_rules != nil {
2979 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_PROPERTY_UNSUPPORTED, "jarjar_rules")
2980 return &javaCommonAttributes{}, &bp2BuildJavaInfo{}, false
2981 }
Sam Delmericoe91d0302022-02-23 15:28:33 +00002982 }
2983 }
2984 }
Liz Kammer9f52f6b2023-10-06 16:47:00 -04002985 srcs.Append(
2986 bazel.MakeLabelListAttribute(
2987 android.BazelLabelForModuleSrcExcludes(ctx,
2988 m.properties.Openjdk9.Srcs,
2989 m.properties.Exclude_srcs)))
Romain Jobredeaux3eaf7472023-03-08 16:34:17 -05002990 srcs.ResolveExcludes()
Sam Delmericoc7681022022-02-04 21:01:20 +00002991
2992 javaSrcPartition := "java"
2993 protoSrcPartition := "proto"
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04002994 xsdSrcPartition := "xsd"
Sam Delmerico24da73c2022-03-16 20:36:54 +00002995 logtagSrcPartition := "logtag"
Sam Delmerico97bd1272022-08-25 14:45:31 -04002996 aidlSrcPartition := "aidl"
Alix8062f4d2022-11-14 21:38:07 +00002997 kotlinPartition := "kotlin"
Sam Delmericoc7681022022-02-04 21:01:20 +00002998 srcPartitions := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Sam Delmerico24da73c2022-03-16 20:36:54 +00002999 javaSrcPartition: bazel.LabelPartition{Extensions: []string{".java"}, Keep_remainder: true},
3000 logtagSrcPartition: bazel.LabelPartition{Extensions: []string{".logtags", ".logtag"}},
3001 protoSrcPartition: android.ProtoSrcLabelPartition,
Sam Delmerico97bd1272022-08-25 14:45:31 -04003002 aidlSrcPartition: android.AidlSrcLabelPartition,
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04003003 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(javaXsdTargetName)},
Alix8062f4d2022-11-14 21:38:07 +00003004 kotlinPartition: bazel.LabelPartition{Extensions: []string{".kt"}},
Sam Delmericoc7681022022-02-04 21:01:20 +00003005 })
3006
Sam Delmerico24da73c2022-03-16 20:36:54 +00003007 javaSrcs := srcPartitions[javaSrcPartition]
Alix8062f4d2022-11-14 21:38:07 +00003008 kotlinSrcs := srcPartitions[kotlinPartition]
3009 javaSrcs.Append(kotlinSrcs)
Sam Delmerico24da73c2022-03-16 20:36:54 +00003010
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04003011 staticDeps.Append(srcPartitions[xsdSrcPartition])
3012
Sam Delmerico24da73c2022-03-16 20:36:54 +00003013 if !srcPartitions[logtagSrcPartition].IsEmpty() {
3014 logtagsLibName := m.Name() + "_logtags"
Sam Delmerico24da73c2022-03-16 20:36:54 +00003015 ctx.CreateBazelTargetModule(
3016 bazel.BazelTargetModuleProperties{
3017 Rule_class: "event_log_tags",
Sam Delmerico48af73b2022-04-05 14:03:11 +00003018 Bzl_load_location: "//build/bazel/rules/java:event_log_tags.bzl",
Sam Delmerico24da73c2022-03-16 20:36:54 +00003019 },
3020 android.CommonAttributes{Name: logtagsLibName},
3021 &eventLogTagsAttributes{
3022 Srcs: srcPartitions[logtagSrcPartition],
3023 },
3024 )
Sam Delmerico97bd1272022-08-25 14:45:31 -04003025
3026 logtagsSrcs := bazel.MakeLabelList([]bazel.Label{{Label: ":" + logtagsLibName}})
3027 javaSrcs.Append(bazel.MakeLabelListAttribute(logtagsSrcs))
Sam Delmerico24da73c2022-03-16 20:36:54 +00003028 }
Sam Delmerico97bd1272022-08-25 14:45:31 -04003029
3030 if !srcPartitions[aidlSrcPartition].IsEmpty() {
3031 aidlLibs, aidlSrcs := srcPartitions[aidlSrcPartition].Partition(func(src bazel.Label) bool {
3032 return android.IsConvertedToAidlLibrary(ctx, src.OriginalModuleName)
3033 })
3034
Spandan Das39b6cc52023-04-12 19:05:49 +00003035 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx, ctx.Module())
Liz Kammer2b3f56e2023-03-23 11:51:49 -04003036
Sam Delmerico97bd1272022-08-25 14:45:31 -04003037 if !aidlSrcs.IsEmpty() {
3038 aidlLibName := m.Name() + "_aidl_library"
3039 ctx.CreateBazelTargetModule(
3040 bazel.BazelTargetModuleProperties{
3041 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04003042 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Sam Delmerico97bd1272022-08-25 14:45:31 -04003043 },
3044 android.CommonAttributes{Name: aidlLibName},
3045 &aidlLibraryAttributes{
3046 Srcs: aidlSrcs,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04003047 Tags: apexAvailableTags,
Sam Delmerico97bd1272022-08-25 14:45:31 -04003048 },
3049 )
3050 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
3051 }
3052
3053 javaAidlLibName := m.Name() + "_java_aidl_library"
3054 ctx.CreateBazelTargetModule(
3055 bazel.BazelTargetModuleProperties{
3056 Rule_class: "java_aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04003057 Bzl_load_location: "//build/bazel/rules/java:java_aidl_library.bzl",
Sam Delmerico97bd1272022-08-25 14:45:31 -04003058 },
3059 android.CommonAttributes{Name: javaAidlLibName},
3060 &javaAidlLibraryAttributes{
3061 Deps: aidlLibs,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04003062 Tags: apexAvailableTags,
Sam Delmerico97bd1272022-08-25 14:45:31 -04003063 },
3064 )
3065
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04003066 staticDeps.Append(bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + javaAidlLibName}))
Sam Delmerico97bd1272022-08-25 14:45:31 -04003067 }
Sam Delmerico24da73c2022-03-16 20:36:54 +00003068
Alixb1e5c6a2023-06-20 21:00:40 +00003069 var javacopts bazel.StringListAttribute //[]string
3070 plugins := bazel.MakeLabelListAttribute(
3071 android.BazelLabelForModuleDeps(ctx, m.properties.Plugins),
3072 )
Liz Kammer9f52f6b2023-10-06 16:47:00 -04003073 if m.properties.Javacflags != nil || m.properties.Openjdk9.Javacflags != nil {
3074 javacopts = bazel.MakeStringListAttribute(
3075 append(append([]string{}, m.properties.Javacflags...), m.properties.Openjdk9.Javacflags...))
Sam Delmerico58614c02022-03-15 21:02:09 +00003076 }
Vinh Tran3ac6daf2022-04-22 19:09:58 -04003077
Sam Delmerico58614c02022-03-15 21:02:09 +00003078 epEnabled := m.properties.Errorprone.Enabled
Alixb1e5c6a2023-06-20 21:00:40 +00003079 epJavacflags := m.properties.Errorprone.Javacflags
3080 var errorproneForceEnable bazel.BoolAttribute
3081 if epEnabled == nil {
3082 //TODO(b/227504307) add configuration that depends on RUN_ERROR_PRONE environment variable
3083 } else if *epEnabled {
3084 plugins.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.properties.Errorprone.Extra_check_modules)))
3085 javacopts.Append(bazel.MakeStringListAttribute(epJavacflags))
3086 errorproneForceEnable.Value = epEnabled
3087 } else {
3088 javacopts.Append(bazel.MakeStringListAttribute([]string{"-XepDisableAllChecks"}))
Sam Delmerico58614c02022-03-15 21:02:09 +00003089 }
3090
Liz Kammer93b7e952023-10-09 14:07:46 -04003091 resourcesAttrs := m.convertJavaResourcesAttributes(ctx)
3092
Sam Delmericoc0161432022-02-25 21:34:51 +00003093 commonAttrs := &javaCommonAttributes{
Sam Delmerico79985812022-03-23 20:20:42 +00003094 Srcs: javaSrcs,
Liz Kammer93b7e952023-10-09 14:07:46 -04003095 javaResourcesAttributes: resourcesAttrs,
Alixb1e5c6a2023-06-20 21:00:40 +00003096 Plugins: plugins,
3097 Javacopts: javacopts,
3098 Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
3099 Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
3100 Errorprone_force_enable: errorproneForceEnable,
usta15ab5502023-09-26 18:25:57 -04003101 Javac_shard_size: m.properties.Javac_shard_size,
Wei Libafb6d62021-12-10 03:14:59 -08003102 }
3103
Alix495cc8a2023-01-12 18:20:32 +00003104 for axis, configToProps := range archVariantProps {
3105 for config, _props := range configToProps {
3106 if archProps, ok := _props.(*CommonProperties); ok {
3107 var libLabels []bazel.Label
3108 for _, d := range archProps.Libs {
3109 neverlinkLabel := android.BazelLabelForModuleDepSingle(ctx, d)
3110 neverlinkLabel.Label = neverlinkLabel.Label + "-neverlink"
3111 libLabels = append(libLabels, neverlinkLabel)
3112 }
3113 deps.SetSelectValue(axis, config, bazel.MakeLabelList(libLabels))
3114 }
Alixb4e09a02022-09-27 15:36:01 +00003115 }
Wei Libafb6d62021-12-10 03:14:59 -08003116 }
Sam Delmericoc0161432022-02-25 21:34:51 +00003117
Sam Delmerico97bd1272022-08-25 14:45:31 -04003118 depLabels := &javaDependencyLabels{}
Liz Kammer93b7e952023-10-09 14:07:46 -04003119 deps.Append(resourcesAttrs.Additional_resources)
Alix495cc8a2023-01-12 18:20:32 +00003120 depLabels.Deps = deps
Romain Jobredeauxeb711b92023-04-03 22:53:34 -04003121
3122 for axis, configToProps := range archVariantProps {
3123 for config, _props := range configToProps {
3124 if archProps, ok := _props.(*CommonProperties); ok {
3125 archStaticLibs := android.BazelLabelForModuleDeps(
3126 ctx,
3127 android.LastUniqueStrings(android.CopyOf(archProps.Static_libs)))
3128 depLabels.StaticDeps.SetSelectValue(axis, config, archStaticLibs)
3129 }
3130 }
3131 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04003132 depLabels.StaticDeps.Append(staticDeps)
Sam Delmericofde9fb52022-01-28 20:53:38 +00003133
Zi Wang4dbd0e82023-09-21 16:00:45 -07003134 var additionalProtoDeps bazel.LabelListAttribute
3135 additionalProtoDeps.Append(depLabels.Deps)
3136 additionalProtoDeps.Append(depLabels.StaticDeps)
3137 protoDepLabel := bp2buildProto(ctx, &m.Module, srcPartitions[protoSrcPartition], additionalProtoDeps)
3138 // Soong does not differentiate between a java_library and the Bazel equivalent of
3139 // a java_proto_library + proto_library pair. Instead, in Soong proto sources are
3140 // listed directly in the srcs of a java_library, and the classes produced
3141 // by protoc are included directly in the resulting JAR. Thus upstream dependencies
3142 // that depend on a java_library with proto sources can link directly to the protobuf API,
3143 // and so this should be a static dependency.
3144 if protoDepLabel != nil {
3145 depLabels.StaticDeps.Append(bazel.MakeSingleLabelListAttribute(*protoDepLabel))
3146 }
3147
Alix75db7842023-03-06 22:08:49 +00003148 hasKotlin := !kotlinSrcs.IsEmpty()
Alixf848bf82023-03-06 19:43:55 +00003149 commonAttrs.kotlinAttributes = &kotlinAttributes{
3150 Kotlincflags: &m.properties.Kotlincflags,
3151 }
Alix75db7842023-03-06 22:08:49 +00003152 if len(m.properties.Common_srcs) != 0 {
3153 hasKotlin = true
Alixf848bf82023-03-06 19:43:55 +00003154 commonAttrs.kotlinAttributes.Common_srcs = bazel.MakeLabelListAttribute(android.BazelLabelForModuleSrc(ctx, m.properties.Common_srcs))
Alix75db7842023-03-06 22:08:49 +00003155 }
3156
Alix8062f4d2022-11-14 21:38:07 +00003157 bp2BuildInfo := &bp2BuildJavaInfo{
Zi Wangdd936362023-09-15 09:46:17 -07003158 DepLabels: depLabels,
3159 hasKotlin: hasKotlin,
Alix8062f4d2022-11-14 21:38:07 +00003160 }
3161
Liz Kammer7f375862023-08-04 16:37:42 -04003162 return commonAttrs, bp2BuildInfo, true
Sam Delmericoc0161432022-02-25 21:34:51 +00003163}
3164
3165type javaLibraryAttributes struct {
3166 *javaCommonAttributes
Alix7c8eaeb2022-11-16 15:44:55 +00003167 Deps bazel.LabelListAttribute
3168 Exports bazel.LabelListAttribute
3169 Neverlink bazel.BoolAttribute
Sam Delmericofde9fb52022-01-28 20:53:38 +00003170}
3171
Alix75db7842023-03-06 22:08:49 +00003172type kotlinAttributes struct {
Alixf848bf82023-03-06 19:43:55 +00003173 Common_srcs bazel.LabelListAttribute
3174 Kotlincflags *[]string
Alix75db7842023-03-06 22:08:49 +00003175}
3176
Alix32540022023-03-16 21:06:13 +00003177func ktJvmLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
3178 return bazel.BazelTargetModuleProperties{
3179 Rule_class: "kt_jvm_library",
Alixa28acb52023-05-08 15:41:01 +00003180 Bzl_load_location: "//build/bazel/rules/kotlin:kt_jvm_library.bzl",
Alix32540022023-03-16 21:06:13 +00003181 }
3182}
3183
3184func javaLibraryBazelTargetModuleProperties() bazel.BazelTargetModuleProperties {
3185 return bazel.BazelTargetModuleProperties{
3186 Rule_class: "java_library",
Alix83a8bc42023-05-04 18:03:23 +00003187 Bzl_load_location: "//build/bazel/rules/java:library.bzl",
Alix32540022023-03-16 21:06:13 +00003188 }
3189}
3190
Chris Parsons637458d2023-09-19 20:09:00 +00003191func javaLibraryBp2Build(ctx android.Bp2buildMutatorContext, m *Library) {
Liz Kammer7f375862023-08-04 16:37:42 -04003192 commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx)
3193 if !supported {
3194 return
3195 }
Alix8062f4d2022-11-14 21:38:07 +00003196 depLabels := bp2BuildInfo.DepLabels
Sam Delmericoc0161432022-02-25 21:34:51 +00003197
3198 deps := depLabels.Deps
Zi Wang774c6ea2023-09-12 10:24:35 -07003199 exports := depLabels.StaticDeps
Sam Delmericoc0161432022-02-25 21:34:51 +00003200 if !commonAttrs.Srcs.IsEmpty() {
Zi Wang774c6ea2023-09-12 10:24:35 -07003201 deps.Append(exports) // we should only append these if there are sources to use them
Sam Delmerico97bd1272022-08-25 14:45:31 -04003202 } else if !deps.IsEmpty() {
Zi Wangdd936362023-09-15 09:46:17 -07003203 // java_library does not accept deps when there are no srcs because
3204 // there is no compilation happening, but it accepts exports.
3205 // The non-empty deps here are unnecessary as deps on the java_library
3206 // since they aren't being propagated to any dependencies.
3207 // So we can drop deps here.
3208 deps = bazel.LabelListAttribute{}
Sam Delmericoc0161432022-02-25 21:34:51 +00003209 }
Alix8062f4d2022-11-14 21:38:07 +00003210 var props bazel.BazelTargetModuleProperties
Sam Delmericoc0161432022-02-25 21:34:51 +00003211 attrs := &javaLibraryAttributes{
3212 javaCommonAttributes: commonAttrs,
3213 Deps: deps,
Zi Wang774c6ea2023-09-12 10:24:35 -07003214 Exports: exports,
Sam Delmericoc0161432022-02-25 21:34:51 +00003215 }
Alix341484b2022-10-31 19:08:18 +00003216 name := m.Name()
Wei Libafb6d62021-12-10 03:14:59 -08003217
Alix75db7842023-03-06 22:08:49 +00003218 if !bp2BuildInfo.hasKotlin {
Alix32540022023-03-16 21:06:13 +00003219 props = javaLibraryBazelTargetModuleProperties()
Alix8062f4d2022-11-14 21:38:07 +00003220 } else {
Alix32540022023-03-16 21:06:13 +00003221 props = ktJvmLibraryBazelTargetModuleProperties()
Wei Libafb6d62021-12-10 03:14:59 -08003222 }
3223
Alix266bbf22022-12-15 06:12:46 +00003224 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
3225 neverlinkProp := true
3226 neverLinkAttrs := &javaLibraryAttributes{
3227 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
3228 Neverlink: bazel.BoolAttribute{Value: &neverlinkProp},
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -05003229 javaCommonAttributes: &javaCommonAttributes{
3230 Sdk_version: bazel.StringAttribute{Value: m.deviceProperties.Sdk_version},
3231 Java_version: bazel.StringAttribute{Value: m.properties.Java_version},
3232 },
Alix266bbf22022-12-15 06:12:46 +00003233 }
3234 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name + "-neverlink"}, neverLinkAttrs)
3235
Wei Libafb6d62021-12-10 03:14:59 -08003236}
3237
3238type javaBinaryHostAttributes struct {
Sam Delmericoc0161432022-02-25 21:34:51 +00003239 *javaCommonAttributes
3240 Deps bazel.LabelListAttribute
3241 Runtime_deps bazel.LabelListAttribute
3242 Main_class string
3243 Jvm_flags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08003244}
3245
3246// JavaBinaryHostBp2Build is for java_binary_host bp2build.
Chris Parsons637458d2023-09-19 20:09:00 +00003247func javaBinaryHostBp2Build(ctx android.Bp2buildMutatorContext, m *Binary) {
Liz Kammer7f375862023-08-04 16:37:42 -04003248 commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx)
3249 if !supported {
3250 return
3251 }
Alix8062f4d2022-11-14 21:38:07 +00003252 depLabels := bp2BuildInfo.DepLabels
Sam Delmericoc0161432022-02-25 21:34:51 +00003253
3254 deps := depLabels.Deps
3255 deps.Append(depLabels.StaticDeps)
3256 if m.binaryProperties.Jni_libs != nil {
3257 deps.Append(bazel.MakeLabelListAttribute(android.BazelLabelForModuleDeps(ctx, m.binaryProperties.Jni_libs)))
3258 }
3259
3260 var runtimeDeps bazel.LabelListAttribute
3261 if commonAttrs.Srcs.IsEmpty() {
3262 // if there are no sources, then the dependencies can only be used at runtime
3263 runtimeDeps = deps
3264 deps = bazel.LabelListAttribute{}
3265 }
3266
Wei Libafb6d62021-12-10 03:14:59 -08003267 mainClass := ""
3268 if m.binaryProperties.Main_class != nil {
3269 mainClass = *m.binaryProperties.Main_class
3270 }
3271 if m.properties.Manifest != nil {
3272 mainClassInManifest, err := android.GetMainClassInManifest(ctx.Config(), android.PathForModuleSrc(ctx, *m.properties.Manifest).String())
3273 if err != nil {
3274 return
3275 }
3276 mainClass = mainClassInManifest
3277 }
Sam Delmericoc0161432022-02-25 21:34:51 +00003278
Wei Libafb6d62021-12-10 03:14:59 -08003279 // Attribute jvm_flags
Alix7c8eaeb2022-11-16 15:44:55 +00003280 var jvmFlags bazel.StringListAttribute
Wei Libafb6d62021-12-10 03:14:59 -08003281 if m.binaryProperties.Jni_libs != nil {
Spandan Das5dba0ec2023-06-01 02:48:09 +00003282 jniLibPackages := []string{}
3283 for _, jniLib := range m.binaryProperties.Jni_libs {
3284 if jniLibModule, exists := ctx.ModuleFromName(jniLib); exists {
3285 otherDir := ctx.OtherModuleDir(jniLibModule)
3286 jniLibPackages = append(jniLibPackages, filepath.Join(otherDir, jniLib))
Wei Libafb6d62021-12-10 03:14:59 -08003287 }
3288 }
3289 jniLibPaths := []string{}
Spandan Das5dba0ec2023-06-01 02:48:09 +00003290 for _, jniLibPackage := range jniLibPackages {
Wei Libafb6d62021-12-10 03:14:59 -08003291 // See cs/f:.*/third_party/bazel/.*java_stub_template.txt for the use of RUNPATH
3292 jniLibPaths = append(jniLibPaths, "$${RUNPATH}"+jniLibPackage)
3293 }
Alix7c8eaeb2022-11-16 15:44:55 +00003294 jvmFlags = bazel.MakeStringListAttribute([]string{"-Djava.library.path=" + strings.Join(jniLibPaths, ":")})
Wei Libafb6d62021-12-10 03:14:59 -08003295 }
3296
3297 props := bazel.BazelTargetModuleProperties{
Alix82acaf52023-03-09 20:43:10 +00003298 Rule_class: "java_binary",
Alix83a8bc42023-05-04 18:03:23 +00003299 Bzl_load_location: "@rules_java//java:defs.bzl",
Wei Libafb6d62021-12-10 03:14:59 -08003300 }
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003301 binAttrs := &javaBinaryHostAttributes{
Alix7c8eaeb2022-11-16 15:44:55 +00003302 Runtime_deps: runtimeDeps,
3303 Main_class: mainClass,
3304 Jvm_flags: jvmFlags,
3305 }
3306
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003307 if commonAttrs.Srcs.IsEmpty() {
3308 binAttrs.javaCommonAttributes = commonAttrs
3309 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
3310 return
3311 }
3312
Zi Wang65b36722023-05-23 15:18:33 -07003313 libInfo := libraryCreationInfo{
Spandan Das5dba0ec2023-06-01 02:48:09 +00003314 deps: deps,
3315 attrs: commonAttrs,
3316 baseName: m.Name(),
Zi Wang65b36722023-05-23 15:18:33 -07003317 hasKotlin: bp2BuildInfo.hasKotlin,
3318 }
3319 libName := createLibraryTarget(ctx, libInfo)
3320 binAttrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
3321
3322 // Create the BazelTargetModule.
3323 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, binAttrs)
3324}
3325
3326type javaTestHostAttributes struct {
3327 *javaCommonAttributes
Zi Wang7873f612023-07-17 16:36:19 -07003328 Srcs bazel.LabelListAttribute
Zi Wang65b36722023-05-23 15:18:33 -07003329 Deps bazel.LabelListAttribute
3330 Runtime_deps bazel.LabelListAttribute
3331}
3332
3333// javaTestHostBp2Build is for java_test_host bp2build.
Chris Parsons637458d2023-09-19 20:09:00 +00003334func javaTestHostBp2Build(ctx android.Bp2buildMutatorContext, m *TestHost) {
Liz Kammer7f375862023-08-04 16:37:42 -04003335 commonAttrs, bp2BuildInfo, supported := m.convertLibraryAttrsBp2Build(ctx)
3336 if !supported {
3337 return
3338 }
Zi Wang65b36722023-05-23 15:18:33 -07003339 depLabels := bp2BuildInfo.DepLabels
3340
3341 deps := depLabels.Deps
3342 deps.Append(depLabels.StaticDeps)
3343
3344 var runtimeDeps bazel.LabelListAttribute
3345 attrs := &javaTestHostAttributes{
3346 Runtime_deps: runtimeDeps,
3347 }
3348 props := bazel.BazelTargetModuleProperties{
3349 Rule_class: "java_test",
3350 Bzl_load_location: "//build/bazel/rules/java:test.bzl",
3351 }
3352
3353 if commonAttrs.Srcs.IsEmpty() {
3354 // if there are no sources, then the dependencies can only be used at runtime
3355 attrs.Runtime_deps = deps
3356 attrs.javaCommonAttributes = commonAttrs
3357 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
3358 return
3359 }
3360
3361 libInfo := libraryCreationInfo{
Spandan Das5dba0ec2023-06-01 02:48:09 +00003362 deps: deps,
3363 attrs: commonAttrs,
3364 baseName: m.Name(),
Zi Wang65b36722023-05-23 15:18:33 -07003365 hasKotlin: bp2BuildInfo.hasKotlin,
3366 }
3367 libName := createLibraryTarget(ctx, libInfo)
Zi Wang65b36722023-05-23 15:18:33 -07003368
Zi Wang7873f612023-07-17 16:36:19 -07003369 attrs.Srcs = commonAttrs.Srcs
3370 attrs.Deps = deps
3371 attrs.Runtime_deps.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + libName}})
Zi Wang65b36722023-05-23 15:18:33 -07003372 // Create the BazelTargetModule.
3373 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
3374}
3375
3376// libraryCreationInfo encapsulates the info needed to create java_library target from
3377// java_binary_host or java_test_host.
3378type libraryCreationInfo struct {
Spandan Das5dba0ec2023-06-01 02:48:09 +00003379 deps bazel.LabelListAttribute
3380 attrs *javaCommonAttributes
3381 baseName string
Zi Wang65b36722023-05-23 15:18:33 -07003382 hasKotlin bool
3383}
3384
3385// helper function that creates java_library target from java_binary_host or java_test_host,
3386// and returns the library target name,
Chris Parsons637458d2023-09-19 20:09:00 +00003387func createLibraryTarget(ctx android.Bp2buildMutatorContext, libInfo libraryCreationInfo) string {
Zi Wang65b36722023-05-23 15:18:33 -07003388 libName := libInfo.baseName + "_lib"
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003389 var libProps bazel.BazelTargetModuleProperties
Zi Wang65b36722023-05-23 15:18:33 -07003390 if libInfo.hasKotlin {
Alix32540022023-03-16 21:06:13 +00003391 libProps = ktJvmLibraryBazelTargetModuleProperties()
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003392 } else {
Alix32540022023-03-16 21:06:13 +00003393 libProps = javaLibraryBazelTargetModuleProperties()
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003394 }
3395 libAttrs := &javaLibraryAttributes{
Zi Wang65b36722023-05-23 15:18:33 -07003396 Deps: libInfo.deps,
3397 javaCommonAttributes: libInfo.attrs,
Alix7c8eaeb2022-11-16 15:44:55 +00003398 }
Wei Libafb6d62021-12-10 03:14:59 -08003399
Romain Jobredeauxf5f60732023-03-16 11:00:36 -04003400 ctx.CreateBazelTargetModule(libProps, android.CommonAttributes{Name: libName}, libAttrs)
Zi Wang65b36722023-05-23 15:18:33 -07003401 return libName
Wei Libafb6d62021-12-10 03:14:59 -08003402}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003403
Liz Kammere1118222023-10-18 20:38:37 +00003404type bazelJavaImportAttributes struct {
3405 Jars bazel.LabelListAttribute
3406 Exports bazel.LabelListAttribute
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003407}
3408
3409// java_import bp2Build converter.
Chris Parsons637458d2023-09-19 20:09:00 +00003410func (i *Import) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Sam Delmerico48983162022-02-22 21:41:33 +00003411 var jars bazel.LabelListAttribute
3412 archVariantProps := i.GetArchVariantProperties(ctx, &ImportProperties{})
3413 for axis, configToProps := range archVariantProps {
3414 for config, _props := range configToProps {
3415 if archProps, ok := _props.(*ImportProperties); ok {
3416 archJars := android.BazelLabelForModuleSrcExcludes(ctx, archProps.Jars, []string(nil))
3417 jars.SetSelectValue(axis, config, archJars)
3418 }
3419 }
3420 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003421
Liz Kammere1118222023-10-18 20:38:37 +00003422 attrs := &bazelJavaImportAttributes{
3423 Jars: jars,
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003424 }
Alix82acaf52023-03-09 20:43:10 +00003425 props := bazel.BazelTargetModuleProperties{
3426 Rule_class: "java_import",
Alix83a8bc42023-05-04 18:03:23 +00003427 Bzl_load_location: "//build/bazel/rules/java:import.bzl",
Alix82acaf52023-03-09 20:43:10 +00003428 }
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003429
Liz Kammere1118222023-10-18 20:38:37 +00003430 name := android.RemoveOptionalPrebuiltPrefix(i.Name())
3431
Alixb4e09a02022-09-27 15:36:01 +00003432 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name}, attrs)
3433
Liz Kammere1118222023-10-18 20:38:37 +00003434 neverlink := true
3435 neverlinkAttrs := &javaLibraryAttributes{
3436 Neverlink: bazel.BoolAttribute{Value: &neverlink},
3437 Exports: bazel.MakeSingleLabelListAttribute(bazel.Label{Label: ":" + name}),
3438 javaCommonAttributes: &javaCommonAttributes{
3439 Sdk_version: bazel.StringAttribute{Value: proptools.StringPtr("none")},
3440 },
Alixb4e09a02022-09-27 15:36:01 +00003441 }
Alix82acaf52023-03-09 20:43:10 +00003442 ctx.CreateBazelTargetModule(
Liz Kammere1118222023-10-18 20:38:37 +00003443 javaLibraryBazelTargetModuleProperties(),
Alix82acaf52023-03-09 20:43:10 +00003444 android.CommonAttributes{Name: name + "-neverlink"},
3445 neverlinkAttrs)
Sam Delmerico277795c2022-02-25 17:04:37 +00003446}
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003447
Sam Delmerico277795c2022-02-25 17:04:37 +00003448var _ android.MixedBuildBuildable = (*Import)(nil)
3449
3450func (i *Import) getBazelModuleLabel(ctx android.BaseModuleContext) string {
3451 return android.RemoveOptionalPrebuiltPrefixFromBazelLabel(i.GetBazelLabel(ctx, i))
3452}
3453
3454func (i *Import) ProcessBazelQueryResponse(ctx android.ModuleContext) {
3455 i.commonBuildActions(ctx)
3456
3457 bazelCtx := ctx.Config().BazelContext
3458 filePaths, err := bazelCtx.GetOutputFiles(i.getBazelModuleLabel(ctx), android.GetConfigKey(ctx))
3459 if err != nil {
3460 ctx.ModuleErrorf(err.Error())
3461 return
3462 }
3463
3464 bazelJars := android.Paths{}
3465 for _, bazelOutputFile := range filePaths {
3466 bazelJars = append(bazelJars, android.PathForBazelOut(ctx, bazelOutputFile))
3467 }
3468
3469 jarName := android.RemoveOptionalPrebuiltPrefix(i.Name()) + ".jar"
3470 outputFile := android.PathForModuleOut(ctx, "bazelCombined", jarName)
3471 TransformJarsToJar(ctx, outputFile, "combine prebuilt jars", bazelJars,
3472 android.OptionalPath{}, // manifest
3473 false, // stripDirEntries
3474 []string{}, // filesToStrip
3475 []string{}, // dirsToStrip
3476 )
3477 i.combinedClasspathFile = outputFile
3478
3479 ctx.SetProvider(JavaInfoProvider, JavaInfo{
3480 HeaderJars: android.PathsIfNonNil(i.combinedClasspathFile),
3481 ImplementationAndResourcesJars: android.PathsIfNonNil(i.combinedClasspathFile),
3482 ImplementationJars: android.PathsIfNonNil(i.combinedClasspathFile),
Joe Onorato6fe59eb2023-07-16 13:20:33 -07003483 // TODO(b/240308299) include AIDL information from Bazel
3484 // TODO: aconfig files?
Sam Delmerico277795c2022-02-25 17:04:37 +00003485 })
3486
3487 i.maybeInstall(ctx, jarName, outputFile)
3488}
3489
3490func (i *Import) QueueBazelCall(ctx android.BaseModuleContext) {
3491 bazelCtx := ctx.Config().BazelContext
3492 bazelCtx.QueueBazelRequest(i.getBazelModuleLabel(ctx), cquery.GetOutputFiles, android.GetConfigKey(ctx))
3493}
3494
3495func (i *Import) IsMixedBuildSupported(ctx android.BaseModuleContext) bool {
3496 return true
Romain Jobredeaux428a3662022-01-28 11:12:52 -05003497}
Jihoon Kangfdf32362023-09-12 00:36:43 +00003498
3499type JavaApiContributionImport struct {
3500 JavaApiContribution
3501
3502 prebuilt android.Prebuilt
3503}
3504
3505func ApiContributionImportFactory() android.Module {
3506 module := &JavaApiContributionImport{}
3507 android.InitAndroidModule(module)
3508 android.InitDefaultableModule(module)
3509 android.InitPrebuiltModule(module, &[]string{""})
3510 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00003511 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00003512 return module
3513}
3514
3515func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
3516 return &module.prebuilt
3517}
3518
3519func (module *JavaApiContributionImport) Name() string {
3520 return module.prebuilt.Name(module.ModuleBase.Name())
3521}
3522
3523func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3524 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
3525}