blob: b18c56130961435e7d3fd5fb15bfbfea5e7843a9 [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"
Colin Crossdad2a362024-03-23 04:43:41 +000024 "slices"
Alix289e9c62023-08-16 15:06:31 +000025 "sort"
Wei Libafb6d62021-12-10 03:14:59 -080026 "strings"
Colin Cross2fe66872015-03-30 17:20:39 -070027
Jihoon Kang0ac87c22022-11-15 19:06:14 +000028 "android/soong/remoteexec"
Jihoon Kang6592e872023-12-19 01:13:16 +000029
Colin Cross2fe66872015-03-30 17:20:39 -070030 "github.com/google/blueprint"
Colin Crossa14fb6a2024-10-23 16:57:06 -070031 "github.com/google/blueprint/depset"
Colin Cross76b5f0c2017-08-29 16:02:06 -070032 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070033
Colin Cross635c3b02016-05-18 15:37:25 -070034 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080035 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010036 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070037 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070038 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070039)
40
Colin Cross463a90e2015-06-17 14:20:06 -070041func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010042 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000043
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080044 RegisterJavaSdkMemberTypes()
45}
46
Paul Duffin535e0a12021-03-30 23:34:32 +010047func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080048 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
49
50 ctx.RegisterModuleType("java_library", LibraryFactory)
51 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
52 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
53 ctx.RegisterModuleType("java_binary", BinaryFactory)
54 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
55 ctx.RegisterModuleType("java_test", TestFactory)
56 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
57 ctx.RegisterModuleType("java_test_host", TestHostFactory)
58 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
59 ctx.RegisterModuleType("java_import", ImportFactory)
60 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
61 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
62 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
63 ctx.RegisterModuleType("dex_import", DexImportFactory)
Jihoon Kang0ac87c22022-11-15 19:06:14 +000064 ctx.RegisterModuleType("java_api_library", ApiLibraryFactory)
65 ctx.RegisterModuleType("java_api_contribution", ApiContributionFactory)
Jihoon Kangfdf32362023-09-12 00:36:43 +000066 ctx.RegisterModuleType("java_api_contribution_import", ApiContributionImportFactory)
LaMont Jones8546f0c2025-01-30 13:51:14 -080067 ctx.RegisterModuleType("java_genrule_combiner", GenruleCombinerFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080068
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010069 // This mutator registers dependencies on dex2oat for modules that should be
70 // dexpreopted. This is done late when the final variants have been
71 // established, to not get the dependencies split into the wrong variants and
72 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080073 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
Colin Cross8a962802024-10-09 15:29:27 -070074 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator)
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040075 // needs access to ApexInfoProvider which is available after variant creation
Colin Cross8a962802024-10-09 15:29:27 -070076 ctx.BottomUp("jacoco_deps", jacocoDepsMutator)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080077 })
78
LaMont Jones0c10e4d2023-05-16 00:58:37 +000079 ctx.RegisterParallelSingletonType("kythe_java_extract", kytheExtractJavaFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080080}
81
82func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000083 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000084 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010085 android.RegisterSdkMemberType(javaLibsSdkMemberType)
Spandan Das159b2642024-03-20 21:22:47 +000086 android.RegisterSdkMemberType(JavaBootLibsSdkMemberType)
87 android.RegisterSdkMemberType(JavaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010088 android.RegisterSdkMemberType(javaTestSdkMemberType)
89}
90
Jihoon Kangfe914ed2024-02-12 22:49:21 +000091type StubsLinkType int
92
93const (
94 Unknown StubsLinkType = iota
95 Stubs
96 Implementation
97)
98
Paul Duffin2da04242021-04-23 19:43:28 +010099var (
100 // Supports adding java header libraries to module_exports and sdk.
101 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000102 android.SdkMemberTypeBase{
Paul Duffin2da04242021-04-23 19:43:28 +0100103 PropertyName: "java_header_libs",
104 SupportsSdk: true,
105 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000106 func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin2da04242021-04-23 19:43:28 +0100107 headerJars := j.HeaderJars()
108 if len(headerJars) != 1 {
109 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
110 }
111
112 return headerJars[0]
113 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000114 sdkSnapshotFilePathForJar,
115 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100116 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000117
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000118 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100119 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000120 implementationJars := j.ImplementationAndResourcesJars()
121 if len(implementationJars) != 1 {
122 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
123 }
124 return implementationJars[0]
125 }
126
Paul Duffin2da04242021-04-23 19:43:28 +0100127 // Supports adding java implementation libraries to module_exports but not sdk.
128 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000129 android.SdkMemberTypeBase{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000130 PropertyName: "java_libs",
131 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000132 exportImplementationClassesJar,
133 sdkSnapshotFilePathForJar,
134 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100135 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000136
Paul Duffin13648912022-07-15 13:12:35 +0000137 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
138 // In the S build the build will break if updatable-media does not provide a full implementation
139 // jar. That issue was fixed in Tiramisu by b/229932396.
140 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
141 return true
142 }
143
144 return false
145 }
146
Paul Duffin2da04242021-04-23 19:43:28 +0100147 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000148 //
149 // The build has some implicit dependencies (via the boot jars configuration) on a number of
150 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
151 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
152 // used outside those mainline modules.
153 //
154 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
155 // either java_libs, or java_header_libs would end up exporting more information than was strictly
156 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
157 // sdk/module_exports without exposing any unnecessary information.
Spandan Das159b2642024-03-20 21:22:47 +0000158 JavaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000159 android.SdkMemberTypeBase{
Paul Duffindb170e42020-12-08 17:48:25 +0000160 PropertyName: "java_boot_libs",
161 SupportsSdk: true,
162 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000163 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000164 if snapshotRequiresImplementationJar(ctx) {
165 return exportImplementationClassesJar(ctx, j)
166 }
167
Paul Duffin5c211452021-07-15 12:42:44 +0100168 // Java boot libs are only provided in the SDK to provide access to their dex implementation
169 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
170 // actual implementation jar but the java_import will need a file that exists so just copy an
171 // empty file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000172 return ctx.SnapshotBuilder().EmptyFile()
Paul Duffin5c211452021-07-15 12:42:44 +0100173 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000174 func(ctx android.SdkMemberContext, osPrefix, name string) string {
Paul Duffin13648912022-07-15 13:12:35 +0000175 if snapshotRequiresImplementationJar(ctx) {
176 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
177 }
178
Paul Duffin5c211452021-07-15 12:42:44 +0100179 // Create a special name for the implementation jar to try and provide some useful information
180 // to a developer that attempts to compile against this.
181 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
182 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
183 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000184 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100185 }
Paul Duffindb170e42020-12-08 17:48:25 +0000186
Jiakai Zhangea180332021-09-26 08:58:02 +0000187 // Supports adding java systemserver libraries to module_exports and sdk.
188 //
189 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
190 // of modules that are part of the java systemserver classpath and which are provided by mainline
191 // modules but which are not otherwise used outside those mainline modules.
192 //
193 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
194 // either java_libs, or java_header_libs would end up exporting more information than was strictly
195 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
196 // the sdk/module_exports without exposing any unnecessary information.
Spandan Das159b2642024-03-20 21:22:47 +0000197 JavaSystemserverLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000198 android.SdkMemberTypeBase{
Jiakai Zhangea180332021-09-26 08:58:02 +0000199 PropertyName: "java_systemserver_libs",
200 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000201
202 // This was only added in Tiramisu.
203 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000204 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000205 func(ctx android.SdkMemberContext, j *Library) android.Path {
Jiakai Zhangea180332021-09-26 08:58:02 +0000206 // Java systemserver libs are only provided in the SDK to provide access to their dex
207 // implementation jar for use by dexpreopting. They do not need to provide an actual
208 // implementation jar but the java_import will need a file that exists so just copy an empty
209 // file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000210 return ctx.SnapshotBuilder().EmptyFile()
Jiakai Zhangea180332021-09-26 08:58:02 +0000211 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000212 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000213 // Create a special name for the implementation jar to try and provide some useful information
214 // to a developer that attempts to compile against this.
215 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
216 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
217 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000218 onlyCopyJarToSnapshot,
Jiakai Zhangea180332021-09-26 08:58:02 +0000219 }
220
Paul Duffin2da04242021-04-23 19:43:28 +0100221 // Supports adding java test libraries to module_exports but not sdk.
222 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000223 SdkMemberTypeBase: android.SdkMemberTypeBase{
224 PropertyName: "java_tests",
225 },
Paul Duffin2da04242021-04-23 19:43:28 +0100226 }
Zi Wangca65b402022-10-10 13:45:06 -0700227
228 // Rule for generating device binary default wrapper
229 deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
Colin Cross7cd1d422024-11-13 13:05:49 -0800230 Command: `printf '#!/system/bin/sh\n` +
Zi Wangca65b402022-10-10 13:45:06 -0700231 `export CLASSPATH=/system/framework/$jar_name\n` +
Colin Cross7cd1d422024-11-13 13:05:49 -0800232 `exec app_process /$partition/bin $main_class "$$@"\n'> ${out}`,
Zi Wangca65b402022-10-10 13:45:06 -0700233 Description: "Generating device binary wrapper ${jar_name}",
234 }, "jar_name", "partition", "main_class")
Paul Duffin2da04242021-04-23 19:43:28 +0100235)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900236
Sam Delmerico95d70942023-08-02 18:00:35 -0400237type ProguardSpecInfo struct {
238 // If true, proguard flags files will be exported to reverse dependencies across libs edges
239 // If false, proguard flags files will only be exported to reverse dependencies across
240 // static_libs edges.
241 Export_proguard_flags_files bool
242
243 // TransitiveDepsProguardSpecFiles is a depset of paths to proguard flags files that are exported from
244 // all transitive deps. This list includes all proguard flags files from transitive static dependencies,
245 // and all proguard flags files from transitive libs dependencies which set `export_proguard_spec: true`.
Colin Crossa14fb6a2024-10-23 16:57:06 -0700246 ProguardFlagsFiles depset.DepSet[android.Path]
Sam Delmerico95d70942023-08-02 18:00:35 -0400247
248 // implementation detail to store transitive proguard flags files from exporting shared deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700249 UnconditionallyExportedProguardFlags depset.DepSet[android.Path]
Sam Delmerico95d70942023-08-02 18:00:35 -0400250}
251
Colin Crossbc7d76c2023-12-12 16:39:03 -0800252var ProguardSpecInfoProvider = blueprint.NewProvider[ProguardSpecInfo]()
Sam Delmerico95d70942023-08-02 18:00:35 -0400253
Yu Liu460cf372025-01-10 00:34:06 +0000254type AndroidLibraryDependencyInfo struct {
255 ExportPackage android.Path
256 ResourcesNodeDepSet depset.DepSet[*resourcesNode]
257 RRODirsDepSet depset.DepSet[rroDir]
258 ManifestsDepSet depset.DepSet[android.Path]
259}
260
261type UsesLibraryDependencyInfo struct {
Yu Liu460cf372025-01-10 00:34:06 +0000262 DexJarInstallPath android.Path
263 ClassLoaderContexts dexpreopt.ClassLoaderContextMap
264}
265
266type SdkLibraryComponentDependencyInfo struct {
267 // The name of the implementation library for the optional SDK library or nil, if there isn't one.
268 OptionalSdkLibraryImplementation *string
269}
270
271type ProvidesUsesLibInfo struct {
272 ProvidesUsesLib *string
273}
274
275type ModuleWithUsesLibraryInfo struct {
276 UsesLibrary *usesLibrary
277}
278
Yu Liuc0a36302025-01-10 22:26:01 +0000279type ModuleWithSdkDepInfo struct {
280 SdkLinkType sdkLinkType
281 Stubs bool
282}
283
Colin Crossdcf71b22021-02-01 13:59:03 -0800284// JavaInfo contains information about a java module for use by modules that depend on it.
285type JavaInfo struct {
286 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
287 // against this module. If empty, ImplementationJars should be used instead.
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700288 // Unlike LocalHeaderJars, HeaderJars includes classes from static dependencies.
Colin Crossdcf71b22021-02-01 13:59:03 -0800289 HeaderJars android.Paths
290
Joe Onorato349ae8d2024-02-05 22:46:00 +0000291 RepackagedHeaderJars android.Paths
292
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500293 // set of header jars for all transitive libs deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700294 TransitiveLibsHeaderJarsForR8 depset.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500295
296 // set of header jars for all transitive static libs deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700297 TransitiveStaticLibsHeaderJarsForR8 depset.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500298
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700299 // depset of header jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700300 TransitiveStaticLibsHeaderJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700301
302 // depset of implementation jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700303 TransitiveStaticLibsImplementationJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700304
305 // depset of resource jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700306 TransitiveStaticLibsResourceJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700307
Colin Crossdcf71b22021-02-01 13:59:03 -0800308 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
309 // in the module as well as any resources included in the module.
310 ImplementationAndResourcesJars android.Paths
311
312 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin27819362024-07-22 21:03:50 +0100313 // module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800314 ImplementationJars android.Paths
315
316 // ResourceJars is a list of jars that contain the resources included in the module.
317 ResourceJars android.Paths
318
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700319 // LocalHeaderJars is a list of jars that contain classes from this module, but not from any static dependencies.
320 LocalHeaderJars android.Paths
321
Colin Crossdcf71b22021-02-01 13:59:03 -0800322 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
323 // depending on this module.
324 AidlIncludeDirs android.Paths
325
326 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
327 // module.
328 SrcJarArgs []string
329
330 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
331 SrcJarDeps android.Paths
332
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000333 // The source files of this module and all its transitive static dependencies.
Colin Crossa14fb6a2024-10-23 16:57:06 -0700334 TransitiveSrcFiles depset.DepSet[android.Path]
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000335
Colin Crossdcf71b22021-02-01 13:59:03 -0800336 // ExportedPlugins is a list of paths that should be used as annotation processors for any
337 // module that depends on this module.
338 ExportedPlugins android.Paths
339
340 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
341 // any module that depends on this module.
342 ExportedPluginClasses []string
343
344 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
345 // requiring disbling turbine for any modules that depend on it.
346 ExportedPluginDisableTurbine bool
347
348 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
349 // instrumented by jacoco.
350 JacocoReportClassesFile android.Path
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000351
352 // StubsLinkType provides information about whether the provided jars are stub jars or
353 // implementation jars. If the provider is set by java_sdk_library, the link type is "unknown"
354 // and selection between the stub jar vs implementation jar is deferred to SdkLibrary.sdkJars(...)
355 StubsLinkType StubsLinkType
Jihoon Kang705e63e2024-03-13 01:21:16 +0000356
357 // AconfigIntermediateCacheOutputPaths is a path to the cache files collected from the
358 // java_aconfig_library modules that are statically linked to this module.
359 AconfigIntermediateCacheOutputPaths android.Paths
Yu Liu63bdf632024-12-03 19:54:05 +0000360
361 SdkVersion android.SdkSpec
Yu Liu460cf372025-01-10 00:34:06 +0000362
Yu Liu7eebf8b2025-01-17 00:23:57 +0000363 // output file of the module, which may be a classes jar or a dex jar
364 OutputFile android.Path
365
Yu Liu35acd332025-01-24 23:11:22 +0000366 ExtraOutputFiles android.Paths
367
Yu Liu460cf372025-01-10 00:34:06 +0000368 AndroidLibraryDependencyInfo *AndroidLibraryDependencyInfo
369
370 UsesLibraryDependencyInfo *UsesLibraryDependencyInfo
371
372 SdkLibraryComponentDependencyInfo *SdkLibraryComponentDependencyInfo
373
374 ProvidesUsesLibInfo *ProvidesUsesLibInfo
375
Cole Faustc9b88c92025-02-06 17:58:26 -0800376 MissingOptionalUsesLibs []string
Yu Liuc0a36302025-01-10 22:26:01 +0000377
378 ModuleWithSdkDepInfo *ModuleWithSdkDepInfo
Yu Liu35acd332025-01-24 23:11:22 +0000379
380 // output file containing classes.dex and resources
381 DexJarFile OptionalDexJarPath
382
383 // installed file for binary dependency
384 InstallFile android.Path
385
386 // The path to the dex jar that is in the boot class path. If this is unset then the associated
387 // module is not a boot jar, but could be one of the <x>-hiddenapi modules that provide additional
388 // annotations for the <x> boot dex jar but which do not actually provide a boot dex jar
389 // themselves.
390 //
391 // This must be the path to the unencoded dex jar as the encoded dex jar indirectly depends on
392 // this file so using the encoded dex jar here would result in a cycle in the ninja rules.
393 BootDexJarPath OptionalDexJarPath
394
395 // The compressed state of the dex file being encoded. This is used to ensure that the encoded
396 // dex file has the same state.
397 UncompressDexState *bool
398
399 // True if the module containing this structure contributes to the hiddenapi information or has
400 // that information encoded within it.
401 Active bool
402
403 BuiltInstalled string
404
Yu Liu35acd332025-01-24 23:11:22 +0000405 // The config is used for two purposes:
406 // - Passing dexpreopt information about libraries from Soong to Make. This is needed when
407 // a <uses-library> is defined in Android.bp, but used in Android.mk (see dex_preopt_config_merger.py).
408 // Note that dexpreopt.config might be needed even if dexpreopt is disabled for the library itself.
409 // - Dexpreopt post-processing (using dexpreopt artifacts from a prebuilt system image to incrementally
410 // dexpreopt another partition).
411 ConfigPath android.WritablePath
412
Yu Liu35acd332025-01-24 23:11:22 +0000413 LogtagsSrcs android.Paths
414
415 ProguardDictionary android.OptionalPath
416
417 ProguardUsageZip android.OptionalPath
418
419 LinterReports android.Paths
420
421 // installed file for hostdex copy
422 HostdexInstallFile android.InstallPath
423
424 // Additional srcJars tacked in by GeneratedJavaLibraryModule
425 GeneratedSrcjars []android.Path
426
427 // True if profile-guided optimization is actually enabled.
428 ProfileGuided bool
Yu Liu0a37d422025-02-13 02:05:00 +0000429
430 Stem string
431
432 DexJarBuildPath OptionalDexJarPath
433
434 DexpreopterInfo *DexpreopterInfo
Colin Crossdcf71b22021-02-01 13:59:03 -0800435}
436
Colin Cross7727c7f2024-07-18 15:36:32 -0700437var JavaInfoProvider = blueprint.NewProvider[*JavaInfo]()
Colin Crossdcf71b22021-02-01 13:59:03 -0800438
Yu Liu0a37d422025-02-13 02:05:00 +0000439type DexpreopterInfo struct {
440 // The path to the profile on host that dexpreopter generates. This is used as the input for
441 // dex2oat.
442 OutputProfilePathOnHost android.Path
443 // If the java module is to be installed into an APEX, this list contains information about the
444 // dexpreopt outputs to be installed on devices. Note that these dexpreopt outputs are installed
445 // outside of the APEX.
446 ApexSystemServerDexpreoptInstalls []DexpreopterInstall
447
448 // ApexSystemServerDexJars returns the list of dex jars if this is an apex system server jar.
449 ApexSystemServerDexJars android.Paths
450}
451
452type JavaLibraryInfo struct {
453 Prebuilt bool
454}
Yu Liuc0a36302025-01-10 22:26:01 +0000455
456var JavaLibraryInfoProvider = blueprint.NewProvider[JavaLibraryInfo]()
457
Yu Liu0a37d422025-02-13 02:05:00 +0000458type JavaDexImportInfo struct{}
459
460var JavaDexImportInfoProvider = blueprint.NewProvider[JavaDexImportInfo]()
461
Colin Cross75ce9ec2021-02-26 16:20:32 -0800462// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
463// the sysprop implementation library.
464type SyspropPublicStubInfo struct {
465 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
466 // the sysprop implementation library.
Colin Cross7727c7f2024-07-18 15:36:32 -0700467 JavaInfo *JavaInfo
Colin Cross75ce9ec2021-02-26 16:20:32 -0800468}
469
Colin Crossbc7d76c2023-12-12 16:39:03 -0800470var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]()
Colin Cross75ce9ec2021-02-26 16:20:32 -0800471
Paul Duffin44b481b2020-06-17 16:59:43 +0100472// Methods that need to be implemented for a module that is added to apex java_libs property.
473type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700474 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100475 ImplementationAndResourcesJars() android.Paths
476}
477
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100478// Provides build path and install path to DEX jars.
479type UsesLibraryDependency interface {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000480 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100481 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000482 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100483}
484
Jaewoong Jung26342642021-03-17 15:56:23 -0700485// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800486type xref interface {
487 XrefJavaFiles() android.Paths
Spandan Das1028d5a2024-08-19 21:45:48 +0000488 XrefKotlinFiles() android.Paths
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800489}
490
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800491func (j *Module) XrefJavaFiles() android.Paths {
492 return j.kytheFiles
493}
494
Spandan Das1028d5a2024-08-19 21:45:48 +0000495func (j *Module) XrefKotlinFiles() android.Paths {
496 return j.kytheKotlinFiles
497}
498
Yu Liu67a28422024-03-05 00:36:31 +0000499func (d dependencyTag) PropagateAconfigValidation() bool {
500 return d.static
501}
502
503var _ android.PropagateAconfigValidationDependencyTag = dependencyTag{}
504
Colin Crossbe1da472017-07-07 15:59:46 -0700505type dependencyTag struct {
506 blueprint.BaseDependencyTag
507 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000508
509 // True if the dependency is relinked at runtime.
510 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800511
512 // True if the dependency is a toolchain, for example an annotation processor.
513 toolchain bool
Yu Liu67a28422024-03-05 00:36:31 +0000514
515 static bool
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000516
517 installable bool
Colin Cross2fe66872015-03-30 17:20:39 -0700518}
519
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000520var _ android.InstallNeededDependencyTag = (*dependencyTag)(nil)
521
522func (d dependencyTag) InstallDepNeeded() bool {
523 return d.installable
Colin Crosse9fe2942020-11-10 18:12:15 -0800524}
525
Colin Cross65cb3142021-12-10 23:05:02 +0000526func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
527 if d.runtimeLinked {
528 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800529 } else if d.toolchain {
530 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000531 }
532 return nil
533}
534
535var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
536
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100537type usesLibraryDependencyTag struct {
538 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100539 sdkVersion int // SDK version in which the library appared as a standalone library.
540 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100541}
542
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100543func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100544 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000545 dependencyTag: dependencyTag{
546 name: fmt.Sprintf("uses-library-%d", sdkVersion),
547 runtimeLinked: true,
548 },
549 sdkVersion: sdkVersion,
550 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100551 }
552}
553
Jiyong Park8be103b2019-11-08 15:53:48 +0900554func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000555 return depTag == jniLibTag || depTag == jniInstallTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900556}
557
Colin Crossbe1da472017-07-07 15:59:46 -0700558var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800559 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000560 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Yu Liu67a28422024-03-05 00:36:31 +0000561 staticLibTag = dependencyTag{name: "staticlib", static: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000562 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400563 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000564 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800565 pluginTag = dependencyTag{name: "plugin", toolchain: true}
566 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
567 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000568 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
569 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800570 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Crossce564252022-01-12 11:13:32 -0800571 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800572 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
573 certificateTag = dependencyTag{name: "certificate"}
574 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800575 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000576 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500577 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800578 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000579 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
Jihoon Kang84b25892023-12-01 22:01:06 +0000580 aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"}
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000581 jniInstallTag = dependencyTag{name: "jni install", runtimeLinked: true, installable: true}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100582 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
583 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
584 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
585 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
586 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700587)
Colin Cross2fe66872015-03-30 17:20:39 -0700588
Spandan Das8aac9932024-07-18 23:14:13 +0000589// A list of tags for deps used for compiling a module.
590// Any dependency tags that modifies the following properties of `deps` in `Module.collectDeps` should be
591// added to this list:
592// - bootClasspath
593// - classpath
594// - java9Classpath
595// - systemModules
596// - kotlin deps...
597var (
598 compileDependencyTags = []blueprint.DependencyTag{
599 sdkLibTag,
600 libTag,
601 staticLibTag,
602 bootClasspathTag,
603 systemModulesTag,
604 java9LibTag,
Spandan Das8aac9932024-07-18 23:14:13 +0000605 kotlinPluginTag,
606 syspropPublicStubDepTag,
607 instrumentationForTag,
608 }
609)
610
Jiyong Park83dc74b2020-01-14 18:38:44 +0900611func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Jihoon Kangd2de5932025-02-04 17:53:44 +0000612 return depTag == libTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900613}
614
615func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
616 return depTag == staticLibTag
617}
618
Colin Crossfc3674a2017-09-18 17:41:52 -0700619type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100620 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700621
Colin Cross6cef4812019-10-17 14:23:50 -0700622 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
623 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100624
625 // The default system modules to use. Will be an empty string if no system
626 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700627 systemModules string
628
Pete Gilline3d44b22020-06-29 11:28:51 +0100629 // The modules that will be added to the classpath regardless of the Java language level targeted
630 classpath []string
631
Colin Cross6cef4812019-10-17 14:23:50 -0700632 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100633 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700634 java9Classpath []string
635
Colin Crossa97c5d32018-03-28 14:58:31 -0700636 frameworkResModule string
637
Colin Cross86a60ae2018-05-29 14:44:55 -0700638 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700639 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100640
641 noStandardLibs, noFrameworksLibs bool
642}
643
644func (s sdkDep) hasStandardLibs() bool {
645 return !s.noStandardLibs
646}
647
648func (s sdkDep) hasFrameworkLibs() bool {
649 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700650}
651
Colin Crossa4f08812018-10-02 22:03:40 -0700652type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700653 name string
654 path android.Path
655 target android.Target
656 coverageFile android.OptionalPath
657 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000658 partition string
Jiyong Park25b92222024-05-17 22:58:54 +0000659 installPaths android.InstallPaths
Colin Crossa4f08812018-10-02 22:03:40 -0700660}
661
Jiyong Parkf1691d22021-03-29 20:11:58 +0900662func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700663 sdkDep := decodeSdkDep(ctx, sdkContext)
664 if sdkDep.useModule {
665 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
666 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400667 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700668 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000669 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000670 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000671 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700672 }
673 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
674 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
675 }
676 }
677 if sdkDep.systemModules != "" {
678 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
679 }
680}
681
Colin Cross32f676a2017-09-06 13:41:06 -0700682type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700683 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
684 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
685 // systemModules and java9Classpath instead.
686 bootClasspath classpath
687
688 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
689 // contains header jars for all static and non-static dependencies.
690 classpath classpath
691
692 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
693 // header jars for all non-static dependencies. Static dependencies have already been
694 // combined into the program jar.
695 dexClasspath classpath
696
697 // java9Classpath is the list of jars that will be added to the classpath when targeting
698 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
699 // are provided by systemModules.
700 java9Classpath classpath
701
Colin Crossfdaa6722024-08-23 11:58:08 -0700702 processorPath classpath ``
Colin Cross748b2d82020-11-19 13:52:06 -0800703 errorProneProcessorPath classpath
704 processorClasses []string
705 staticJars android.Paths
706 staticHeaderJars android.Paths
707 staticResourceJars android.Paths
708 aidlIncludeDirs android.Paths
709 srcs android.Paths
710 srcJars android.Paths
711 systemModules *systemModules
712 aidlPreprocess android.OptionalPath
Colin Crossa1ff7c62021-09-17 14:11:52 -0700713 kotlinPlugins android.Paths
Jihoon Kang6592e872023-12-19 01:13:16 +0000714 aconfigProtoFiles android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800715
716 disableTurbine bool
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700717
Colin Crossa14fb6a2024-10-23 16:57:06 -0700718 transitiveStaticLibsHeaderJars []depset.DepSet[android.Path]
719 transitiveStaticLibsImplementationJars []depset.DepSet[android.Path]
720 transitiveStaticLibsResourceJars []depset.DepSet[android.Path]
Colin Cross32f676a2017-09-06 13:41:06 -0700721}
Colin Cross2fe66872015-03-30 17:20:39 -0700722
Yu Liu39f5fb32025-01-13 23:52:19 +0000723func checkProducesJars(ctx android.ModuleContext, dep android.SourceFilesInfo, module android.ModuleProxy) {
724 for _, f := range dep.Srcs {
Colin Cross54250902017-12-05 09:28:08 -0800725 if f.Ext() != ".jar" {
726 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
Yu Liu39f5fb32025-01-13 23:52:19 +0000727 ctx.OtherModuleName(module))
Colin Cross54250902017-12-05 09:28:08 -0800728 }
729 }
730}
731
Jiyong Parkf1691d22021-03-29 20:11:58 +0900732func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700733 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700734 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700735 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900736 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca253f8c02024-05-23 10:28:24 +0100737 } else if ctx.Config().TargetsJava21() {
Sorin Basca37cc2712024-10-16 10:25:36 +0100738 // Build flag that controls whether Java 21 is used as the default
739 // target version, or Java 17.
Sorin Basca253f8c02024-05-23 10:28:24 +0100740 return JAVA_VERSION_21
Sorin Basca384250c2023-02-02 17:56:19 +0000741 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000742 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700743 }
Nan Zhang357466b2018-04-17 17:38:36 -0700744}
745
Jihoon Kangff878bf2022-12-22 21:26:06 +0000746// Java version for stubs generation
747func getStubsJavaVersion() javaVersion {
748 return JAVA_VERSION_8
749}
750
Colin Cross1e743852019-10-28 11:37:20 -0700751type javaVersion int
752
753const (
754 JAVA_VERSION_UNSUPPORTED = 0
755 JAVA_VERSION_6 = 6
756 JAVA_VERSION_7 = 7
757 JAVA_VERSION_8 = 8
758 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000759 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100760 JAVA_VERSION_17 = 17
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100761 JAVA_VERSION_21 = 21
Colin Cross1e743852019-10-28 11:37:20 -0700762)
763
764func (v javaVersion) String() string {
765 switch v {
766 case JAVA_VERSION_6:
Sorin Bascad567a512024-01-15 16:38:46 +0000767 // Java version 1.6 no longer supported, bumping to 1.8
768 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700769 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000770 // Java version 1.7 no longer supported, bumping to 1.8
771 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700772 case JAVA_VERSION_8:
773 return "1.8"
774 case JAVA_VERSION_9:
775 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000776 case JAVA_VERSION_11:
777 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100778 case JAVA_VERSION_17:
779 return "17"
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100780 case JAVA_VERSION_21:
781 return "21"
Colin Cross1e743852019-10-28 11:37:20 -0700782 default:
783 return "unsupported"
784 }
785}
786
Cole Faustd96eebf2022-06-28 14:41:27 -0700787func (v javaVersion) StringForKotlinc() string {
788 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
789 // error: unknown JVM target version: foo
Sorin Bascad567a512024-01-15 16:38:46 +0000790 // Supported versions: 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
Cole Faustd96eebf2022-06-28 14:41:27 -0700791 switch v {
Sorin Bascad567a512024-01-15 16:38:46 +0000792 case JAVA_VERSION_6:
793 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700794 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000795 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700796 case JAVA_VERSION_9:
797 return "9"
798 default:
799 return v.String()
800 }
801}
802
Colin Cross1e743852019-10-28 11:37:20 -0700803// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
804func (v javaVersion) usesJavaModules() bool {
805 return v >= 9
806}
807
808func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100809 switch javaVersion {
810 case "1.6", "6":
Sorin Bascad567a512024-01-15 16:38:46 +0000811 // Java version 1.6 no longer supported, bumping to 1.8
812 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100813 case "1.7", "7":
Sorin Bascad567a512024-01-15 16:38:46 +0000814 // Java version 1.7 no longer supported, bumping to 1.8
815 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100816 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700817 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100818 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700819 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000820 case "11":
821 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100822 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100823 return JAVA_VERSION_17
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100824 case "21":
825 return JAVA_VERSION_21
Sorin Bascace720c32022-05-24 12:13:50 +0100826 case "10", "12", "13", "14", "15", "16":
827 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700828 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100829 default:
830 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700831 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100832 }
833}
834
Colin Cross2fe66872015-03-30 17:20:39 -0700835//
836// Java libraries (.jar file)
837//
838
Colin Crossf506d872017-07-19 15:53:04 -0700839type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700840 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700841
Colin Cross312634e2023-11-21 15:13:56 -0800842 combinedExportedProguardFlagsFile android.Path
Jared Duke5979b302022-12-19 21:08:39 +0000843
Colin Cross09ad3a62023-11-15 12:29:33 -0800844 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Jihoon Kang1262e202025-02-07 22:46:09 +0000845
846 apiXmlFile android.WritablePath
Colin Cross2fe66872015-03-30 17:20:39 -0700847}
848
Jiyong Park45bf82e2020-12-15 22:29:02 +0900849var _ android.ApexModule = (*Library)(nil)
850
Jihoon Kanga3a05462024-04-05 00:36:44 +0000851func (j *Library) CheckDepsMinSdkVersion(ctx android.ModuleContext) {
852 CheckMinSdkVersion(ctx, j)
853}
854
satayevd604b212021-07-21 14:23:52 +0100855// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100856type PermittedPackagesForUpdatableBootJars interface {
857 PermittedPackagesForUpdatableBootJars() []string
858}
859
860var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
861
862func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
863 return j.properties.Permitted_packages
864}
865
Spandan Dase21a8d42024-01-23 23:56:29 +0000866func shouldUncompressDex(ctx android.ModuleContext, libName string, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000867 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Crossff694a82023-12-13 15:54:49 -0800868 if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000869 return true
870 }
871
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000872 // Store uncompressed (and do not strip) dex files from boot class path jars.
873 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
874 return true
875 }
876
Jared Dukea561efb2024-02-09 18:45:24 +0000877 // Store uncompressed dex files that are preopted on /system or /system_other.
878 if !dexpreopter.dexpreoptDisabled(ctx, libName) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000879 return true
880 }
Jared Dukea561efb2024-02-09 18:45:24 +0000881
Colin Cross083a2aa2019-02-06 16:37:12 -0800882 if ctx.Config().UncompressPrivAppDex() &&
883 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
884 return true
885 }
886
Colin Cross2fc72f62018-12-21 12:59:54 -0800887 return false
888}
889
Jiakai Zhang22450f22021-10-11 03:05:20 +0000890// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
891func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
892 if dexer.dexProperties.Uncompress_dex == nil {
893 // If the value was not force-set by the user, use reasonable default based on the module.
Spandan Dase21a8d42024-01-23 23:56:29 +0000894 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexpreopter))
Jiakai Zhang22450f22021-10-11 03:05:20 +0000895 }
896}
897
Spandan Das8469e932024-02-20 16:47:07 +0000898// list of java_library modules that set platform_apis: true
899// this property is a no-op for java_library
900// TODO (b/215379393): Remove this allowlist
901var (
902 aospPlatformApiAllowlist = map[string]bool{
903 "adservices-test-scenarios": true,
904 "aidl-cpp-java-test-interface-java": true,
905 "aidl-test-extras-java": true,
906 "aidl-test-interface-java": true,
907 "aidl-test-interface-permission-java": true,
908 "aidl_test_java_client_permission": true,
909 "aidl_test_java_client_sdk1": true,
910 "aidl_test_java_client_sdk29": true,
911 "aidl_test_java_client": true,
912 "aidl_test_java_service_permission": true,
913 "aidl_test_java_service_sdk1": true,
914 "aidl_test_java_service_sdk29": true,
915 "aidl_test_java_service": true,
916 "aidl_test_loggable_interface-java": true,
917 "aidl_test_nonvintf_parcelable-V1-java": true,
918 "aidl_test_nonvintf_parcelable-V2-java": true,
919 "aidl_test_unstable_parcelable-java": true,
920 "aidl_test_vintf_parcelable-V1-java": true,
921 "aidl_test_vintf_parcelable-V2-java": true,
922 "android.aidl.test.trunk-V1-java": true,
923 "android.aidl.test.trunk-V2-java": true,
924 "android.frameworks.location.altitude-V1-java": true,
925 "android.frameworks.location.altitude-V2-java": true,
926 "android.frameworks.stats-V1-java": true,
927 "android.frameworks.stats-V2-java": true,
928 "android.frameworks.stats-V3-java": true,
929 "android.hardware.authsecret-V1-java": true,
930 "android.hardware.authsecret-V2-java": true,
931 "android.hardware.biometrics.common-V1-java": true,
932 "android.hardware.biometrics.common-V2-java": true,
933 "android.hardware.biometrics.common-V3-java": true,
934 "android.hardware.biometrics.common-V4-java": true,
935 "android.hardware.biometrics.face-V1-java": true,
936 "android.hardware.biometrics.face-V2-java": true,
937 "android.hardware.biometrics.face-V3-java": true,
938 "android.hardware.biometrics.face-V4-java": true,
939 "android.hardware.biometrics.fingerprint-V1-java": true,
940 "android.hardware.biometrics.fingerprint-V2-java": true,
941 "android.hardware.biometrics.fingerprint-V3-java": true,
942 "android.hardware.biometrics.fingerprint-V4-java": true,
943 "android.hardware.bluetooth.lmp_event-V1-java": true,
944 "android.hardware.confirmationui-V1-java": true,
945 "android.hardware.confirmationui-V2-java": true,
946 "android.hardware.gatekeeper-V1-java": true,
947 "android.hardware.gatekeeper-V2-java": true,
948 "android.hardware.gnss-V1-java": true,
949 "android.hardware.gnss-V2-java": true,
950 "android.hardware.gnss-V3-java": true,
951 "android.hardware.gnss-V4-java": true,
952 "android.hardware.graphics.common-V1-java": true,
953 "android.hardware.graphics.common-V2-java": true,
954 "android.hardware.graphics.common-V3-java": true,
955 "android.hardware.graphics.common-V4-java": true,
956 "android.hardware.graphics.common-V5-java": true,
957 "android.hardware.identity-V1-java": true,
958 "android.hardware.identity-V2-java": true,
959 "android.hardware.identity-V3-java": true,
960 "android.hardware.identity-V4-java": true,
961 "android.hardware.identity-V5-java": true,
962 "android.hardware.identity-V6-java": true,
963 "android.hardware.keymaster-V1-java": true,
964 "android.hardware.keymaster-V2-java": true,
965 "android.hardware.keymaster-V3-java": true,
966 "android.hardware.keymaster-V4-java": true,
967 "android.hardware.keymaster-V5-java": true,
968 "android.hardware.oemlock-V1-java": true,
969 "android.hardware.oemlock-V2-java": true,
970 "android.hardware.power.stats-V1-java": true,
971 "android.hardware.power.stats-V2-java": true,
972 "android.hardware.power.stats-V3-java": true,
973 "android.hardware.power-V1-java": true,
974 "android.hardware.power-V2-java": true,
975 "android.hardware.power-V3-java": true,
976 "android.hardware.power-V4-java": true,
977 "android.hardware.power-V5-java": true,
978 "android.hardware.rebootescrow-V1-java": true,
979 "android.hardware.rebootescrow-V2-java": true,
980 "android.hardware.security.authgraph-V1-java": true,
981 "android.hardware.security.keymint-V1-java": true,
982 "android.hardware.security.keymint-V2-java": true,
983 "android.hardware.security.keymint-V3-java": true,
984 "android.hardware.security.keymint-V4-java": true,
Nikolay Elenkov7ee98922024-03-21 06:41:34 +0000985 "android.hardware.security.secretkeeper-V1-java": true,
Spandan Das8469e932024-02-20 16:47:07 +0000986 "android.hardware.security.secureclock-V1-java": true,
987 "android.hardware.security.secureclock-V2-java": true,
988 "android.hardware.thermal-V1-java": true,
989 "android.hardware.thermal-V2-java": true,
990 "android.hardware.threadnetwork-V1-java": true,
991 "android.hardware.weaver-V1-java": true,
992 "android.hardware.weaver-V2-java": true,
993 "android.hardware.weaver-V3-java": true,
994 "android.security.attestationmanager-java": true,
995 "android.security.authorization-java": true,
996 "android.security.compat-java": true,
997 "android.security.legacykeystore-java": true,
998 "android.security.maintenance-java": true,
999 "android.security.metrics-java": true,
1000 "android.system.keystore2-V1-java": true,
1001 "android.system.keystore2-V2-java": true,
1002 "android.system.keystore2-V3-java": true,
1003 "android.system.keystore2-V4-java": true,
1004 "binderReadParcelIface-java": true,
1005 "binderRecordReplayTestIface-java": true,
1006 "car-experimental-api-static-lib": true,
1007 "collector-device-lib-platform": true,
1008 "com.android.car.oem": true,
1009 "com.google.hardware.pixel.display-V10-java": true,
1010 "com.google.hardware.pixel.display-V1-java": true,
1011 "com.google.hardware.pixel.display-V2-java": true,
1012 "com.google.hardware.pixel.display-V3-java": true,
1013 "com.google.hardware.pixel.display-V4-java": true,
1014 "com.google.hardware.pixel.display-V5-java": true,
1015 "com.google.hardware.pixel.display-V6-java": true,
1016 "com.google.hardware.pixel.display-V7-java": true,
1017 "com.google.hardware.pixel.display-V8-java": true,
1018 "com.google.hardware.pixel.display-V9-java": true,
1019 "conscrypt-support": true,
1020 "cts-keystore-test-util": true,
1021 "cts-keystore-user-auth-helper-library": true,
1022 "ctsmediautil": true,
1023 "CtsNetTestsNonUpdatableLib": true,
1024 "DpmWrapper": true,
1025 "flickerlib-apphelpers": true,
1026 "flickerlib-helpers": true,
1027 "flickerlib-parsers": true,
1028 "flickerlib": true,
1029 "hardware.google.bluetooth.ccc-V1-java": true,
1030 "hardware.google.bluetooth.sar-V1-java": true,
1031 "monet": true,
1032 "pixel-power-ext-V1-java": true,
1033 "pixel-power-ext-V2-java": true,
1034 "pixel_stateresidency_provider_aidl_interface-java": true,
1035 "pixel-thermal-ext-V1-java": true,
1036 "protolog-lib": true,
1037 "RkpRegistrationCheck": true,
1038 "rotary-service-javastream-protos": true,
1039 "service_based_camera_extensions": true,
1040 "statsd-helper-test": true,
1041 "statsd-helper": true,
1042 "test-piece-2-V1-java": true,
1043 "test-piece-2-V2-java": true,
1044 "test-piece-3-V1-java": true,
1045 "test-piece-3-V2-java": true,
1046 "test-piece-3-V3-java": true,
1047 "test-piece-4-V1-java": true,
1048 "test-piece-4-V2-java": true,
1049 "test-root-package-V1-java": true,
1050 "test-root-package-V2-java": true,
1051 "test-root-package-V3-java": true,
1052 "test-root-package-V4-java": true,
1053 "testServiceIface-java": true,
1054 "wm-flicker-common-app-helpers": true,
1055 "wm-flicker-common-assertions": true,
1056 "wm-shell-flicker-utils": true,
1057 "wycheproof-keystore": true,
1058 }
Paul Duffin3f1ae0b2022-07-27 16:27:42 +00001059
Spandan Das8469e932024-02-20 16:47:07 +00001060 // Union of aosp and internal allowlists
1061 PlatformApiAllowlist = map[string]bool{}
1062)
1063
1064func init() {
1065 for k, v := range aospPlatformApiAllowlist {
1066 PlatformApiAllowlist[k] = v
1067 }
1068}
1069
1070func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Spandan Das5ae65ee2024-04-16 22:03:26 +00001071 if disableSourceApexVariant(ctx) {
1072 // Prebuilts are active, do not create the installation rules for the source javalib.
1073 // Even though the source javalib is not used, we need to hide it to prevent duplicate installation rules.
1074 // TODO (b/331665856): Implement a principled solution for this.
1075 j.HideFromMake()
Spandan Das034af2c2024-10-30 21:45:09 +00001076 j.SkipInstall()
Spandan Das5ae65ee2024-04-16 22:03:26 +00001077 }
Paul Duffin3f1ae0b2022-07-27 16:27:42 +00001078 j.provideHiddenAPIPropertyInfo(ctx)
1079
Jiyong Park92315372021-04-02 08:45:46 +09001080 j.sdkVersion = j.SdkVersion(ctx)
1081 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +00001082 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +09001083
Jihoon Kanga3a05462024-04-05 00:36:44 +00001084 // Check min_sdk_version of the transitive dependencies if this module is created from
1085 // java_sdk_library.
Spandan Dasb9c58352024-05-13 18:29:45 +00001086 if j.overridableProperties.Min_sdk_version != nil && j.SdkLibraryName() != nil {
Jihoon Kanga3a05462024-04-05 00:36:44 +00001087 j.CheckDepsMinSdkVersion(ctx)
1088 }
1089
Jihoon Kangfe914ed2024-02-12 22:49:21 +00001090 // SdkLibrary.GenerateAndroidBuildActions(ctx) sets the stubsLinkType to Unknown.
1091 // If the stubsLinkType has already been set to Unknown, the stubsLinkType should
1092 // not be overridden.
1093 if j.stubsLinkType != Unknown {
1094 if proptools.Bool(j.properties.Is_stubs_module) {
1095 j.stubsLinkType = Stubs
1096 } else {
1097 j.stubsLinkType = Implementation
1098 }
1099 }
1100
yangbill2af0b6e2024-03-15 09:29:29 +00001101 j.stem = proptools.StringDefault(j.overridableProperties.Stem, ctx.ModuleName())
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001102
Sam Delmericoc8e040c2023-10-31 17:27:02 +00001103 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
Colin Cross40213022023-12-13 15:19:49 -08001104 android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo)
Colin Cross312634e2023-11-21 15:13:56 -08001105 exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList()
1106 j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...)
1107
1108 combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags")
1109 writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles)
1110 j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile
Sam Delmericoc8e040c2023-10-31 17:27:02 +00001111
Colin Crossff694a82023-12-13 15:54:49 -08001112 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07001113 if !apexInfo.IsForPlatform() {
1114 j.hideApexVariantFromMake = true
1115 }
1116
Artur Satayev2db1c3f2020-04-08 19:09:30 +01001117 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +00001118 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -08001119 if ctx.Device() {
Jihoon Kanga3a05462024-04-05 00:36:44 +00001120 libName := j.Name()
1121 if j.SdkLibraryName() != nil && strings.HasSuffix(libName, ".impl") {
1122 libName = proptools.String(j.SdkLibraryName())
1123 }
Colin Cross61df14a2021-12-01 13:04:46 -08001124 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Jihoon Kanga3a05462024-04-05 00:36:44 +00001125 ctx, libName, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross61df14a2021-12-01 13:04:46 -08001126 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
1127 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
1128 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1129 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Spandan Das0727ba72024-02-13 16:37:43 +00001130 if j.usesLibrary.shouldDisableDexpreopt {
1131 j.dexpreopter.disableDexpreopt()
1132 }
Colin Cross61df14a2021-12-01 13:04:46 -08001133 }
Yu Liu460cf372025-01-10 00:34:06 +00001134 javaInfo := j.compile(ctx, nil, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -07001135
Cole Faustb9c67e22024-10-08 16:39:56 -07001136 j.setInstallRules(ctx)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001137
1138 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
1139 TestOnly: Bool(j.sourceProperties.Test_only),
1140 TopLevelTarget: j.sourceProperties.Top_level_test_target,
1141 })
mrziwang9f7b9f42024-07-10 12:18:06 -07001142
Yu Liu0a37d422025-02-13 02:05:00 +00001143 android.SetProvider(ctx, JavaLibraryInfoProvider, JavaLibraryInfo{
1144 Prebuilt: false,
1145 })
Yu Liuc0a36302025-01-10 22:26:01 +00001146
Yu Liu460cf372025-01-10 00:34:06 +00001147 if javaInfo != nil {
1148 setExtraJavaInfo(ctx, j, javaInfo)
Yu Liu35acd332025-01-24 23:11:22 +00001149 javaInfo.ExtraOutputFiles = j.extraOutputFiles
1150 javaInfo.DexJarFile = j.dexJarFile
1151 javaInfo.InstallFile = j.installFile
1152 javaInfo.BootDexJarPath = j.bootDexJarPath
1153 javaInfo.UncompressDexState = j.uncompressDexState
1154 javaInfo.Active = j.active
Yu Liu35acd332025-01-24 23:11:22 +00001155 javaInfo.BuiltInstalled = j.builtInstalled
1156 javaInfo.ConfigPath = j.configPath
Yu Liu35acd332025-01-24 23:11:22 +00001157 javaInfo.LogtagsSrcs = j.logtagsSrcs
1158 javaInfo.ProguardDictionary = j.proguardDictionary
1159 javaInfo.ProguardUsageZip = j.proguardUsageZip
1160 javaInfo.LinterReports = j.reports
1161 javaInfo.HostdexInstallFile = j.hostdexInstallFile
1162 javaInfo.GeneratedSrcjars = j.properties.Generated_srcjars
1163 javaInfo.ProfileGuided = j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided
1164
Yu Liu460cf372025-01-10 00:34:06 +00001165 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
1166 }
1167
mrziwang9f7b9f42024-07-10 12:18:06 -07001168 setOutputFiles(ctx, j.Module)
Jihoon Kangd4063812025-01-24 00:25:30 +00001169
Cole Faust208f8e72025-01-28 13:19:19 -08001170 j.javaLibraryModuleInfoJSON(ctx)
Wei Li986fe742025-01-30 15:14:42 -08001171
1172 buildComplianceMetadata(ctx)
Jihoon Kang1262e202025-02-07 22:46:09 +00001173
1174 j.createApiXmlFile(ctx)
Cole Faust1dcf9e42025-02-19 17:23:34 -08001175
1176 if j.dexer.proguardDictionary.Valid() {
1177 android.SetProvider(ctx, ProguardProvider, ProguardInfo{
1178 ModuleName: ctx.ModuleName(),
1179 Class: "JAVA_LIBRARIES",
1180 ProguardDictionary: j.dexer.proguardDictionary.Path(),
1181 ProguardUsageZip: j.dexer.proguardUsageZip.Path(),
1182 ClassesJar: j.implementationAndResourcesJar,
1183 })
1184 }
Cole Faust208f8e72025-01-28 13:19:19 -08001185}
1186
1187func (j *Library) javaLibraryModuleInfoJSON(ctx android.ModuleContext) *android.ModuleInfoJSON {
Jihoon Kangd4063812025-01-24 00:25:30 +00001188 moduleInfoJSON := ctx.ModuleInfoJSON()
1189 moduleInfoJSON.Class = []string{"JAVA_LIBRARIES"}
1190 if j.implementationAndResourcesJar != nil {
1191 moduleInfoJSON.ClassesJar = []string{j.implementationAndResourcesJar.String()}
1192 }
1193 moduleInfoJSON.SystemSharedLibs = []string{"none"}
1194
1195 if j.hostDexNeeded() {
1196 hostDexModuleInfoJSON := ctx.ExtraModuleInfoJSON()
1197 hostDexModuleInfoJSON.SubName = "-hostdex"
1198 hostDexModuleInfoJSON.Class = []string{"JAVA_LIBRARIES"}
1199 if j.implementationAndResourcesJar != nil {
1200 hostDexModuleInfoJSON.ClassesJar = []string{j.implementationAndResourcesJar.String()}
1201 }
1202 hostDexModuleInfoJSON.SystemSharedLibs = []string{"none"}
1203 hostDexModuleInfoJSON.SupportedVariantsOverride = []string{"HOST"}
1204 }
1205
1206 if j.hideApexVariantFromMake {
1207 moduleInfoJSON.Disabled = true
Jihoon Kangd4063812025-01-24 00:25:30 +00001208 }
Cole Faust208f8e72025-01-28 13:19:19 -08001209 return moduleInfoJSON
Jihoon Kanga3a05462024-04-05 00:36:44 +00001210}
1211
Wei Li986fe742025-01-30 15:14:42 -08001212func buildComplianceMetadata(ctx android.ModuleContext) {
1213 // Dump metadata that can not be done in android/compliance-metadata.go
1214 complianceMetadataInfo := ctx.ComplianceMetadataInfo()
1215 builtFiles := ctx.GetOutputFiles().DefaultOutputFiles.Strings()
1216 for _, paths := range ctx.GetOutputFiles().TaggedOutputFiles {
1217 builtFiles = append(builtFiles, paths.Strings()...)
1218 }
Wei Li736c6c22025-02-11 12:59:24 -08001219 complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.BUILT_FILES, android.SortedUniqueStrings(builtFiles))
Wei Li986fe742025-01-30 15:14:42 -08001220
1221 // Static deps
1222 staticDepNames := make([]string, 0)
1223 staticDepFiles := android.Paths{}
1224 ctx.VisitDirectDepsWithTag(staticLibTag, func(module android.Module) {
1225 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
1226 staticDepNames = append(staticDepNames, module.Name())
1227 staticDepFiles = append(staticDepFiles, dep.ImplementationJars...)
1228 staticDepFiles = append(staticDepFiles, dep.HeaderJars...)
1229 staticDepFiles = append(staticDepFiles, dep.ResourceJars...)
1230 }
1231 })
Wei Li736c6c22025-02-11 12:59:24 -08001232 complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.STATIC_DEPS, android.SortedUniqueStrings(staticDepNames))
1233 complianceMetadataInfo.SetListValue(android.ComplianceMetadataProp.STATIC_DEP_FILES, android.SortedUniqueStrings(staticDepFiles.Strings()))
Wei Li986fe742025-01-30 15:14:42 -08001234}
1235
Cole Faustb9c67e22024-10-08 16:39:56 -07001236func (j *Library) getJarInstallDir(ctx android.ModuleContext) android.InstallPath {
1237 var installDir android.InstallPath
1238 if ctx.InstallInTestcases() {
1239 var archDir string
1240 if !ctx.Host() {
1241 archDir = ctx.DeviceConfig().DeviceArch()
1242 }
1243 installModuleName := ctx.ModuleName()
1244 // If this module is an impl library created from java_sdk_library,
1245 // install the files under the java_sdk_library module outdir instead of this module outdir.
1246 if j.SdkLibraryName() != nil && strings.HasSuffix(j.Name(), ".impl") {
1247 installModuleName = proptools.String(j.SdkLibraryName())
1248 }
1249 installDir = android.PathForModuleInstall(ctx, installModuleName, archDir)
1250 } else {
1251 installDir = android.PathForModuleInstall(ctx, "framework")
1252 }
1253 return installDir
1254}
1255
1256func (j *Library) setInstallRules(ctx android.ModuleContext) {
Jihoon Kanga3a05462024-04-05 00:36:44 +00001257 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
1258
1259 if (Bool(j.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() {
Colin Cross09ad3a62023-11-15 12:29:33 -08001260 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -07001261 if j.InstallMixin != nil {
1262 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
1263 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001264 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
1265 if hostDexNeeded {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001266 j.hostdexInstallFile = ctx.InstallFileWithoutCheckbuild(
Colin Cross3108ce12021-11-10 14:38:50 -08001267 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001268 j.Stem()+"-hostdex.jar", j.outputFile)
1269 }
Cole Faustb9c67e22024-10-08 16:39:56 -07001270 j.installFile = ctx.InstallFileWithoutCheckbuild(j.getJarInstallDir(ctx), j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -07001271 }
Colin Crossb7a63242015-04-16 14:09:14 -07001272}
1273
Colin Crossf506d872017-07-19 15:53:04 -07001274func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Ulya Trafimoviche4432872021-08-18 16:57:11 +01001275 j.usesLibrary.deps(ctx, false)
Jiakai Zhangf98da192024-04-15 11:15:41 +00001276 j.deps(ctx)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001277
1278 if j.SdkLibraryName() != nil && strings.HasSuffix(j.Name(), ".impl") {
1279 if dexpreopt.IsDex2oatNeeded(ctx) {
1280 dexpreopt.RegisterToolDeps(ctx)
1281 }
1282 prebuiltSdkLibExists := ctx.OtherModuleExists(android.PrebuiltNameFromSource(proptools.String(j.SdkLibraryName())))
1283 if prebuiltSdkLibExists && ctx.OtherModuleExists("all_apex_contributions") {
1284 ctx.AddDependency(ctx.Module(), android.AcDepTag, "all_apex_contributions")
1285 }
1286 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001287}
1288
Jihoon Kang1262e202025-02-07 22:46:09 +00001289var apiXMLGeneratingApiSurfaces = []android.SdkKind{
1290 android.SdkPublic,
1291 android.SdkSystem,
1292 android.SdkModule,
1293 android.SdkSystemServer,
1294 android.SdkTest,
1295}
1296
1297func (j *Library) createApiXmlFile(ctx android.ModuleContext) {
1298 if kind, ok := android.JavaLibraryNameToSdkKind(ctx.ModuleName()); ok && android.InList(kind, apiXMLGeneratingApiSurfaces) {
1299 scopePrefix := AllApiScopes.matchingScopeFromSdkKind(kind).apiFilePrefix
1300 j.apiXmlFile = android.PathForModuleOut(ctx, fmt.Sprintf("%sapi.xml", scopePrefix))
1301 ctx.Build(pctx, android.BuildParams{
1302 Rule: generateApiXMLRule,
1303 // LOCAL_SOONG_CLASSES_JAR
1304 Input: j.implementationAndResourcesJar,
1305 Output: j.apiXmlFile,
1306 })
Jihoon Kang1262e202025-02-07 22:46:09 +00001307 ctx.DistForGoal("dist_files", j.apiXmlFile)
1308 }
1309}
1310
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001311const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001312 aidlIncludeDir = "aidl"
1313 javaDir = "java"
1314 jarFileSuffix = ".jar"
1315 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001316)
1317
Paul Duffina0dbf432019-12-05 11:25:53 +00001318// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +00001319func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +00001320 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001321}
1322
Paul Duffina04c1072020-03-02 10:16:35 +00001323func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
1324 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001325}
1326
Paul Duffin13879572019-11-28 14:31:38 +00001327type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +00001328 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +00001329
1330 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001331 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +00001332 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
1333
1334 // Function to compute the snapshot relative path to which the named library's
1335 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +00001336 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +00001337
1338 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
1339 // files like aidl files should also be copied.
1340 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +00001341}
1342
Paul Duffindb170e42020-12-08 17:48:25 +00001343const (
1344 onlyCopyJarToSnapshot = true
1345 copyEverythingToSnapshot = false
1346)
1347
Paul Duffin296701e2021-07-14 10:29:36 +01001348func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1349 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +00001350}
1351
1352func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
1353 _, ok := module.(*Library)
1354 return ok
1355}
1356
Paul Duffin3a4eb502020-03-19 16:11:18 +00001357func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1358 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001359}
Paul Duffina0dbf432019-12-05 11:25:53 +00001360
Paul Duffin14eb4672020-03-02 11:33:02 +00001361func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +00001362 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +00001363}
1364
1365type librarySdkMemberProperties struct {
1366 android.SdkMemberPropertiesBase
1367
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001368 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +00001369 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +01001370
1371 // The list of permitted packages that need to be passed to the prebuilts as they are used to
1372 // create the updatable-bcp-packages.txt file.
1373 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +00001374
1375 // The value of the min_sdk_version property, translated into a number where possible.
1376 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001377
1378 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +00001379}
1380
Paul Duffin3a4eb502020-03-19 16:11:18 +00001381func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +00001382 j := variant.(*Library)
1383
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001384 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +00001385
Paul Duffina551a1c2020-03-17 21:04:24 +00001386 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +01001387
1388 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +00001389
1390 // If the min_sdk_version was set then add the canonical representation of the API level to the
1391 // snapshot.
Spandan Dasb9c58352024-05-13 18:29:45 +00001392 if j.overridableProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -07001393 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
1394 if err != nil {
1395 ctx.ModuleErrorf("%s", err)
1396 }
Paul Duffinbb638eb2022-11-26 13:36:38 +00001397 p.MinSdkVersion = proptools.StringPtr(canonical)
1398 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001399
1400 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
1401 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
1402 }
Paul Duffin14eb4672020-03-02 11:33:02 +00001403}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001404
Paul Duffin3a4eb502020-03-19 16:11:18 +00001405func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001406 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001407
Paul Duffindb170e42020-12-08 17:48:25 +00001408 memberType := ctx.MemberType().(*librarySdkMemberType)
1409
Paul Duffina551a1c2020-03-17 21:04:24 +00001410 exportedJar := p.JarToExport
1411 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +00001412 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +00001413 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +00001414
1415 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +00001416 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
1417
Paul Duffina551a1c2020-03-17 21:04:24 +00001418 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
1419 }
1420
Paul Duffinbb638eb2022-11-26 13:36:38 +00001421 if p.MinSdkVersion != nil {
1422 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
1423 }
1424
Paul Duffin869de142021-07-15 14:14:41 +01001425 if len(p.PermittedPackages) > 0 {
1426 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
1427 }
1428
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001429 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
1430 if p.DexPreoptProfileGuided != nil {
1431 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
1432 }
1433
Paul Duffindb170e42020-12-08 17:48:25 +00001434 // Do not copy anything else to the snapshot.
1435 if memberType.onlyCopyJarToSnapshot {
1436 return
1437 }
1438
Paul Duffina551a1c2020-03-17 21:04:24 +00001439 aidlIncludeDirs := p.AidlIncludeDirs
1440 if len(aidlIncludeDirs) != 0 {
1441 sdkModuleContext := ctx.SdkModuleContext()
1442 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +00001443 // TODO(jiyong): copy parcelable declarations only
1444 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
1445 for _, file := range aidlFiles {
1446 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
1447 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001448 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001449
Paul Duffina551a1c2020-03-17 21:04:24 +00001450 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +00001451 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001452}
1453
Colin Cross1b16b0e2019-02-12 14:41:32 -08001454// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
1455//
1456// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
1457// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
1458// as a `static_libs` dependency of another module.
1459//
1460// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
1461// a device.
1462//
1463// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1464// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -07001465func LibraryFactory() android.Module {
1466 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -07001467
Colin Crossce6734e2020-06-15 16:09:53 -07001468 module.addHostAndDeviceProperties()
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001469 module.AddProperties(&module.sourceProperties)
Colin Cross2fe66872015-03-30 17:20:39 -07001470
Paul Duffin71b33cc2021-06-23 11:39:47 +01001471 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001472
Jiyong Park7f7766d2019-07-25 22:02:35 +09001473 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001474 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -07001475 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001476}
1477
Colin Cross1b16b0e2019-02-12 14:41:32 -08001478// java_library_static is an obsolete alias for java_library.
1479func LibraryStaticFactory() android.Module {
1480 return LibraryFactory()
1481}
1482
1483// java_library_host builds and links sources into a `.jar` file for the host.
1484//
1485// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
1486// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001487func LibraryHostFactory() android.Module {
1488 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -07001489
Colin Crossce6734e2020-06-15 16:09:53 -07001490 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -07001491
Colin Cross9ae1b922018-06-26 17:59:05 -07001492 module.Module.properties.Installable = proptools.BoolPtr(true)
1493
Jiyong Park7f7766d2019-07-25 22:02:35 +09001494 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001495 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -07001496 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001497}
1498
1499//
Colin Crossb628ea52018-08-14 16:42:33 -07001500// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -07001501//
1502
Dan Shi95d19422020-08-15 12:24:26 -07001503// Test option struct.
1504type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001505 android.CommonTestOptions
1506
Dan Shi95d19422020-08-15 12:24:26 -07001507 // a list of extra test configuration files that should be installed with the module.
1508 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -08001509
1510 // Extra <option> tags to add to the auto generated test xml file. The "key"
1511 // is optional in each of these.
1512 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +00001513
1514 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
1515 // The "key" is optional in each of these.
1516 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -07001517}
1518
Colin Cross05638fc2018-04-09 18:40:24 -07001519type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -07001520 // list of compatibility suites (for example "cts", "vts") that the module should be
1521 // installed into.
1522 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -07001523
1524 // the name of the test configuration (for example "AndroidTest.xml") that should be
1525 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -08001526 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -07001527
Jack He33338892018-09-19 02:21:28 -07001528 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
1529 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -08001530 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -07001531
Colin Crossd96ca352018-08-10 16:06:24 -07001532 // list of files or filegroup modules that provide data that should be installed alongside
1533 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +09001534 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001535
Cole Faust65cb40a2024-10-21 15:41:42 -07001536 // Same as data, but will add dependencies on modules using the device's os variation and
1537 // the common arch variation. Useful for a host test that wants to embed a module built for
1538 // device.
1539 Device_common_data []string `android:"path_device_common"`
1540
1541 // same as data, but adds dependencies using the device's os variation and the device's first
1542 // architecture's variation. Can be used to add a module built for device to the data of a
1543 // host test.
1544 Device_first_data []string `android:"path_device_first"`
1545
Cole Faust18f03f12024-10-23 14:51:11 -07001546 // same as data, but adds dependencies using the device's os variation and the device's first
1547 // 32-bit architecture's variation. If a 32-bit arch doesn't exist for this device, it will use
1548 // a 64 bit arch instead. Can be used to add a module built for device to the data of a
1549 // host test.
1550 Device_first_prefer32_data []string `android:"path_device_first_prefer32"`
1551
Colin Crossb3614422025-02-18 15:18:18 -08001552 // Same as data, but will add dependencies on modules using the host's os variation and
1553 // the common arch variation. Useful for a device test that wants to depend on a host
1554 // module, for example to include a custom Tradefed test runner.
1555 Host_common_data []string `android:"path_host_common"`
1556
Dan Shi6ffaaa82019-09-26 11:41:36 -07001557 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1558 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1559 // explicitly.
1560 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +08001561
1562 // Add parameterized mainline modules to auto generated test config. The options will be
1563 // handled by TradeFed to do downloading and installing the specified modules on the device.
1564 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -07001565
1566 // Test options.
1567 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -08001568
1569 // Names of modules containing JNI libraries that should be installed alongside the test.
Jihoon Kang6d39c702024-09-30 20:50:38 +00001570 Jni_libs proptools.Configurable[[]string]
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001571
1572 // Install the test into a folder named for the module in all test suites.
1573 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -07001574}
1575
Liz Kammerdd849a82020-06-12 16:38:45 -07001576type hostTestProperties struct {
1577 // list of native binary modules that should be installed alongside the test
1578 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +00001579
1580 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +00001581 // This property only adds the first variant of the dependency
1582 Data_device_bins_first []string `android:"arch_variant"`
1583
1584 // list of device binary modules that should be installed alongside the test
1585 // This property adds 64bit AND 32bit variants of the dependency
1586 Data_device_bins_both []string `android:"arch_variant"`
1587
1588 // list of device binary modules that should be installed alongside the test
1589 // This property only adds 64bit variants of the dependency
1590 Data_device_bins_64 []string `android:"arch_variant"`
1591
1592 // list of device binary modules that should be installed alongside the test
1593 // This property adds 32bit variants of the dependency if available, or else
1594 // defaults to the 64bit variant
1595 Data_device_bins_prefer32 []string `android:"arch_variant"`
1596
1597 // list of device binary modules that should be installed alongside the test
1598 // This property only adds 32bit variants of the dependency
1599 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001600}
1601
Paul Duffin42df1442019-03-20 12:45:53 +00001602type testHelperLibraryProperties struct {
1603 // list of compatibility suites (for example "cts", "vts") that the module should be
1604 // installed into.
1605 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001606
1607 // Install the test into a folder named for the module in all test suites.
1608 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001609}
1610
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001611type prebuiltTestProperties struct {
1612 // list of compatibility suites (for example "cts", "vts") that the module should be
1613 // installed into.
1614 Test_suites []string `android:"arch_variant"`
1615
1616 // the name of the test configuration (for example "AndroidTest.xml") that should be
1617 // installed with the module.
1618 Test_config *string `android:"path,arch_variant"`
1619}
1620
Colin Cross05638fc2018-04-09 18:40:24 -07001621type Test struct {
1622 Library
1623
1624 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001625
Dan Shi95d19422020-08-15 12:24:26 -07001626 testConfig android.Path
1627 extraTestConfigs android.Paths
1628 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001629}
1630
Liz Kammerdd849a82020-06-12 16:38:45 -07001631type TestHost struct {
1632 Test
1633
1634 testHostProperties hostTestProperties
1635}
1636
Paul Duffin42df1442019-03-20 12:45:53 +00001637type TestHelperLibrary struct {
1638 Library
1639
1640 testHelperLibraryProperties testHelperLibraryProperties
1641}
1642
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001643type JavaTestImport struct {
1644 Import
1645
1646 prebuiltTestProperties prebuiltTestProperties
1647
1648 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001649 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001650}
1651
Colin Cross24cc4be62021-11-03 14:09:41 -07001652func (j *Test) InstallInTestcases() bool {
1653 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1654 // testcases by base_rules.mk.
1655 return !j.Host()
1656}
1657
1658func (j *TestHelperLibrary) InstallInTestcases() bool {
1659 return true
1660}
1661
1662func (j *JavaTestImport) InstallInTestcases() bool {
1663 return true
1664}
1665
Colin Crosse1a85552024-06-14 12:17:37 -07001666func (j *TestHost) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Yu Liud8aa2002023-10-05 11:40:06 -07001667 return ctx.DeviceConfig().NativeCoverageEnabled()
1668}
1669
Sam Delmericocc271e22022-06-01 15:45:02 +00001670func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1671 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1672 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1673 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1674 }
1675
1676 var maybeAndroid32Target *android.Target
1677 var maybeAndroid64Target *android.Target
1678 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1679 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1680 if len(android32TargetList) > 0 {
1681 maybeAndroid32Target = &android32TargetList[0]
1682 }
1683 if len(android64TargetList) > 0 {
1684 maybeAndroid64Target = &android64TargetList[0]
1685 }
1686
1687 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1688 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1689 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1690 return
1691 }
1692 if maybeAndroid32Target != nil {
1693 ctx.AddFarVariationDependencies(
1694 maybeAndroid32Target.Variations(),
1695 dataDeviceBinsTag,
1696 j.testHostProperties.Data_device_bins_both...,
1697 )
1698 }
1699 if maybeAndroid64Target != nil {
1700 ctx.AddFarVariationDependencies(
1701 maybeAndroid64Target.Variations(),
1702 dataDeviceBinsTag,
1703 j.testHostProperties.Data_device_bins_both...,
1704 )
1705 }
1706 }
1707
1708 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1709 if maybeAndroid32Target != nil {
1710 ctx.AddFarVariationDependencies(
1711 maybeAndroid32Target.Variations(),
1712 dataDeviceBinsTag,
1713 j.testHostProperties.Data_device_bins_prefer32...,
1714 )
1715 } else {
1716 if maybeAndroid64Target == nil {
1717 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1718 return
1719 }
1720 ctx.AddFarVariationDependencies(
1721 maybeAndroid64Target.Variations(),
1722 dataDeviceBinsTag,
1723 j.testHostProperties.Data_device_bins_prefer32...,
1724 )
1725 }
1726 }
1727
1728 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1729 if maybeAndroid32Target == nil {
1730 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1731 return
1732 }
1733 deviceVariations := maybeAndroid32Target.Variations()
1734 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1735 }
1736
1737 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1738 if maybeAndroid64Target == nil {
1739 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1740 return
1741 }
1742 deviceVariations := maybeAndroid64Target.Variations()
1743 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1744 }
1745}
1746
Liz Kammerdd849a82020-06-12 16:38:45 -07001747func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1748 if len(j.testHostProperties.Data_native_bins) > 0 {
1749 for _, target := range ctx.MultiTargets() {
1750 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1751 }
1752 }
1753
Jihoon Kang6d39c702024-09-30 20:50:38 +00001754 jniLibs := j.testProperties.Jni_libs.GetOrDefault(ctx, nil)
1755 if len(jniLibs) > 0 {
Colin Crossf8d9c492021-01-26 11:01:43 -08001756 for _, target := range ctx.MultiTargets() {
1757 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
Jihoon Kang6d39c702024-09-30 20:50:38 +00001758 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, jniLibs...)
Colin Crossf8d9c492021-01-26 11:01:43 -08001759 }
1760 }
1761
Sam Delmericocc271e22022-06-01 15:45:02 +00001762 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001763 j.deps(ctx)
1764}
1765
Yuexi Ma627263f2021-03-04 13:47:56 -08001766func (j *TestHost) AddExtraResource(p android.Path) {
1767 j.extraResources = append(j.extraResources, p)
1768}
1769
Sam Delmericocc271e22022-06-01 15:45:02 +00001770func (j *TestHost) dataDeviceBins() []string {
1771 ret := make([]string, 0,
1772 len(j.testHostProperties.Data_device_bins_first)+
1773 len(j.testHostProperties.Data_device_bins_both)+
1774 len(j.testHostProperties.Data_device_bins_prefer32)+
1775 len(j.testHostProperties.Data_device_bins_32)+
1776 len(j.testHostProperties.Data_device_bins_64),
1777 )
1778
1779 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1780 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1781 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1782 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1783 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1784
1785 return ret
1786}
1787
Sam Delmericob3342ce2022-01-20 21:10:28 +00001788func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1789 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001790 dataDeviceBins := j.dataDeviceBins()
1791 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001792 // add Tradefed configuration to push device bins to device for testing
1793 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1794 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001795 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001796 fullPath := filepath.Join(remoteDir, bin)
1797 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1798 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001799 configs = append(configs, tradefed.Object{
1800 Type: "target_preparer",
1801 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1802 Options: options,
1803 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001804 }
1805
1806 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +00001807 android.SetProvider(ctx, tradefed.BaseTestProviderKey, tradefed.BaseTestProviderData{
Ronald Braunsteinf424c9a2024-10-22 01:41:20 +00001808 TestcaseRelDataFiles: testcaseRel(j.data),
1809 OutputFile: j.outputFile,
1810 TestConfig: j.testConfig,
1811 RequiredModuleNames: j.RequiredModuleNames(ctx),
1812 TestSuites: j.testProperties.Test_suites,
1813 IsHost: true,
1814 LocalSdkVersion: j.sdkVersion.String(),
1815 IsUnitTest: Bool(j.testProperties.Test_options.Unit_test),
1816 MkInclude: "$(BUILD_SYSTEM)/soong_java_prebuilt.mk",
1817 MkAppClass: "JAVA_LIBRARIES",
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +00001818 })
Jihoon Kangd4063812025-01-24 00:25:30 +00001819
1820 moduleInfoJSON := ctx.ModuleInfoJSON()
1821 if proptools.Bool(j.testProperties.Test_options.Unit_test) {
1822 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, "host-unit-tests")
1823 }
Sam Delmericob3342ce2022-01-20 21:10:28 +00001824}
1825
Colin Cross303e21f2018-08-07 16:49:25 -07001826func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Spandan Dasb0410872024-06-25 03:30:03 +00001827 checkMinSdkVersionMts(ctx, j.MinSdkVersion(ctx))
Sam Delmericob3342ce2022-01-20 21:10:28 +00001828 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1829}
1830
1831func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001832 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1833 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001834 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001835 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1836 }
Cole Faust21680542022-12-07 18:18:37 -08001837 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1838 TestConfigProp: j.testProperties.Test_config,
1839 TestConfigTemplateProp: j.testProperties.Test_config_template,
1840 TestSuites: j.testProperties.Test_suites,
1841 Config: configs,
1842 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001843 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001844 AutoGenConfig: j.testProperties.Auto_gen_config,
1845 UnitTest: j.testProperties.Test_options.Unit_test,
1846 DeviceTemplate: "${JavaTestConfigTemplate}",
1847 HostTemplate: "${JavaHostTestConfigTemplate}",
1848 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1849 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001850
Colin Cross8a497952019-03-05 22:25:09 -08001851 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Cole Faust65cb40a2024-10-21 15:41:42 -07001852 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_common_data)...)
1853 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_first_data)...)
Cole Faust18f03f12024-10-23 14:51:11 -07001854 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_first_prefer32_data)...)
Colin Crossb3614422025-02-18 15:18:18 -08001855 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Host_common_data)...)
Colin Cross303e21f2018-08-07 16:49:25 -07001856
Dan Shi95d19422020-08-15 12:24:26 -07001857 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1858
Yu Liu7eebf8b2025-01-17 00:23:57 +00001859 ctx.VisitDirectDepsProxyWithTag(dataNativeBinsTag, func(dep android.ModuleProxy) {
Liz Kammerdd849a82020-06-12 16:38:45 -07001860 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1861 })
1862
Yu Liu7eebf8b2025-01-17 00:23:57 +00001863 ctx.VisitDirectDepsProxyWithTag(dataDeviceBinsTag, func(dep android.ModuleProxy) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001864 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1865 })
1866
Colin Crossb614cd42024-10-11 12:52:21 -07001867 var directImplementationDeps android.Paths
1868 var transitiveImplementationDeps []depset.DepSet[android.Path]
Yu Liu7eebf8b2025-01-17 00:23:57 +00001869 ctx.VisitDirectDepsProxyWithTag(jniLibTag, func(dep android.ModuleProxy) {
Colin Cross313aa542023-12-13 13:47:44 -08001870 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
Colin Crossf8d9c492021-01-26 11:01:43 -08001871 if sharedLibInfo.SharedLibrary != nil {
1872 // Copy to an intermediate output directory to append "lib[64]" to the path,
1873 // so that it's compatible with the default rpath values.
1874 var relPath string
1875 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1876 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1877 } else {
1878 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1879 }
1880 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1881 ctx.Build(pctx, android.BuildParams{
1882 Rule: android.Cp,
1883 Input: sharedLibInfo.SharedLibrary,
1884 Output: relocatedLib,
1885 })
1886 j.data = append(j.data, relocatedLib)
Colin Crossb614cd42024-10-11 12:52:21 -07001887
1888 directImplementationDeps = append(directImplementationDeps, android.OutputFileForModule(ctx, dep, ""))
1889 if info, ok := android.OtherModuleProvider(ctx, dep, cc.ImplementationDepInfoProvider); ok {
1890 transitiveImplementationDeps = append(transitiveImplementationDeps, info.ImplementationDeps)
1891 }
Colin Crossf8d9c492021-01-26 11:01:43 -08001892 } else {
1893 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1894 }
1895 })
1896
Colin Crossb614cd42024-10-11 12:52:21 -07001897 android.SetProvider(ctx, cc.ImplementationDepInfoProvider, &cc.ImplementationDepInfo{
1898 ImplementationDeps: depset.New(depset.PREORDER, directImplementationDeps, transitiveImplementationDeps),
1899 })
1900
Colin Cross303e21f2018-08-07 16:49:25 -07001901 j.Library.GenerateAndroidBuildActions(ctx)
Jihoon Kangd4063812025-01-24 00:25:30 +00001902
1903 moduleInfoJSON := ctx.ModuleInfoJSON()
1904 // LOCAL_MODULE_TAGS
1905 moduleInfoJSON.Tags = append(moduleInfoJSON.Tags, "tests")
1906 var allTestConfigs android.Paths
1907 if j.testConfig != nil {
1908 allTestConfigs = append(allTestConfigs, j.testConfig)
1909 }
1910 allTestConfigs = append(allTestConfigs, j.extraTestConfigs...)
1911 if len(allTestConfigs) > 0 {
1912 moduleInfoJSON.TestConfig = allTestConfigs.Strings()
1913 } else {
1914 optionalConfig := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "AndroidTest.xml")
1915 if optionalConfig.Valid() {
1916 moduleInfoJSON.TestConfig = append(moduleInfoJSON.TestConfig, optionalConfig.String())
1917 }
1918 }
1919 if len(j.testProperties.Test_suites) > 0 {
1920 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, j.testProperties.Test_suites...)
1921 } else {
1922 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, "null-suite")
1923 }
1924 if _, ok := j.testConfig.(android.WritablePath); ok {
1925 moduleInfoJSON.AutoTestConfig = []string{"true"}
1926 }
1927 if proptools.Bool(j.testProperties.Test_options.Unit_test) {
1928 moduleInfoJSON.IsUnitTest = "true"
1929 if ctx.Host() {
1930 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, "host-unit-tests")
1931 }
1932 }
1933 moduleInfoJSON.TestMainlineModules = append(moduleInfoJSON.TestMainlineModules, j.testProperties.Test_mainline_modules...)
Jihoon Kang82197492025-01-29 19:30:31 +00001934
1935 // Install test deps
1936 if !ctx.Config().KatiEnabled() {
1937 pathInTestCases := android.PathForModuleInstall(ctx, "testcases", ctx.ModuleName())
1938 if j.testConfig != nil {
1939 ctx.InstallFile(pathInTestCases, ctx.ModuleName()+".config", j.testConfig)
1940 }
Cole Faustec71dfb2025-02-18 13:31:12 -08001941 dynamicConfig := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "DynamicConfig.xml")
1942 if dynamicConfig.Valid() {
1943 ctx.InstallFile(pathInTestCases, ctx.ModuleName()+".dynamic", dynamicConfig.Path())
1944 }
Jihoon Kang82197492025-01-29 19:30:31 +00001945 testDeps := append(j.data, j.extraTestConfigs...)
1946 for _, data := range android.SortedUniquePaths(testDeps) {
1947 dataPath := android.DataPath{SrcPath: data}
1948 ctx.InstallTestData(pathInTestCases, []android.DataPath{dataPath})
1949 }
Spandan Dasd718aa52025-02-04 21:18:36 +00001950 if j.outputFile != nil {
1951 ctx.InstallFile(pathInTestCases, ctx.ModuleName()+".jar", j.outputFile)
Jihoon Kang82197492025-01-29 19:30:31 +00001952 }
1953 }
Colin Cross05638fc2018-04-09 18:40:24 -07001954}
1955
Paul Duffin42df1442019-03-20 12:45:53 +00001956func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1957 j.Library.GenerateAndroidBuildActions(ctx)
Jihoon Kangd4063812025-01-24 00:25:30 +00001958
1959 moduleInfoJSON := ctx.ModuleInfoJSON()
1960 moduleInfoJSON.Tags = append(moduleInfoJSON.Tags, "tests")
1961 if len(j.testHelperLibraryProperties.Test_suites) > 0 {
1962 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, j.testHelperLibraryProperties.Test_suites...)
1963 } else {
1964 moduleInfoJSON.CompatibilitySuites = append(moduleInfoJSON.CompatibilitySuites, "null-suite")
1965 }
1966 optionalConfig := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "AndroidTest.xml")
1967 if optionalConfig.Valid() {
1968 moduleInfoJSON.TestConfig = append(moduleInfoJSON.TestConfig, optionalConfig.String())
1969 }
Paul Duffin42df1442019-03-20 12:45:53 +00001970}
1971
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001972func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001973 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1974 TestConfigProp: j.prebuiltTestProperties.Test_config,
1975 TestSuites: j.prebuiltTestProperties.Test_suites,
1976 DeviceTemplate: "${JavaTestConfigTemplate}",
1977 HostTemplate: "${JavaHostTestConfigTemplate}",
1978 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1979 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001980
1981 j.Import.GenerateAndroidBuildActions(ctx)
1982}
1983
1984type testSdkMemberType struct {
1985 android.SdkMemberTypeBase
1986}
1987
Paul Duffin296701e2021-07-14 10:29:36 +01001988func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1989 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001990}
1991
1992func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1993 _, ok := module.(*Test)
1994 return ok
1995}
1996
Paul Duffin3a4eb502020-03-19 16:11:18 +00001997func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1998 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001999}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002000
Paul Duffin14eb4672020-03-02 11:33:02 +00002001func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
2002 return &testSdkMemberProperties{}
2003}
2004
2005type testSdkMemberProperties struct {
2006 android.SdkMemberPropertiesBase
2007
Paul Duffina551a1c2020-03-17 21:04:24 +00002008 JarToExport android.Path
2009 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00002010}
2011
Paul Duffin3a4eb502020-03-19 16:11:18 +00002012func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00002013 test := variant.(*Test)
2014
2015 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002016 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00002017 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002018 }
2019
Paul Duffina551a1c2020-03-17 21:04:24 +00002020 p.JarToExport = implementationJars[0]
2021 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00002022}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002023
Paul Duffin3a4eb502020-03-19 16:11:18 +00002024func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00002025 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00002026
Paul Duffina551a1c2020-03-17 21:04:24 +00002027 exportedJar := p.JarToExport
2028 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00002029 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00002030 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00002031
2032 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00002033 }
2034
2035 testConfig := p.TestConfig
2036 if testConfig != nil {
2037 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
2038 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00002039 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
2040 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002041}
2042
Colin Cross1b16b0e2019-02-12 14:41:32 -08002043// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
2044// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
2045//
2046// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
2047// compiled against the device bootclasspath.
2048//
2049// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
2050// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07002051func TestFactory() android.Module {
2052 module := &Test{}
2053
Colin Crossce6734e2020-06-15 16:09:53 -07002054 module.addHostAndDeviceProperties()
2055 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07002056
Colin Cross9ae1b922018-06-26 17:59:05 -07002057 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08002058 module.Module.dexpreopter.isTest = true
Cole Faustc7315282025-01-10 15:37:01 -08002059 module.Module.linter.properties.Lint.Test_module_type = proptools.BoolPtr(true)
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07002060 module.Module.sourceProperties.Test_only = proptools.BoolPtr(true)
2061 module.Module.sourceProperties.Top_level_test_target = true
Colin Cross9ae1b922018-06-26 17:59:05 -07002062
Colin Cross05638fc2018-04-09 18:40:24 -07002063 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07002064 return module
2065}
2066
Paul Duffin42df1442019-03-20 12:45:53 +00002067// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
2068func TestHelperLibraryFactory() android.Module {
2069 module := &TestHelperLibrary{}
2070
Colin Crossce6734e2020-06-15 16:09:53 -07002071 module.addHostAndDeviceProperties()
2072 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00002073
Colin Cross9a4abed2019-04-24 13:19:28 -07002074 module.Module.properties.Installable = proptools.BoolPtr(true)
2075 module.Module.dexpreopter.isTest = true
Cole Faustc7315282025-01-10 15:37:01 -08002076 module.Module.linter.properties.Lint.Test_module_type = proptools.BoolPtr(true)
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07002077 module.Module.sourceProperties.Test_only = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07002078
Paul Duffin42df1442019-03-20 12:45:53 +00002079 InitJavaModule(module, android.HostAndDeviceSupported)
2080 return module
2081}
2082
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002083// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
2084// and makes sure that it is added to the appropriate test suite.
2085//
2086// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
2087// compiled against an Android classpath.
2088//
2089// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
2090// for host modules.
2091func JavaTestImportFactory() android.Module {
2092 module := &JavaTestImport{}
2093
2094 module.AddProperties(
2095 &module.Import.properties,
2096 &module.prebuiltTestProperties)
2097
2098 module.Import.properties.Installable = proptools.BoolPtr(true)
2099
2100 android.InitPrebuiltModule(module, &module.properties.Jars)
2101 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00002102 InitJavaModule(module, android.HostAndDeviceSupported)
2103 return module
2104}
2105
Colin Cross1b16b0e2019-02-12 14:41:32 -08002106// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
2107// allow running the test with `atest` or a `TEST_MAPPING` file.
2108//
2109// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
2110// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07002111func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07002112 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07002113
Colin Crossce6734e2020-06-15 16:09:53 -07002114 module.addHostProperties()
2115 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07002116 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07002117
Yuexi Ma627263f2021-03-04 13:47:56 -08002118 InitTestHost(
2119 module,
2120 proptools.BoolPtr(true),
2121 nil,
2122 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07002123
Liz Kammerdd849a82020-06-12 16:38:45 -07002124 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00002125
Colin Cross05638fc2018-04-09 18:40:24 -07002126 return module
2127}
2128
Yuexi Ma627263f2021-03-04 13:47:56 -08002129func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
2130 th.properties.Installable = installable
2131 th.testProperties.Auto_gen_config = autoGenConfig
2132 th.testProperties.Test_suites = testSuites
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07002133 th.sourceProperties.Test_only = proptools.BoolPtr(true)
2134 th.sourceProperties.Top_level_test_target = true
Yuexi Ma627263f2021-03-04 13:47:56 -08002135}
2136
Colin Cross05638fc2018-04-09 18:40:24 -07002137//
Colin Cross2fe66872015-03-30 17:20:39 -07002138// Java Binaries (.jar file plus wrapper script)
2139//
2140
Colin Crossf506d872017-07-19 15:53:04 -07002141type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07002142 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002143 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07002144
2145 // Name of the class containing main to be inserted into the manifest as Main-Class.
2146 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07002147
Spandan Dase42c5d92024-10-03 22:39:52 +00002148 // Names of modules containing JNI libraries that should be installed alongside the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002149 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07002150}
2151
Colin Crossf506d872017-07-19 15:53:04 -07002152type Binary struct {
2153 Library
Colin Cross2fe66872015-03-30 17:20:39 -07002154
Colin Crossf506d872017-07-19 15:53:04 -07002155 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07002156
Colin Crossc3315992017-12-08 19:12:36 -08002157 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07002158 binaryFile android.InstallPath
Spandan Dase42c5d92024-10-03 22:39:52 +00002159
2160 androidMkNamesOfJniLibs []string
Colin Cross2fe66872015-03-30 17:20:39 -07002161}
2162
Alex Light24237172017-10-26 09:46:21 -07002163func (j *Binary) HostToolPath() android.OptionalPath {
2164 return android.OptionalPathForPath(j.binaryFile)
2165}
2166
Colin Crossf506d872017-07-19 15:53:04 -07002167func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
yangbill2af0b6e2024-03-15 09:29:29 +00002168 j.stem = proptools.StringDefault(j.overridableProperties.Stem, ctx.ModuleName())
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002169
Cole Faustb9c67e22024-10-08 16:39:56 -07002170 // Handle the binary wrapper. This comes before compiling the jar so that the wrapper
2171 // is the first PackagingSpec
2172 if j.binaryProperties.Wrapper != nil {
2173 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Nan Zhang3c807db2017-11-03 14:53:31 -07002174 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002175 if ctx.Windows() {
Cole Faustb9c67e22024-10-08 16:39:56 -07002176 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002177 }
2178
Cole Faustb9c67e22024-10-08 16:39:56 -07002179 if ctx.Device() {
2180 // device binary should have a main_class property if it does not
2181 // have a specific wrapper, so that a default wrapper can
2182 // be generated for it.
2183 if j.binaryProperties.Main_class == nil {
2184 ctx.PropertyErrorf("main_class", "main_class property "+
2185 "is required for device binary if no default wrapper is assigned")
2186 } else {
2187 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
2188 jarName := j.Stem() + ".jar"
2189 partition := j.PartitionTag(ctx.DeviceConfig())
2190 ctx.Build(pctx, android.BuildParams{
2191 Rule: deviceBinaryWrapper,
2192 Output: wrapper,
2193 Args: map[string]string{
2194 "jar_name": jarName,
2195 "partition": partition,
2196 "main_class": String(j.binaryProperties.Main_class),
2197 },
2198 })
2199 j.wrapperFile = wrapper
Spandan Dase42c5d92024-10-03 22:39:52 +00002200 }
Cole Faustb9c67e22024-10-08 16:39:56 -07002201 } else {
2202 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
2203 }
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002204 }
Cole Faustb9c67e22024-10-08 16:39:56 -07002205
2206 ext := ""
2207 if ctx.Windows() {
2208 ext = ".bat"
2209 }
2210
2211 // The host installation rules make the installed wrapper depend on all the dependencies
2212 // of the wrapper variant, which will include the common variant's jar file and any JNI
2213 // libraries. This is verified by TestBinary. Also make it depend on the jar file so that
2214 // the binary file timestamp will update when the jar file timestamp does. The jar file is
2215 // built later on, in j.Library.GenerateAndroidBuildActions, so we have to create an identical
2216 // installpath representing it here.
2217 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
2218 ctx.ModuleName()+ext, j.wrapperFile, j.getJarInstallDir(ctx).Join(ctx, j.Stem()+".jar"))
2219
2220 // Set the jniLibs of this binary.
2221 // These will be added to `LOCAL_REQUIRED_MODULES`, and the kati packaging system will
2222 // install these alongside the java binary.
Yu Liucbb50c22025-01-15 20:57:49 +00002223 ctx.VisitDirectDepsProxyWithTag(jniInstallTag, func(jni android.ModuleProxy) {
Cole Faustb9c67e22024-10-08 16:39:56 -07002224 // Use the BaseModuleName of the dependency (without any prebuilt_ prefix)
Yu Liucbb50c22025-01-15 20:57:49 +00002225 commonInfo, _ := android.OtherModuleProvider(ctx, jni, android.CommonModuleInfoKey)
2226 j.androidMkNamesOfJniLibs = append(j.androidMkNamesOfJniLibs, commonInfo.BaseModuleName+":"+commonInfo.Target.Arch.ArchType.Bitness())
Cole Faustb9c67e22024-10-08 16:39:56 -07002227 })
2228 // Check that native libraries are not listed in `required`. Prompt users to use `jni_libs` instead.
Yu Liucbb50c22025-01-15 20:57:49 +00002229 ctx.VisitDirectDepsProxyWithTag(android.RequiredDepTag, func(dep android.ModuleProxy) {
Cole Faustb9c67e22024-10-08 16:39:56 -07002230 if _, hasSharedLibraryInfo := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider); hasSharedLibraryInfo {
2231 ctx.ModuleErrorf("cc_library %s is no longer supported in `required` of java_binary modules. Please use jni_libs instead.", dep.Name())
2232 }
2233 })
2234
2235 // Compile the jar
2236 if j.binaryProperties.Main_class != nil {
2237 if j.properties.Manifest != nil {
2238 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
2239 }
2240 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
2241 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
2242 j.overrideManifest = android.OptionalPathForPath(manifestFile)
2243 }
2244
2245 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross2fe66872015-03-30 17:20:39 -07002246}
2247
Colin Crossf506d872017-07-19 15:53:04 -07002248func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Cole Faustb9c67e22024-10-08 16:39:56 -07002249 j.deps(ctx)
Cole Faust3dac4862024-08-19 16:56:11 -07002250 // These dependencies ensure the installation rules will install the jar file when the
Spandan Dase42c5d92024-10-03 22:39:52 +00002251 // wrapper is installed, and the jni libraries when the wrapper is installed.
Cole Faustb9c67e22024-10-08 16:39:56 -07002252 if ctx.Os().Class == android.Host {
2253 ctx.AddVariationDependencies(ctx.Config().BuildOSTarget.Variations(), jniInstallTag, j.binaryProperties.Jni_libs...)
2254 } else if ctx.Os().Class == android.Device {
2255 ctx.AddVariationDependencies(ctx.Config().AndroidFirstDeviceTarget.Variations(), jniInstallTag, j.binaryProperties.Jni_libs...)
2256 } else {
2257 ctx.ModuleErrorf("Unknown os class")
Colin Cross6b4a32d2017-12-05 13:42:45 -08002258 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07002259}
2260
Colin Cross1b16b0e2019-02-12 14:41:32 -08002261// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
2262// as well.
2263//
2264// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
2265// compiled against the device bootclasspath.
2266//
2267// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
2268// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07002269func BinaryFactory() android.Module {
2270 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07002271
Colin Crossce6734e2020-06-15 16:09:53 -07002272 module.addHostAndDeviceProperties()
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07002273 module.AddProperties(&module.binaryProperties, &module.sourceProperties)
Colin Cross36242852017-06-23 15:06:31 -07002274
Colin Cross9ae1b922018-06-26 17:59:05 -07002275 module.Module.properties.Installable = proptools.BoolPtr(true)
2276
Cole Faustb9c67e22024-10-08 16:39:56 -07002277 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Colin Cross6b4a32d2017-12-05 13:42:45 -08002278 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08002279
Colin Cross36242852017-06-23 15:06:31 -07002280 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002281}
2282
Colin Cross1b16b0e2019-02-12 14:41:32 -08002283// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
2284//
2285// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
2286// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07002287func BinaryHostFactory() android.Module {
2288 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07002289
Colin Crossce6734e2020-06-15 16:09:53 -07002290 module.addHostProperties()
2291 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07002292
Colin Cross9ae1b922018-06-26 17:59:05 -07002293 module.Module.properties.Installable = proptools.BoolPtr(true)
2294
Cole Faustb9c67e22024-10-08 16:39:56 -07002295 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommon)
Colin Cross6b4a32d2017-12-05 13:42:45 -08002296 android.InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -07002297 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002298}
2299
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002300type JavaApiContribution struct {
2301 android.ModuleBase
2302 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00002303 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002304
2305 properties struct {
2306 // name of the API surface
2307 Api_surface *string
2308
2309 // relative path to the API signature text file
2310 Api_file *string `android:"path"`
2311 }
2312}
2313
2314func ApiContributionFactory() android.Module {
2315 module := &JavaApiContribution{}
2316 android.InitAndroidModule(module)
2317 android.InitDefaultableModule(module)
2318 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002319 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002320 return module
2321}
2322
2323type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00002324 ApiFile android.Path
2325 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002326}
2327
Colin Crossbc7d76c2023-12-12 16:39:03 -08002328var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]()
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002329
2330func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00002331 var apiFile android.Path = nil
2332 if apiFileString := ap.properties.Api_file; apiFileString != nil {
2333 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
2334 }
2335
Colin Cross40213022023-12-13 15:19:49 -08002336 android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00002337 ApiFile: apiFile,
2338 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002339 })
2340}
2341
2342type ApiLibrary struct {
2343 android.ModuleBase
2344 android.DefaultableModuleBase
2345
Spandan Dascb368ea2023-03-22 04:27:05 +00002346 hiddenAPI
2347 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00002348 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00002349
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002350 properties JavaApiLibraryProperties
2351
Jihoon Kang01e522c2023-03-14 01:09:34 +00002352 stubsSrcJar android.WritablePath
2353 stubsJar android.WritablePath
2354 stubsJarWithoutStaticLibs android.WritablePath
2355 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00002356 // .dex of stubs, used for hiddenapi processing
2357 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00002358
2359 validationPaths android.Paths
Jihoon Kang5d701272024-02-15 21:53:49 +00002360
2361 stubsType StubsType
2362
2363 aconfigProtoFiles android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002364}
2365
2366type JavaApiLibraryProperties struct {
2367 // name of the API surface
2368 Api_surface *string
2369
Jihoon Kang60d4a092022-11-17 23:47:43 +00002370 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00002371 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00002372 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002373
2374 // List of flags to be passed to the javac compiler to generate jar file
2375 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002376
2377 // List of shared java libs that this module has dependencies to and
2378 // should be passed as classpath in javac invocation
Cole Faustb7493472024-08-28 11:55:52 -07002379 Libs proptools.Configurable[[]string]
Jihoon Kange30fff02023-02-14 20:18:20 +00002380
2381 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00002382 // merge zipped after metalava invocation
Cole Faustb7493472024-08-28 11:55:52 -07002383 Static_libs proptools.Configurable[[]string]
Jihoon Kang01e522c2023-03-14 01:09:34 +00002384
Jihoon Kang862da6f2023-08-01 06:28:51 +00002385 // Version of previously released API file for compatibility check.
2386 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00002387
2388 // java_system_modules module providing the jar to be added to the
2389 // bootclasspath when compiling the stubs.
2390 // The jar will also be passed to metalava as a classpath to
2391 // generate compilable stubs.
2392 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00002393
2394 // If true, the module runs validation on the API signature files provided
2395 // by the modules passed via api_contributions by checking if the files are
2396 // in sync with the source Java files. However, the environment variable
2397 // DISABLE_STUB_VALIDATION has precedence over this property.
2398 Enable_validation *bool
Jihoon Kang5d701272024-02-15 21:53:49 +00002399
2400 // Type of stubs the module should generate. Must be one of "everything", "runtime" or
2401 // "exportable". Defaults to "everything".
2402 // - "everything" stubs include all non-flagged apis and flagged apis, regardless of the state
2403 // of the flag.
2404 // - "runtime" stubs include all non-flagged apis and flagged apis that are ENABLED or
2405 // READ_WRITE, and all other flagged apis are stripped.
2406 // - "exportable" stubs include all non-flagged apis and flagged apis that are ENABLED and
2407 // READ_ONLY, and all other flagged apis are stripped.
2408 Stubs_type *string
2409
2410 // List of aconfig_declarations module names that the stubs generated in this module
2411 // depend on.
2412 Aconfig_declarations []string
Paul Duffin27819362024-07-22 21:03:50 +01002413
2414 // List of hard coded filegroups containing Metalava config files that are passed to every
2415 // Metalava invocation that this module performs. See addMetalavaConfigFilesToCmd.
2416 ConfigFiles []string `android:"path" blueprint:"mutated"`
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002417
2418 // If not blank, set to the version of the sdk to compile against.
2419 // Defaults to an empty string, which compiles the module against the private platform APIs.
2420 // Values are of one of the following forms:
2421 // 1) numerical API level, "current", "none", or "core_platform"
2422 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
2423 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
2424 // If the SDK kind is empty, it will be set to public.
2425 Sdk_version *string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002426}
2427
2428func ApiLibraryFactory() android.Module {
2429 module := &ApiLibrary{}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002430 module.AddProperties(&module.properties)
Paul Duffin27819362024-07-22 21:03:50 +01002431 module.properties.ConfigFiles = getMetalavaConfigFilegroupReference()
2432 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002433 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00002434 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002435 return module
2436}
2437
2438func (al *ApiLibrary) ApiSurface() *string {
2439 return al.properties.Api_surface
2440}
2441
2442func (al *ApiLibrary) StubsJar() android.Path {
2443 return al.stubsJar
2444}
2445
2446func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00002447 srcs android.Paths, homeDir android.WritablePath,
Paul Duffind71dc402025-01-24 16:10:09 +00002448 classpath android.Paths, configFiles android.Paths, apiSurface *string) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002449 rule.Command().Text("rm -rf").Flag(homeDir.String())
2450 rule.Command().Text("mkdir -p").Flag(homeDir.String())
2451
2452 cmd := rule.Command()
2453 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
2454
2455 if metalavaUseRbe(ctx) {
2456 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
2457 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
2458 labels := map[string]string{"type": "tool", "name": "metalava"}
2459
2460 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
2461 rule.Rewrapper(&remoteexec.REParams{
2462 Labels: labels,
2463 ExecStrategy: execStrategy,
2464 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
2465 Platform: map[string]string{remoteexec.PoolKey: pool},
2466 })
2467 }
2468
2469 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
2470 Flag(config.JavacVmFlags).
2471 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002472 FlagWithInputList("--source-files ", srcs, " ")
2473
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02002474 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002475 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00002476 Flag("--include-annotations").
2477 // The flag makes nullability issues as warnings rather than errors by replacing
2478 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
2479 // and these packages are meant to have everything annotated
2480 // @RecentlyNullable/@RecentlyNonNull.
2481 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002482 FlagWithArg("--repeat-errors-max ", "10").
2483 FlagWithArg("--hide ", "UnresolvedImport").
2484 FlagWithArg("--hide ", "InvalidNullabilityOverride").
2485 FlagWithArg("--hide ", "ChangedDefault")
2486
Paul Duffin27819362024-07-22 21:03:50 +01002487 addMetalavaConfigFilesToCmd(cmd, configFiles)
2488
Paul Duffind71dc402025-01-24 16:10:09 +00002489 addOptionalApiSurfaceToCmd(cmd, apiSurface)
2490
Jihoon Kang4ec24872023-10-05 17:26:09 +00002491 if len(classpath) == 0 {
2492 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
2493 // classes on the classpath when an API file contains missing classes. However, as this command
2494 // does not specify `--classpath` this is not needed for that. However, this is also used as a
2495 // signal to the special metalava code for generating stubs from text files that it needs to add
2496 // some additional items into the API (e.g. default constructors).
2497 cmd.FlagWithArg("--api-class-resolution ", "api")
2498 } else {
2499 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
2500 cmd.FlagWithInputList("--classpath ", classpath, ":")
2501 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01002502
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002503 return cmd
2504}
2505
Jihoon Kang1bff0342023-01-17 20:40:22 +00002506func (al *ApiLibrary) HeaderJars() android.Paths {
2507 return android.Paths{al.stubsJar}
2508}
2509
2510func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
2511 return nil, nil
2512}
2513
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002514func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
2515 if stubsDir.Valid() {
2516 cmd.FlagWithArg("--stubs ", stubsDir.String())
2517 }
2518}
2519
Jihoon Kang063ec002023-06-28 01:16:23 +00002520func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
2521 for _, validationPath := range validationPaths {
2522 cmd.Validation(validationPath)
2523 }
2524}
2525
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002526func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00002527 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00002528 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
Jihoon Kang4f04df92024-01-30 02:30:06 +00002529 !ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") &&
Jihoon Kang063ec002023-06-28 01:16:23 +00002530 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00002531 for _, apiContributionName := range apiContributions {
2532 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00002533
2534 // Add the java_api_contribution module generating droidstubs module
2535 // as dependency when validation adding conditions are met and
2536 // the java_api_contribution module name has ".api.contribution" suffix.
2537 // All droidstubs-generated modules possess the suffix in the name,
2538 // but there is no such guarantee for tests.
2539 if addValidations {
2540 if strings.HasSuffix(apiContributionName, ".api.contribution") {
2541 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
2542 } else {
2543 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
2544 "current timestamp provider is not found for the api "+
2545 "contribution %s",
2546 ctx.ModuleName(),
2547 apiContributionName,
2548 )
2549 }
2550 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002551 }
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002552 if ctx.Device() {
2553 sdkDep := decodeSdkDep(ctx, android.SdkContext(al))
2554 if sdkDep.useModule {
2555 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
2556 ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
2557 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
2558
2559 }
2560 }
Cole Faustb7493472024-08-28 11:55:52 -07002561 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs.GetOrDefault(ctx, nil)...)
2562 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002563
Jihoon Kang5d701272024-02-15 21:53:49 +00002564 for _, aconfigDeclarationsName := range al.properties.Aconfig_declarations {
2565 ctx.AddDependency(ctx.Module(), aconfigDeclarationTag, aconfigDeclarationsName)
2566 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002567}
2568
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002569// Map where key is the api scope name and value is the int value
2570// representing the order of the api scope, narrowest to the widest
Jihoon Kang98aa8fa2024-06-07 11:06:57 +00002571var scopeOrderMap = AllApiScopes.MapToIndex(
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002572 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00002573
Paul Duffind01f0b22025-01-24 18:27:07 +00002574// Add some extra entries into scopeOrderMap for some special api surface names needed by libcore,
2575// external/conscrypt and external/icu and java/core-libraries.
2576func init() {
2577 count := len(scopeOrderMap)
2578 scopeOrderMap["core"] = count + 1
2579 scopeOrderMap["core-platform"] = count + 2
2580 scopeOrderMap["intra-core"] = count + 3
2581 scopeOrderMap["core-platform-plus-public"] = count + 4
Paul Duffin5f779162025-01-27 12:01:20 +00002582 scopeOrderMap["core-platform-legacy"] = count + 5
Paul Duffind01f0b22025-01-24 18:27:07 +00002583}
2584
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002585func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
2586 for _, srcFileInfo := range srcFilesInfo {
2587 if srcFileInfo.ApiSurface == "" {
2588 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00002589 }
2590 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002591 sort.Slice(srcFilesInfo, func(i, j int) bool {
2592 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
2593 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00002594
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002595 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00002596}
2597
Jihoon Kang5d701272024-02-15 21:53:49 +00002598var validstubsType = []StubsType{Everything, Runtime, Exportable}
2599
2600func (al *ApiLibrary) validateProperties(ctx android.ModuleContext) {
2601 if al.properties.Stubs_type == nil {
2602 ctx.ModuleErrorf("java_api_library module type must specify stubs_type property.")
2603 } else {
2604 al.stubsType = StringToStubsType(proptools.String(al.properties.Stubs_type))
2605 }
2606
2607 if !android.InList(al.stubsType, validstubsType) {
2608 ctx.PropertyErrorf("stubs_type", "%s is not a valid stubs_type property value. "+
2609 "Must be one of %s.", proptools.String(al.properties.Stubs_type), validstubsType)
2610 }
2611}
2612
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002613func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang5d701272024-02-15 21:53:49 +00002614 al.validateProperties(ctx)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002615
2616 rule := android.NewRuleBuilder(pctx, ctx)
2617
2618 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
2619 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
2620 SandboxInputs()
2621
Jihoon Kang063ec002023-06-28 01:16:23 +00002622 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002623 rule.Command().Text("rm -rf").Text(stubsDir.String())
2624 rule.Command().Text("mkdir -p").Text(stubsDir.String())
2625
2626 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
2627
Jihoon Kang8fe19822023-09-14 06:27:36 +00002628 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002629 var classPaths android.Paths
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002630 var bootclassPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00002631 var staticLibs android.Paths
Jihoon Kang4ec24872023-10-05 17:26:09 +00002632 var systemModulesPaths android.Paths
Yu Liucbb50c22025-01-15 20:57:49 +00002633 ctx.VisitDirectDepsProxy(func(dep android.ModuleProxy) {
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002634 tag := ctx.OtherModuleDependencyTag(dep)
2635 switch tag {
2636 case javaApiContributionTag:
Colin Cross313aa542023-12-13 13:47:44 -08002637 provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider)
Jihoon Kang8fe19822023-09-14 06:27:36 +00002638 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00002639 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
2640 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00002641 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002642 case libTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002643 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2644 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002645 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002646 }
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002647 case bootClasspathTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002648 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2649 bootclassPaths = append(bootclassPaths, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002650 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002651 }
Jihoon Kange30fff02023-02-14 20:18:20 +00002652 case staticLibTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002653 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2654 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002655 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002656 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00002657 case systemModulesTag:
Colin Crossb61c2262024-08-08 14:04:42 -07002658 if sm, ok := android.OtherModuleProvider(ctx, dep, SystemModulesProvider); ok {
2659 systemModulesPaths = append(systemModulesPaths, sm.HeaderJars...)
2660 }
Jihoon Kang063ec002023-06-28 01:16:23 +00002661 case metalavaCurrentApiTimestampTag:
Yu Liucbb50c22025-01-15 20:57:49 +00002662 if currentApiTimestampProvider, ok := android.OtherModuleProvider(ctx, dep, DroidStubsInfoProvider); ok {
2663 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp)
Jihoon Kang063ec002023-06-28 01:16:23 +00002664 }
Jihoon Kang5d701272024-02-15 21:53:49 +00002665 case aconfigDeclarationTag:
2666 if provider, ok := android.OtherModuleProvider(ctx, dep, android.AconfigDeclarationsProviderKey); ok {
2667 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.IntermediateCacheOutputPath)
Yu Liu67a28422024-03-05 00:36:31 +00002668 } else if provider, ok := android.OtherModuleProvider(ctx, dep, android.CodegenInfoProvider); ok {
Jihoon Kang5d701272024-02-15 21:53:49 +00002669 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.IntermediateCacheOutputPaths...)
2670 } else {
2671 ctx.ModuleErrorf("Only aconfig_declarations and aconfig_declarations_group "+
2672 "module type is allowed for flags_packages property, but %s is neither "+
2673 "of these supported module types",
2674 dep.Name(),
2675 )
2676 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002677 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00002678 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002679
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002680 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
2681 var srcFiles android.Paths
2682 for _, srcFileInfo := range srcFilesInfo {
2683 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00002684 }
2685
Jihoon Kang160634c2023-05-25 05:28:29 +00002686 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00002687 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
2688 }
2689
Paul Duffin27819362024-07-22 21:03:50 +01002690 configFiles := android.PathsForModuleSrc(ctx, al.properties.ConfigFiles)
2691
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002692 combinedPaths := append(([]android.Path)(nil), systemModulesPaths...)
2693 combinedPaths = append(combinedPaths, classPaths...)
2694 combinedPaths = append(combinedPaths, bootclassPaths...)
Paul Duffind71dc402025-01-24 16:10:09 +00002695 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, combinedPaths, configFiles, al.properties.Api_surface)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002696
2697 al.stubsFlags(ctx, cmd, stubsDir)
2698
Paul Duffin1b1eb9b2024-06-18 18:17:39 +01002699 previousApi := String(al.properties.Previous_api)
2700 if previousApi != "" {
2701 previousApiFiles := android.PathsForModuleSrc(ctx, []string{previousApi})
2702 cmd.FlagForEachInput("--migrate-nullness ", previousApiFiles)
Jihoon Kang862da6f2023-08-01 06:28:51 +00002703 }
2704
Jihoon Kang063ec002023-06-28 01:16:23 +00002705 al.addValidation(ctx, cmd, al.validationPaths)
2706
Jihoon Kang5d701272024-02-15 21:53:49 +00002707 generateRevertAnnotationArgs(ctx, cmd, al.stubsType, al.aconfigProtoFiles)
2708
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002709 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00002710 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
2711 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00002712
Jihoon Kangca198c22023-06-22 23:13:51 +00002713 rule.Command().
2714 BuiltTool("soong_zip").
2715 Flag("-write_if_changed").
2716 Flag("-jar").
2717 FlagWithOutput("-o ", al.stubsSrcJar).
2718 FlagWithArg("-C ", stubsDir.String()).
2719 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002720
Paul Duffin336b16a2023-08-15 23:10:13 +01002721 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00002722
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002723 javacFlags := javaBuilderFlags{
2724 javaVersion: getStubsJavaVersion(),
2725 javacFlags: strings.Join(al.properties.Javacflags, " "),
2726 classpath: classpath(classPaths),
2727 bootClasspath: classpath(append(systemModulesPaths, bootclassPaths...)),
Jihoon Kangca198c22023-06-22 23:13:51 +00002728 }
Jihoon Kang423d2292022-11-29 23:10:10 +00002729
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002730 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
2731
2732 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
2733 android.Paths{al.stubsSrcJar}, annoSrcJar, javacFlags, android.Paths{})
2734
Jihoon Kange30fff02023-02-14 20:18:20 +00002735 builder := android.NewRuleBuilder(pctx, ctx)
2736 builder.Command().
2737 BuiltTool("merge_zips").
2738 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00002739 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00002740 Inputs(staticLibs)
2741 builder.Build("merge_zips", "merge jar files")
2742
Spandan Dascb368ea2023-03-22 04:27:05 +00002743 // compile stubs to .dex for hiddenapi processing
2744 dexParams := &compileDexParams{
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002745 flags: javacFlags,
Spandan Dascb368ea2023-03-22 04:27:05 +00002746 sdkVersion: al.SdkVersion(ctx),
2747 minSdkVersion: al.MinSdkVersion(ctx),
2748 classesJar: al.stubsJar,
2749 jarName: ctx.ModuleName() + ".jar",
2750 }
Spandan Das3dbda182024-05-20 22:23:10 +00002751 dexOutputFile, _ := al.dexer.compileDex(ctx, dexParams)
Spandan Dascb368ea2023-03-22 04:27:05 +00002752 uncompressed := true
2753 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2754 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2755 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2756
Jihoon Kang423d2292022-11-29 23:10:10 +00002757 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002758
Yu Liu460cf372025-01-10 00:34:06 +00002759 javaInfo := &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002760 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2761 LocalHeaderJars: android.PathsIfNonNil(al.stubsJar),
Colin Crossa14fb6a2024-10-23 16:57:06 -07002762 TransitiveStaticLibsHeaderJars: depset.New(depset.PREORDER, android.PathsIfNonNil(al.stubsJar), nil),
2763 TransitiveStaticLibsImplementationJars: depset.New(depset.PREORDER, android.PathsIfNonNil(al.stubsJar), nil),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002764 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2765 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2766 AidlIncludeDirs: android.Paths{},
2767 StubsLinkType: Stubs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002768 // No aconfig libraries on api libraries
Yu Liu460cf372025-01-10 00:34:06 +00002769 }
2770 setExtraJavaInfo(ctx, al, javaInfo)
2771 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002772}
2773
Spandan Das59a4a2b2024-01-09 21:35:56 +00002774func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dascb368ea2023-03-22 04:27:05 +00002775 return al.dexJarFile
2776}
2777
2778func (al *ApiLibrary) DexJarInstallPath() android.Path {
2779 return al.dexJarFile.Path()
2780}
2781
2782func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2783 return nil
2784}
2785
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002786// Most java_api_library constitues the sdk, but there are some java_api_library that
2787// does not contribute to the api surface. Such modules are allowed to set sdk_version
2788// other than "none"
Spandan Dascb368ea2023-03-22 04:27:05 +00002789func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002790 return android.SdkSpecFrom(ctx, proptools.String(al.properties.Sdk_version))
Spandan Dascb368ea2023-03-22 04:27:05 +00002791}
2792
2793// java_api_library is always at "current". Return FutureApiLevel
2794func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002795 return al.SdkVersion(ctx).ApiLevel
2796}
2797
2798func (al *ApiLibrary) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
2799 return al.SdkVersion(ctx).ApiLevel
2800}
2801
2802func (al *ApiLibrary) SystemModules() string {
2803 return proptools.String(al.properties.System_modules)
2804}
2805
2806func (al *ApiLibrary) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2807 return al.SdkVersion(ctx).ApiLevel
Spandan Dascb368ea2023-03-22 04:27:05 +00002808}
2809
Cole Faustb36d31d2024-08-27 16:04:28 -07002810func (al *ApiLibrary) IDEInfo(ctx android.BaseModuleContext, i *android.IdeInfo) {
2811 i.Deps = append(i.Deps, al.ideDeps(ctx)...)
Cole Faustb7493472024-08-28 11:55:52 -07002812 i.Libs = append(i.Libs, al.properties.Libs.GetOrDefault(ctx, nil)...)
2813 i.Static_libs = append(i.Static_libs, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Spandan Das4ae68012024-07-18 19:35:31 +00002814 i.SrcJars = append(i.SrcJars, al.stubsSrcJar.String())
2815}
2816
2817// deps of java_api_library for module_bp_java_deps.json
Cole Faustb36d31d2024-08-27 16:04:28 -07002818func (al *ApiLibrary) ideDeps(ctx android.BaseModuleContext) []string {
Spandan Das4ae68012024-07-18 19:35:31 +00002819 ret := []string{}
Cole Faustb7493472024-08-28 11:55:52 -07002820 ret = append(ret, al.properties.Libs.GetOrDefault(ctx, nil)...)
2821 ret = append(ret, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Spandan Das4f443e72024-10-17 00:04:19 +00002822 if proptools.StringDefault(al.properties.System_modules, "none") != "none" {
Spandan Das4ae68012024-07-18 19:35:31 +00002823 ret = append(ret, proptools.String(al.properties.System_modules))
2824 }
Spandan Das4ae68012024-07-18 19:35:31 +00002825 // Other non java_library dependencies like java_api_contribution are ignored for now.
2826 return ret
2827}
2828
Spandan Dascb368ea2023-03-22 04:27:05 +00002829// implement the following interfaces for hiddenapi processing
2830var _ hiddenAPIModule = (*ApiLibrary)(nil)
2831var _ UsesLibraryDependency = (*ApiLibrary)(nil)
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002832var _ android.SdkContext = (*ApiLibrary)(nil)
Spandan Dascb368ea2023-03-22 04:27:05 +00002833
Spandan Das4ae68012024-07-18 19:35:31 +00002834// implement the following interface for IDE completion.
2835var _ android.IDEInfo = (*ApiLibrary)(nil)
2836
Colin Cross2fe66872015-03-30 17:20:39 -07002837//
2838// Java prebuilts
2839//
2840
Colin Cross74d73e22017-08-02 11:05:49 -07002841type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002842 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002843
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002844 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2845 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002846 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002847
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002848 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2849 // specified.
2850 Min_sdk_version *string
2851
William Loh5a082f92022-05-17 20:21:50 +00002852 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2853 // and uses-permission tags in manifest_fixer.
2854 Replace_max_sdk_version_placeholder *string
2855
Colin Cross535e2cf2017-10-20 17:57:49 -07002856 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002857
Paul Duffin869de142021-07-15 14:14:41 +01002858 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002859 Permitted_packages []string
2860
Jiyong Park1be96912018-05-28 18:02:19 +09002861 // List of shared java libs that this module has dependencies to
2862 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002863
Colin Crossdad2a362024-03-23 04:43:41 +00002864 // List of static java libs that this module has dependencies to
Cole Faustb7493472024-08-28 11:55:52 -07002865 Static_libs proptools.Configurable[[]string]
Colin Crossdad2a362024-03-23 04:43:41 +00002866
Colin Cross37f6d792018-07-12 12:28:41 -07002867 // List of files to remove from the jar file(s)
2868 Exclude_files []string
2869
2870 // List of directories to remove from the jar file(s)
2871 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002872
2873 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002874 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002875
2876 // set the name of the output
2877 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002878
2879 Aidl struct {
2880 // directories that should be added as include directories for any aidl sources of modules
2881 // that depend on this module, as well as to aidl for this module.
2882 Export_include_dirs []string
2883 }
Spandan Das3cf04632024-01-19 00:22:22 +00002884
2885 // Name of the source soong module that gets shadowed by this prebuilt
2886 // If unspecified, follows the naming convention that the source module of
2887 // the prebuilt is Name() without "prebuilt_" prefix
2888 Source_module_name *string
Spandan Das23956d12024-01-19 00:22:22 +00002889
2890 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2891 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2892 // (without any prebuilt_ prefix)
2893 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002894
2895 // Property signifying whether the module provides stubs jar or not.
2896 Is_stubs_module *bool
Colin Cross74d73e22017-08-02 11:05:49 -07002897}
2898
2899type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002900 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002901 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002902 android.ApexModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002903 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002904
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002905 // Functionality common to Module and Import.
2906 embeddableInModuleAndImport
2907
Liz Kammerd6c31d22020-08-05 15:40:41 -07002908 hiddenAPI
2909 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002910 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002911
Colin Cross74d73e22017-08-02 11:05:49 -07002912 properties ImportProperties
2913
Liz Kammerd6c31d22020-08-05 15:40:41 -07002914 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002915 dexJarFile OptionalDexJarPath
Spandan Dasfae468e2023-12-12 23:23:53 +00002916 dexJarFileErr error
Jeongik Chad5fe8782021-07-08 01:13:11 +09002917 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002918
Colin Crossdad2a362024-03-23 04:43:41 +00002919 combinedImplementationFile android.Path
2920 combinedHeaderFile android.Path
2921 classLoaderContexts dexpreopt.ClassLoaderContextMap
2922 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002923
2924 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002925
2926 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002927 minSdkVersion android.ApiLevel
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002928
2929 stubsLinkType StubsLinkType
Colin Cross2fe66872015-03-30 17:20:39 -07002930}
2931
Paul Duffin630b11e2021-07-15 13:35:26 +01002932var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2933
2934func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2935 return j.properties.Permitted_packages
2936}
2937
Jiyong Park92315372021-04-02 08:45:46 +09002938func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2939 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002940}
2941
Jiyong Parkf1691d22021-03-29 20:11:58 +09002942func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002943 return "none"
2944}
2945
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002946func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002947 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002948 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002949 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002950 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002951}
2952
Spandan Dasa26eda72023-03-02 00:56:06 +00002953func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002954 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002955 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002956 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002957 // Default is PrivateApiLevel
2958 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002959}
2960
Spandan Dasca70fc42023-03-01 23:38:49 +00002961func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2962 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002963}
2964
Colin Cross74d73e22017-08-02 11:05:49 -07002965func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002966 return &j.prebuilt
2967}
2968
Colin Cross74d73e22017-08-02 11:05:49 -07002969func (j *Import) PrebuiltSrcs() []string {
2970 return j.properties.Jars
2971}
2972
Spandan Das3cf04632024-01-19 00:22:22 +00002973func (j *Import) BaseModuleName() string {
2974 return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name())
2975}
2976
Colin Cross74d73e22017-08-02 11:05:49 -07002977func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002978 return j.prebuilt.Name(j.ModuleBase.Name())
2979}
2980
Jiyong Park0b238752019-10-29 11:23:10 +09002981func (j *Import) Stem() string {
Spandan Das3cf04632024-01-19 00:22:22 +00002982 return proptools.StringDefault(j.properties.Stem, j.BaseModuleName())
Jiyong Park0b238752019-10-29 11:23:10 +09002983}
2984
Spandan Das23956d12024-01-19 00:22:22 +00002985func (j *Import) CreatedByJavaSdkLibraryName() *string {
2986 return j.properties.Created_by_java_sdk_library_name
2987}
2988
Jiyong Park618922e2020-01-08 13:35:43 +09002989func (a *Import) JacocoReportClassesFile() android.Path {
2990 return nil
2991}
2992
Colin Cross74d73e22017-08-02 11:05:49 -07002993func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002994 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Cole Faustb7493472024-08-28 11:55:52 -07002995 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs.GetOrDefault(ctx, nil)...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002996
2997 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002998 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002999 }
Colin Cross1e676be2016-10-12 14:38:15 -07003000}
3001
Sam Delmerico277795c2022-02-25 17:04:37 +00003002func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09003003 j.sdkVersion = j.SdkVersion(ctx)
3004 j.minSdkVersion = j.MinSdkVersion(ctx)
3005
Colin Crossff694a82023-12-13 15:54:49 -08003006 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
3007 if !apexInfo.IsForPlatform() {
Colin Cross56a83212020-09-15 18:30:11 -07003008 j.hideApexVariantFromMake = true
3009 }
3010
Dan Willemsen8e6b3712021-09-20 23:11:24 -07003011 if ctx.Windows() {
3012 j.HideFromMake()
3013 }
Jihoon Kangfe914ed2024-02-12 22:49:21 +00003014
3015 if proptools.Bool(j.properties.Is_stubs_module) {
3016 j.stubsLinkType = Stubs
3017 } else {
3018 j.stubsLinkType = Implementation
3019 }
Sam Delmerico277795c2022-02-25 17:04:37 +00003020}
3021
3022func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3023 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07003024
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01003025 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01003026
Liz Kammerd6c31d22020-08-05 15:40:41 -07003027 var flags javaBuilderFlags
3028
Colin Crossa14fb6a2024-10-23 16:57:06 -07003029 var transitiveClasspathHeaderJars []depset.DepSet[android.Path]
3030 var transitiveBootClasspathHeaderJars []depset.DepSet[android.Path]
3031 var transitiveStaticLibsHeaderJars []depset.DepSet[android.Path]
3032 var transitiveStaticLibsImplementationJars []depset.DepSet[android.Path]
3033 var transitiveStaticLibsResourceJars []depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003034
Colin Cross9ffaf282024-08-12 13:50:09 -07003035 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossdad2a362024-03-23 04:43:41 +00003036 var staticJars android.Paths
Colin Cross53529a92024-08-15 17:11:18 -07003037 var staticResourceJars android.Paths
Colin Crossdad2a362024-03-23 04:43:41 +00003038 var staticHeaderJars android.Paths
Yu Liu39f5fb32025-01-13 23:52:19 +00003039 ctx.VisitDirectDepsProxy(func(module android.ModuleProxy) {
Jiyong Park1be96912018-05-28 18:02:19 +09003040 tag := ctx.OtherModuleDependencyTag(module)
Colin Cross313aa542023-12-13 13:47:44 -08003041 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09003042 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04003043 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07003044 flags.classpath = append(flags.classpath, dep.HeaderJars...)
3045 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07003046 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07003047 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08003048 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Colin Cross53529a92024-08-15 17:11:18 -07003049 staticJars = append(staticJars, dep.ImplementationJars...)
3050 staticResourceJars = append(staticResourceJars, dep.ResourceJars...)
Colin Crossdad2a362024-03-23 04:43:41 +00003051 staticHeaderJars = append(staticHeaderJars, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07003052 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
3053 transitiveStaticLibsHeaderJars = append(transitiveStaticLibsHeaderJars, dep.TransitiveStaticLibsHeaderJars)
3054 transitiveStaticLibsImplementationJars = append(transitiveStaticLibsImplementationJars, dep.TransitiveStaticLibsImplementationJars)
3055 transitiveStaticLibsResourceJars = append(transitiveStaticLibsResourceJars, dep.TransitiveStaticLibsResourceJars)
Liz Kammerd6c31d22020-08-05 15:40:41 -07003056 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08003057 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07003058 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
Jiyong Park1be96912018-05-28 18:02:19 +09003059 }
Jihoon Kang98e9ac62024-09-25 23:42:30 +00003060 } else if _, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09003061 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04003062 case libTag, sdkLibTag:
Jihoon Kangc4db1092024-09-18 23:10:55 +00003063 sdkInfo, _ := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider)
3064 generatingLibsString := android.PrettyConcat(
3065 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
3066 ctx.ModuleErrorf("cannot depend directly on java_sdk_library %q; try depending on %s instead", module.Name(), generatingLibsString)
Jiyong Park1be96912018-05-28 18:02:19 +09003067 }
3068 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003069
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003070 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09003071 })
3072
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003073 localJars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crossdad2a362024-03-23 04:43:41 +00003074 jarName := j.Stem() + ".jar"
3075
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003076 // Combine only the local jars together for use in transitive classpaths.
3077 // Always pass input jar through TransformJarsToJar to strip module-info.class from prebuilts.
3078 localCombinedHeaderJar := android.PathForModuleOut(ctx, "local-combined", jarName)
3079 TransformJarsToJar(ctx, localCombinedHeaderJar, "combine local prebuilt implementation jars", localJars, android.OptionalPath{},
3080 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
3081 localStrippedJars := android.Paths{localCombinedHeaderJar}
3082
Colin Crossa14fb6a2024-10-23 16:57:06 -07003083 completeStaticLibsHeaderJars := depset.New(depset.PREORDER, localStrippedJars, transitiveStaticLibsHeaderJars)
3084 completeStaticLibsImplementationJars := depset.New(depset.PREORDER, localStrippedJars, transitiveStaticLibsImplementationJars)
3085 completeStaticLibsResourceJars := depset.New(depset.PREORDER, nil, transitiveStaticLibsResourceJars)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003086
Colin Crossdad2a362024-03-23 04:43:41 +00003087 // Always pass the input jars to TransformJarsToJar, even if there is only a single jar, we need the output
3088 // file of the module to be named jarName.
Colin Cross77965d92024-08-15 17:11:08 -07003089 var outputFile android.Path
3090 combinedImplementationJar := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross8ff4af32025-02-19 15:17:02 -08003091 implementationJars := completeStaticLibsImplementationJars.ToList()
Colin Cross77965d92024-08-15 17:11:08 -07003092 TransformJarsToJar(ctx, combinedImplementationJar, "combine prebuilt implementation jars", implementationJars, android.OptionalPath{},
Colin Crossdad2a362024-03-23 04:43:41 +00003093 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross77965d92024-08-15 17:11:08 -07003094 outputFile = combinedImplementationJar
Colin Crossdad2a362024-03-23 04:43:41 +00003095
3096 // If no dependencies have separate header jars then there is no need to create a separate
3097 // header jar for this module.
3098 reuseImplementationJarAsHeaderJar := slices.Equal(staticJars, staticHeaderJars)
3099
Colin Cross53529a92024-08-15 17:11:18 -07003100 var resourceJarFile android.Path
3101 if len(staticResourceJars) > 1 {
3102 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
3103 TransformJarsToJar(ctx, combinedJar, "for resources", staticResourceJars, android.OptionalPath{},
3104 false, nil, nil)
3105 resourceJarFile = combinedJar
3106 } else if len(staticResourceJars) == 1 {
3107 resourceJarFile = staticResourceJars[0]
3108 }
3109
Colin Cross77965d92024-08-15 17:11:08 -07003110 var headerJar android.Path
Colin Crossdad2a362024-03-23 04:43:41 +00003111 if reuseImplementationJarAsHeaderJar {
Colin Cross77965d92024-08-15 17:11:08 -07003112 headerJar = outputFile
Colin Crossdad2a362024-03-23 04:43:41 +00003113 } else {
Colin Cross8ff4af32025-02-19 15:17:02 -08003114 headerJars := completeStaticLibsHeaderJars.ToList()
Colin Cross77965d92024-08-15 17:11:08 -07003115 headerOutputFile := android.PathForModuleOut(ctx, "turbine-combined", jarName)
Colin Crossdad2a362024-03-23 04:43:41 +00003116 TransformJarsToJar(ctx, headerOutputFile, "combine prebuilt header jars", headerJars, android.OptionalPath{},
3117 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross77965d92024-08-15 17:11:08 -07003118 headerJar = headerOutputFile
Colin Crossdad2a362024-03-23 04:43:41 +00003119 }
3120
3121 if Bool(j.properties.Jetifier) {
Colin Cross77965d92024-08-15 17:11:08 -07003122 jetifierOutputFile := android.PathForModuleOut(ctx, "jetifier", jarName)
3123 TransformJetifier(ctx, jetifierOutputFile, outputFile)
3124 outputFile = jetifierOutputFile
Colin Crossdad2a362024-03-23 04:43:41 +00003125
3126 if !reuseImplementationJarAsHeaderJar {
Colin Cross77965d92024-08-15 17:11:08 -07003127 jetifierHeaderJar := android.PathForModuleOut(ctx, "jetifier-headers", jarName)
3128 TransformJetifier(ctx, jetifierHeaderJar, headerJar)
3129 headerJar = jetifierHeaderJar
Colin Crossdad2a362024-03-23 04:43:41 +00003130 } else {
Colin Cross77965d92024-08-15 17:11:08 -07003131 headerJar = outputFile
Colin Crossdad2a362024-03-23 04:43:41 +00003132 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003133
3134 // Enabling jetifier requires modifying classes from transitive dependencies, disable transitive
3135 // classpath and use the combined header jar instead.
Colin Crossa14fb6a2024-10-23 16:57:06 -07003136 completeStaticLibsHeaderJars = depset.New(depset.PREORDER, android.Paths{headerJar}, nil)
3137 completeStaticLibsImplementationJars = depset.New(depset.PREORDER, android.Paths{outputFile}, nil)
Colin Crossdad2a362024-03-23 04:43:41 +00003138 }
Colin Cross5e87f342024-04-11 15:28:18 -07003139
Colin Cross53529a92024-08-15 17:11:18 -07003140 implementationJarFile := outputFile
3141
3142 // merge implementation jar with resources if necessary
3143 if resourceJarFile != nil {
3144 jars := android.Paths{resourceJarFile, outputFile}
3145 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
3146 TransformJarsToJar(ctx, combinedJar, "for resources", jars, android.OptionalPath{},
3147 false, nil, nil)
3148 outputFile = combinedJar
3149 }
3150
Luca Stefani172c56d2024-12-17 14:19:09 +01003151 proguardFlags := android.PathForModuleOut(ctx, "proguard_flags")
3152 TransformJarToR8Rules(ctx, proguardFlags, outputFile)
3153
3154 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
3155 android.SetProvider(ctx, ProguardSpecInfoProvider, ProguardSpecInfo{
3156 ProguardFlagsFiles: depset.New[android.Path](
3157 depset.POSTORDER,
3158 android.Paths{proguardFlags},
3159 transitiveProguardFlags,
3160 ),
3161 UnconditionallyExportedProguardFlags: depset.New[android.Path](
3162 depset.POSTORDER,
3163 nil,
3164 transitiveUnconditionalExportedFlags,
3165 ),
3166 })
3167
Colin Cross5e87f342024-04-11 15:28:18 -07003168 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource.
3169 // Also strip the relative path from the header output file so that the reuseImplementationJarAsHeaderJar check
3170 // in a module that depends on this module considers them equal.
Colin Cross77965d92024-08-15 17:11:08 -07003171 j.combinedHeaderFile = headerJar.WithoutRel()
Colin Cross5e87f342024-04-11 15:28:18 -07003172 j.combinedImplementationFile = outputFile.WithoutRel()
Colin Crossdad2a362024-03-23 04:43:41 +00003173
Sam Delmerico277795c2022-02-25 17:04:37 +00003174 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09003175
3176 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07003177
Colin Cross8ff4af32025-02-19 15:17:02 -08003178 ctx.CheckbuildFile(localJars...)
Colin Crossa6182ab2024-08-21 10:47:44 -07003179
Paul Duffin064b70c2020-11-02 17:32:38 +00003180 if ctx.Device() {
Spandan Dasa326b322024-09-19 21:02:52 +00003181 // Shared libraries deapexed from prebuilt apexes are no longer supported.
3182 // Set the dexJarBuildPath to a fake path.
3183 // This allows soong analysis pass, but will be an error during ninja execution if there are
3184 // any rdeps.
Colin Crossff694a82023-12-13 15:54:49 -08003185 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Paul Duffin064b70c2020-11-02 17:32:38 +00003186 if ai.ForPrebuiltApex {
Spandan Dasa326b322024-09-19 21:02:52 +00003187 j.dexJarFile = makeDexJarPathFromPath(android.PathForModuleInstall(ctx, "intentionally_no_longer_supported"))
3188 j.initHiddenAPI(ctx, j.dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin064b70c2020-11-02 17:32:38 +00003189 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09003190 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00003191 if sdkDep.invalidVersion {
3192 ctx.AddMissingDependencies(sdkDep.bootclasspath)
3193 ctx.AddMissingDependencies(sdkDep.java9Classpath)
3194 } else if sdkDep.useFiles {
3195 // sdkDep.jar is actually equivalent to turbine header.jar.
3196 flags.classpath = append(flags.classpath, sdkDep.jars...)
3197 }
3198
3199 // Dex compilation
3200
Jiakai Zhang519c5c82021-09-16 06:15:39 +00003201 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00003202 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00003203 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00003204 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
3205
Colin Cross7707b242024-07-26 12:02:36 -07003206 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00003207 dexParams := &compileDexParams{
3208 flags: flags,
3209 sdkVersion: j.SdkVersion(ctx),
3210 minSdkVersion: j.MinSdkVersion(ctx),
3211 classesJar: outputFile,
3212 jarName: jarName,
3213 }
3214
Spandan Das3dbda182024-05-20 22:23:10 +00003215 dexOutputFile, _ = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00003216 if ctx.Failed() {
3217 return
3218 }
Colin Crossa6182ab2024-08-21 10:47:44 -07003219 ctx.CheckbuildFile(dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00003220
Paul Duffin74d18d12021-05-14 14:18:47 +01003221 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003222 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01003223
3224 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01003225 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00003226
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003227 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09003228 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07003229 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07003230 }
Colin Crossdcf71b22021-02-01 13:59:03 -08003231
Yu Liu460cf372025-01-10 00:34:06 +00003232 javaInfo := &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07003233 HeaderJars: android.PathsIfNonNil(j.combinedHeaderFile),
3234 LocalHeaderJars: android.PathsIfNonNil(j.combinedHeaderFile),
3235 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
3236 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
3237 TransitiveStaticLibsHeaderJars: completeStaticLibsHeaderJars,
3238 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
3239 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
3240 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedImplementationFile),
3241 ImplementationJars: android.PathsIfNonNil(implementationJarFile.WithoutRel()),
3242 ResourceJars: android.PathsIfNonNil(resourceJarFile),
3243 AidlIncludeDirs: j.exportAidlIncludeDirs,
3244 StubsLinkType: j.stubsLinkType,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07003245 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Yu Liu460cf372025-01-10 00:34:06 +00003246 }
3247 setExtraJavaInfo(ctx, j, javaInfo)
3248 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
mrziwang68786d82024-07-09 10:41:55 -07003249
Yu Liu0a37d422025-02-13 02:05:00 +00003250 android.SetProvider(ctx, JavaLibraryInfoProvider, JavaLibraryInfo{
3251 Prebuilt: true,
3252 })
3253
mrziwang68786d82024-07-09 10:41:55 -07003254 ctx.SetOutputFiles(android.Paths{j.combinedImplementationFile}, "")
3255 ctx.SetOutputFiles(android.Paths{j.combinedImplementationFile}, ".jar")
Wei Li986fe742025-01-30 15:14:42 -08003256
3257 buildComplianceMetadata(ctx)
Colin Cross2fe66872015-03-30 17:20:39 -07003258}
3259
Sam Delmerico277795c2022-02-25 17:04:37 +00003260func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
3261 if !Bool(j.properties.Installable) {
3262 return
3263 }
3264
3265 var installDir android.InstallPath
3266 if ctx.InstallInTestcases() {
3267 var archDir string
3268 if !ctx.Host() {
3269 archDir = ctx.DeviceConfig().DeviceArch()
3270 }
3271 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
3272 } else {
3273 installDir = android.PathForModuleInstall(ctx, "framework")
3274 }
3275 ctx.InstallFile(installDir, jarName, outputFile)
3276}
3277
Nan Zhanged19fc32017-10-19 13:06:22 -07003278func (j *Import) HeaderJars() android.Paths {
Colin Crossdad2a362024-03-23 04:43:41 +00003279 return android.PathsIfNonNil(j.combinedHeaderFile)
Nan Zhanged19fc32017-10-19 13:06:22 -07003280}
3281
Colin Cross331a1212018-08-15 20:40:52 -07003282func (j *Import) ImplementationAndResourcesJars() android.Paths {
Colin Crossdad2a362024-03-23 04:43:41 +00003283 return android.PathsIfNonNil(j.combinedImplementationFile)
Colin Cross331a1212018-08-15 20:40:52 -07003284}
3285
Spandan Das59a4a2b2024-01-09 21:35:56 +00003286func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dasfae468e2023-12-12 23:23:53 +00003287 if j.dexJarFileErr != nil {
Spandan Das59a4a2b2024-01-09 21:35:56 +00003288 ctx.ModuleErrorf(j.dexJarFileErr.Error())
Spandan Dasfae468e2023-12-12 23:23:53 +00003289 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07003290 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08003291}
3292
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01003293func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09003294 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01003295}
3296
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01003297func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
3298 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09003299}
3300
Jiyong Park45bf82e2020-12-15 22:29:02 +09003301var _ android.ApexModule = (*Import)(nil)
3302
3303// Implements android.ApexModule
Yu Liuf1806032025-02-07 00:23:34 +00003304func (m *Import) GetDepInSameApexChecker() android.DepInSameApexChecker {
3305 return JavaImportDepInSameApexChecker{}
3306}
3307
3308type JavaImportDepInSameApexChecker struct {
3309 android.BaseDepInSameApexChecker
3310}
3311
3312func (m JavaImportDepInSameApexChecker) OutgoingDepIsInSameApex(tag blueprint.DependencyTag) bool {
3313 return depIsInSameApex(tag)
Jiyong Park0f80c182020-01-31 02:49:53 +09003314}
3315
Jiyong Park45bf82e2020-12-15 22:29:02 +09003316// Implements android.ApexModule
Yu Liudf0b8392025-02-12 18:27:03 +00003317func (j *Import) MinSdkVersionSupported(ctx android.BaseModuleContext) android.ApiLevel {
Spandan Das7fa982c2023-02-24 18:38:56 +00003318 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00003319 minSdkVersion := j.MinSdkVersion(ctx)
Yu Liudf0b8392025-02-12 18:27:03 +00003320
Spandan Das7fa982c2023-02-24 18:38:56 +00003321 // If the module is compiling against core (via sdk_version), skip comparison check.
3322 if sdkVersionSpec.Kind == android.SdkCore {
Yu Liudf0b8392025-02-12 18:27:03 +00003323 return android.MinApiLevel
Jaewoong Jung56e12db2021-04-02 00:38:25 +00003324 }
Yu Liudf0b8392025-02-12 18:27:03 +00003325
3326 return minSdkVersion
Jooyung Han749dc692020-04-15 11:03:39 +09003327}
3328
Paul Duffinfef55002021-06-17 14:56:05 +01003329// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
3330// java_sdk_library_import with the specified base module name requires to be exported from a
3331// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08003332func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
Spandan Das5be63332023-12-13 00:06:32 +00003333 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003334 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08003335 files := []string{
3336 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01003337 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08003338 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
3339 files = append(files, dexJarFileApexRootRelative+".prof")
3340 }
3341 return files
Paul Duffinfef55002021-06-17 14:56:05 +01003342}
3343
Spandan Das5be63332023-12-13 00:06:32 +00003344// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003345// the java library with the specified name.
Spandan Das5be63332023-12-13 00:06:32 +00003346func ApexRootRelativePathToJavaLib(name string) string {
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003347 return filepath.Join("javalib", name+".jar")
3348}
3349
Paul Duffinfef55002021-06-17 14:56:05 +01003350var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
3351
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003352func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01003353 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08003354 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01003355}
3356
Spandan Das2ea84dd2024-01-25 22:12:50 +00003357func (j *Import) UseProfileGuidedDexpreopt() bool {
3358 return proptools.Bool(j.importDexpreoptProperties.Dex_preopt.Profile_guided)
3359}
3360
albaltai36ff7dc2018-12-25 14:35:23 +08003361// Add compile time check for interface implementation
3362var _ android.IDEInfo = (*Import)(nil)
3363var _ android.IDECustomizedModuleName = (*Import)(nil)
3364
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003365// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003366
Cole Faustb36d31d2024-08-27 16:04:28 -07003367func (j *Import) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Spandan Das65bfc292025-01-02 22:55:56 +00003368 dpInfo.Jars = append(dpInfo.Jars, j.combinedImplementationFile.String())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003369}
3370
3371func (j *Import) IDECustomizedModuleName() string {
3372 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
3373 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
3374 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01003375 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003376}
3377
Colin Cross74d73e22017-08-02 11:05:49 -07003378var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07003379
Bill Peckhamff89ffa2020-12-23 16:13:04 -08003380func (j *Import) IsInstallable() bool {
3381 return Bool(j.properties.Installable)
3382}
3383
Jiakai Zhang519c5c82021-09-16 06:15:39 +00003384var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08003385
Colin Cross1b16b0e2019-02-12 14:41:32 -08003386// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
3387//
3388// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
3389// compiled against an Android classpath.
3390//
3391// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
3392// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07003393func ImportFactory() android.Module {
3394 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07003395
Liz Kammerd6c31d22020-08-05 15:40:41 -07003396 module.AddProperties(
3397 &module.properties,
3398 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08003399 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07003400 )
Colin Cross74d73e22017-08-02 11:05:49 -07003401
Paul Duffin71b33cc2021-06-23 11:39:47 +01003402 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01003403
Liz Kammerd6c31d22020-08-05 15:40:41 -07003404 module.dexProperties.Optimize.EnabledByDefault = false
3405
Colin Cross74d73e22017-08-02 11:05:49 -07003406 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003407 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003408 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07003409 return module
Colin Cross2fe66872015-03-30 17:20:39 -07003410}
3411
Colin Cross1b16b0e2019-02-12 14:41:32 -08003412// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
3413// module.
3414//
3415// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
3416// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07003417func ImportFactoryHost() android.Module {
3418 module := &Import{}
3419
3420 module.AddProperties(&module.properties)
3421
3422 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003423 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003424 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07003425 return module
3426}
3427
Colin Cross42be7612019-02-21 18:12:14 -08003428// dex_import module
3429
3430type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07003431 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09003432
3433 // set the name of the output
3434 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08003435}
3436
3437type DexImport struct {
3438 android.ModuleBase
3439 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09003440 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08003441 prebuilt android.Prebuilt
3442
3443 properties DexImportProperties
3444
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003445 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08003446
3447 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07003448
3449 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08003450}
3451
3452func (j *DexImport) Prebuilt() *android.Prebuilt {
3453 return &j.prebuilt
3454}
3455
3456func (j *DexImport) PrebuiltSrcs() []string {
3457 return j.properties.Jars
3458}
3459
3460func (j *DexImport) Name() string {
3461 return j.prebuilt.Name(j.ModuleBase.Name())
3462}
3463
Jiyong Park0b238752019-10-29 11:23:10 +09003464func (j *DexImport) Stem() string {
3465 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
3466}
3467
Jiyong Park77acec62020-06-01 21:39:15 +09003468func (a *DexImport) JacocoReportClassesFile() android.Path {
3469 return nil
3470}
3471
Martin Stjernholm6d415272020-01-31 17:10:36 +00003472func (j *DexImport) IsInstallable() bool {
3473 return true
3474}
3475
Colin Cross42be7612019-02-21 18:12:14 -08003476func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3477 if len(j.properties.Jars) != 1 {
3478 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
3479 }
3480
Colin Crossff694a82023-12-13 15:54:49 -08003481 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07003482 if !apexInfo.IsForPlatform() {
3483 j.hideApexVariantFromMake = true
3484 }
3485
Jiakai Zhang519c5c82021-09-16 06:15:39 +00003486 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00003487 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
3488 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &j.dexpreopter)
Colin Cross42be7612019-02-21 18:12:14 -08003489
3490 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
3491 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
3492
3493 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08003494 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08003495
3496 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
3497 rule.Temporary(temporary)
3498
3499 // use zip2zip to uncompress classes*.dex files
3500 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08003501 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08003502 FlagWithInput("-i ", inputJar).
3503 FlagWithOutput("-o ", temporary).
3504 FlagWithArg("-0 ", "'classes*.dex'")
3505
3506 // use zipalign to align uncompressed classes*.dex files
3507 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08003508 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08003509 Flag("-f").
3510 Text("4").
3511 Input(temporary).
3512 Output(dexOutputFile)
3513
3514 rule.DeleteTemporaryFiles()
3515
Colin Crossf1a035e2020-11-16 17:32:30 -08003516 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08003517 } else {
3518 ctx.Build(pctx, android.BuildParams{
3519 Rule: android.Cp,
3520 Input: inputJar,
3521 Output: dexOutputFile,
3522 })
3523 }
3524
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003525 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08003526
Spandan Dase21a8d42024-01-23 23:56:29 +00003527 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08003528
Colin Cross56a83212020-09-15 18:30:11 -07003529 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09003530 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
3531 j.Stem()+".jar", dexOutputFile)
3532 }
Yu Liu0a37d422025-02-13 02:05:00 +00003533
3534 javaInfo := &JavaInfo{}
3535 setExtraJavaInfo(ctx, j, javaInfo)
3536 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
3537
3538 android.SetProvider(ctx, JavaDexImportInfoProvider, JavaDexImportInfo{})
Colin Cross42be7612019-02-21 18:12:14 -08003539}
3540
Spandan Das59a4a2b2024-01-09 21:35:56 +00003541func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08003542 return j.dexJarFile
3543}
3544
Jiyong Park45bf82e2020-12-15 22:29:02 +09003545var _ android.ApexModule = (*DexImport)(nil)
3546
3547// Implements android.ApexModule
Yu Liudf0b8392025-02-12 18:27:03 +00003548func (m *DexImport) MinSdkVersionSupported(ctx android.BaseModuleContext) android.ApiLevel {
3549 return android.MinApiLevel
Jooyung Han749dc692020-04-15 11:03:39 +09003550}
3551
Colin Cross42be7612019-02-21 18:12:14 -08003552// dex_import imports a `.jar` file containing classes.dex files.
3553//
3554// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
3555// to the device.
3556func DexImportFactory() android.Module {
3557 module := &DexImport{}
3558
3559 module.AddProperties(&module.properties)
3560
3561 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003562 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003563 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08003564 return module
3565}
3566
Colin Cross89536d42017-07-07 14:35:50 -07003567// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07003568type Defaults struct {
3569 android.ModuleBase
3570 android.DefaultsModuleBase
3571}
3572
Colin Cross1b16b0e2019-02-12 14:41:32 -08003573// java_defaults provides a set of properties that can be inherited by other java or android modules.
3574//
3575// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
3576// property in the defaults module that exists in the depending module will be prepended to the depending module's
3577// value for that property.
3578//
3579// Example:
3580//
Sam Delmerico277795c2022-02-25 17:04:37 +00003581// java_defaults {
3582// name: "example_defaults",
3583// srcs: ["common/**/*.java"],
3584// javacflags: ["-Xlint:all"],
3585// aaptflags: ["--auto-add-overlay"],
3586// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08003587//
Sam Delmerico277795c2022-02-25 17:04:37 +00003588// java_library {
3589// name: "example",
3590// defaults: ["example_defaults"],
3591// srcs: ["example/**/*.java"],
3592// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08003593//
3594// is functionally identical to:
3595//
Sam Delmerico277795c2022-02-25 17:04:37 +00003596// java_library {
3597// name: "example",
3598// srcs: [
3599// "common/**/*.java",
3600// "example/**/*.java",
3601// ],
3602// javacflags: ["-Xlint:all"],
3603// }
Paul Duffin47357662019-12-05 14:07:14 +00003604func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07003605 module := &Defaults{}
3606
Colin Cross89536d42017-07-07 14:35:50 -07003607 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08003608 &CommonProperties{},
3609 &DeviceProperties{},
yangbill2af0b6e2024-03-15 09:29:29 +00003610 &OverridableProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07003611 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08003612 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08003613 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07003614 &aaptProperties{},
3615 &androidLibraryProperties{},
3616 &appProperties{},
3617 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08003618 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00003619 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00003620 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07003621 &ImportProperties{},
3622 &AARImportProperties{},
3623 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01003624 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08003625 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09003626 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07003627 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07003628 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08003629 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00003630 &JavaApiLibraryProperties{},
Jihoon Kang9272dcc2024-01-12 00:08:30 +00003631 &bootclasspathFragmentProperties{},
3632 &SourceOnlyBootclasspathProperties{},
John Wu878b2fc2024-10-28 22:29:35 +00003633 &ravenwoodTestProperties{},
Herbert Xued0feb712025-01-08 15:41:40 +08003634 &AndroidAppImportProperties{},
3635 &UsesLibraryProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07003636 )
3637
3638 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07003639 return module
3640}
Nan Zhangea568a42017-11-08 21:20:04 -08003641
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003642func kytheExtractJavaFactory() android.Singleton {
3643 return &kytheExtractJavaSingleton{}
3644}
3645
3646type kytheExtractJavaSingleton struct {
3647}
3648
3649func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
3650 var xrefTargets android.Paths
Spandan Das1028d5a2024-08-19 21:45:48 +00003651 var xrefKotlinTargets android.Paths
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003652 ctx.VisitAllModules(func(module android.Module) {
3653 if javaModule, ok := module.(xref); ok {
3654 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
Spandan Das1028d5a2024-08-19 21:45:48 +00003655 xrefKotlinTargets = append(xrefKotlinTargets, javaModule.XrefKotlinFiles()...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003656 }
3657 })
3658 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
3659 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07003660 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003661 }
Spandan Das1028d5a2024-08-19 21:45:48 +00003662 if len(xrefKotlinTargets) > 0 {
3663 ctx.Phony("xref_kotlin", xrefKotlinTargets...)
3664 }
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003665}
3666
Nan Zhangea568a42017-11-08 21:20:04 -08003667var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07003668var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08003669var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04003670var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003671
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003672// Add class loader context (CLC) of a given dependency to the current CLC.
Yu Liu39f5fb32025-01-13 23:52:19 +00003673func addCLCFromDep(ctx android.ModuleContext, depModule android.ModuleProxy,
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003674 clcMap dexpreopt.ClassLoaderContextMap) {
3675
Yu Liu460cf372025-01-10 00:34:06 +00003676 dep, ok := android.OtherModuleProvider(ctx, depModule, JavaInfoProvider)
3677 if !ok || dep.UsesLibraryDependencyInfo == nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003678 return
3679 }
3680
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003681 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
3682
3683 var sdkLib *string
Jihoon Kang98e9ac62024-09-25 23:42:30 +00003684 if lib, ok := android.OtherModuleProvider(ctx, depModule, SdkLibraryInfoProvider); ok && lib.SharedLibrary {
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003685 // A shared SDK library. This should be added as a top-level CLC element.
3686 sdkLib = &depName
Yu Liu460cf372025-01-10 00:34:06 +00003687 } else if lib := dep.SdkLibraryComponentDependencyInfo; lib != nil && lib.OptionalSdkLibraryImplementation != nil {
3688 if depModule.Name() == proptools.String(lib.OptionalSdkLibraryImplementation)+".impl" {
3689 sdkLib = lib.OptionalSdkLibraryImplementation
Jihoon Kangddda6ea2024-09-18 00:56:52 +00003690 }
Yu Liu460cf372025-01-10 00:34:06 +00003691 } else if ulib := dep.ProvidesUsesLibInfo; ulib != nil {
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003692 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
3693 // property. This should be handled in the same way as a shared SDK library.
Yu Liu460cf372025-01-10 00:34:06 +00003694 sdkLib = ulib.ProvidesUsesLib
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003695 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003696
3697 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04003698 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003699 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01003700 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
3701 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003702 } else if depTag == staticLibTag {
3703 // Propagate <uses-library> through static library dependencies, unless it is a component
3704 // library (such as stubs). Component libraries have a dependency on their SDK library,
3705 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003706 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003707 return
3708 }
3709 } else {
3710 // Don't propagate <uses-library> for other dependency tags.
3711 return
3712 }
3713
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003714 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
3715 // and its CLC should be added as subtree of that node. Otherwise the library is not a
3716 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
3717 // from its CLC should be added to the current CLC.
3718 if sdkLib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +00003719 optional := false
3720 if module, ok := ctx.Module().(ModuleWithUsesLibrary); ok {
Cole Faust64f2d842024-10-17 13:28:34 -07003721 if android.InList(*sdkLib, module.UsesLibrary().usesLibraryProperties.Optional_uses_libs.GetOrDefault(ctx, nil)) {
Jiakai Zhangf98da192024-04-15 11:15:41 +00003722 optional = true
3723 }
3724 }
3725 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, optional,
Yu Liu0a37d422025-02-13 02:05:00 +00003726 dep.DexJarBuildPath.PathOrNil(),
Yu Liu460cf372025-01-10 00:34:06 +00003727 dep.UsesLibraryDependencyInfo.DexJarInstallPath, dep.UsesLibraryDependencyInfo.ClassLoaderContexts)
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003728 } else {
Yu Liu460cf372025-01-10 00:34:06 +00003729 clcMap.AddContextMap(dep.UsesLibraryDependencyInfo.ClassLoaderContexts, depName)
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003730 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003731}
Wei Libafb6d62021-12-10 03:14:59 -08003732
Yu Liu39f5fb32025-01-13 23:52:19 +00003733func addMissingOptionalUsesLibsFromDep(ctx android.ModuleContext, depModule android.ModuleProxy,
Jiakai Zhang36937082024-04-15 11:15:50 +00003734 usesLibrary *usesLibrary) {
3735
Yu Liu460cf372025-01-10 00:34:06 +00003736 dep, ok := android.OtherModuleProvider(ctx, depModule, JavaInfoProvider)
Cole Faustc9b88c92025-02-06 17:58:26 -08003737 if !ok {
Jiakai Zhang36937082024-04-15 11:15:50 +00003738 return
3739 }
3740
Cole Faustc9b88c92025-02-06 17:58:26 -08003741 for _, lib := range dep.MissingOptionalUsesLibs {
Jiakai Zhang36937082024-04-15 11:15:50 +00003742 if !android.InList(lib, usesLibrary.usesLibraryProperties.Missing_optional_uses_libs) {
3743 usesLibrary.usesLibraryProperties.Missing_optional_uses_libs =
3744 append(usesLibrary.usesLibraryProperties.Missing_optional_uses_libs, lib)
3745 }
3746 }
3747}
3748
Jihoon Kangfdf32362023-09-12 00:36:43 +00003749type JavaApiContributionImport struct {
3750 JavaApiContribution
3751
Spandan Das23956d12024-01-19 00:22:22 +00003752 prebuilt android.Prebuilt
3753 prebuiltProperties javaApiContributionImportProperties
3754}
3755
3756type javaApiContributionImportProperties struct {
3757 // Name of the source soong module that gets shadowed by this prebuilt
3758 // If unspecified, follows the naming convention that the source module of
3759 // the prebuilt is Name() without "prebuilt_" prefix
3760 Source_module_name *string
3761
3762 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
3763 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
3764 // (without any prebuilt_ prefix)
3765 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfdf32362023-09-12 00:36:43 +00003766}
3767
3768func ApiContributionImportFactory() android.Module {
3769 module := &JavaApiContributionImport{}
3770 android.InitAndroidModule(module)
3771 android.InitDefaultableModule(module)
3772 android.InitPrebuiltModule(module, &[]string{""})
Spandan Das23956d12024-01-19 00:22:22 +00003773 module.AddProperties(&module.properties, &module.prebuiltProperties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00003774 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00003775 return module
3776}
3777
3778func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
3779 return &module.prebuilt
3780}
3781
3782func (module *JavaApiContributionImport) Name() string {
3783 return module.prebuilt.Name(module.ModuleBase.Name())
3784}
3785
Spandan Das23956d12024-01-19 00:22:22 +00003786func (j *JavaApiContributionImport) BaseModuleName() string {
3787 return proptools.StringDefault(j.prebuiltProperties.Source_module_name, j.ModuleBase.Name())
3788}
3789
3790func (j *JavaApiContributionImport) CreatedByJavaSdkLibraryName() *string {
3791 return j.prebuiltProperties.Created_by_java_sdk_library_name
3792}
3793
Jihoon Kangfdf32362023-09-12 00:36:43 +00003794func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3795 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
3796}
Yu Liu460cf372025-01-10 00:34:06 +00003797
3798func setExtraJavaInfo(ctx android.ModuleContext, module android.Module, javaInfo *JavaInfo) {
3799 if alDep, ok := module.(AndroidLibraryDependency); ok {
3800 javaInfo.AndroidLibraryDependencyInfo = &AndroidLibraryDependencyInfo{
3801 ExportPackage: alDep.ExportPackage(),
3802 ResourcesNodeDepSet: alDep.ResourcesNodeDepSet(),
3803 RRODirsDepSet: alDep.RRODirsDepSet(),
3804 ManifestsDepSet: alDep.ManifestsDepSet(),
3805 }
3806 }
3807
3808 if ulDep, ok := module.(UsesLibraryDependency); ok {
3809 javaInfo.UsesLibraryDependencyInfo = &UsesLibraryDependencyInfo{
Yu Liu460cf372025-01-10 00:34:06 +00003810 DexJarInstallPath: ulDep.DexJarInstallPath(),
3811 ClassLoaderContexts: ulDep.ClassLoaderContexts(),
3812 }
3813 }
3814
3815 if slcDep, ok := module.(SdkLibraryComponentDependency); ok {
3816 javaInfo.SdkLibraryComponentDependencyInfo = &SdkLibraryComponentDependencyInfo{
3817 OptionalSdkLibraryImplementation: slcDep.OptionalSdkLibraryImplementation(),
3818 }
3819 }
3820
3821 if pul, ok := module.(ProvidesUsesLib); ok {
3822 javaInfo.ProvidesUsesLibInfo = &ProvidesUsesLibInfo{
3823 ProvidesUsesLib: pul.ProvidesUsesLib(),
3824 }
3825 }
3826
3827 if mwul, ok := module.(ModuleWithUsesLibrary); ok {
Cole Faustc9b88c92025-02-06 17:58:26 -08003828 javaInfo.MissingOptionalUsesLibs = mwul.UsesLibrary().usesLibraryProperties.Missing_optional_uses_libs
Yu Liu460cf372025-01-10 00:34:06 +00003829 }
Yu Liuc0a36302025-01-10 22:26:01 +00003830
3831 if mwsd, ok := module.(moduleWithSdkDep); ok {
3832 linkType, stubs := mwsd.getSdkLinkType(ctx, ctx.ModuleName())
3833 javaInfo.ModuleWithSdkDepInfo = &ModuleWithSdkDepInfo{
3834 SdkLinkType: linkType,
3835 Stubs: stubs,
3836 }
3837 }
Yu Liu0a37d422025-02-13 02:05:00 +00003838
3839 if st, ok := module.(ModuleWithStem); ok {
3840 javaInfo.Stem = st.Stem()
3841 }
3842
3843 if mm, ok := module.(interface {
3844 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
3845 }); ok {
3846 javaInfo.DexJarBuildPath = mm.DexJarBuildPath(ctx)
3847 }
3848
3849 if di, ok := module.(DexpreopterInterface); ok {
3850 javaInfo.DexpreopterInfo = &DexpreopterInfo{
3851 OutputProfilePathOnHost: di.OutputProfilePathOnHost(),
3852 ApexSystemServerDexpreoptInstalls: di.ApexSystemServerDexpreoptInstalls(),
3853 ApexSystemServerDexJars: di.ApexSystemServerDexJars(),
3854 }
3855 }
Yu Liu460cf372025-01-10 00:34:06 +00003856}