blob: 25be93b46acf921a23acdc727a0d9ca46358c382 [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)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080067
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010068 // This mutator registers dependencies on dex2oat for modules that should be
69 // dexpreopted. This is done late when the final variants have been
70 // established, to not get the dependencies split into the wrong variants and
71 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080072 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
Colin Cross8a962802024-10-09 15:29:27 -070073 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator)
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040074 // needs access to ApexInfoProvider which is available after variant creation
Colin Cross8a962802024-10-09 15:29:27 -070075 ctx.BottomUp("jacoco_deps", jacocoDepsMutator)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080076 })
77
LaMont Jones0c10e4d2023-05-16 00:58:37 +000078 ctx.RegisterParallelSingletonType("kythe_java_extract", kytheExtractJavaFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080079}
80
81func RegisterJavaSdkMemberTypes() {
Paul Duffin255f18e2019-12-13 11:22:16 +000082 // Register sdk member types.
Paul Duffin7b81f5e2020-01-13 21:03:22 +000083 android.RegisterSdkMemberType(javaHeaderLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010084 android.RegisterSdkMemberType(javaLibsSdkMemberType)
Spandan Das159b2642024-03-20 21:22:47 +000085 android.RegisterSdkMemberType(JavaBootLibsSdkMemberType)
86 android.RegisterSdkMemberType(JavaSystemserverLibsSdkMemberType)
Paul Duffin2da04242021-04-23 19:43:28 +010087 android.RegisterSdkMemberType(javaTestSdkMemberType)
88}
89
Jihoon Kangfe914ed2024-02-12 22:49:21 +000090type StubsLinkType int
91
92const (
93 Unknown StubsLinkType = iota
94 Stubs
95 Implementation
96)
97
Paul Duffin2da04242021-04-23 19:43:28 +010098var (
99 // Supports adding java header libraries to module_exports and sdk.
100 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000101 android.SdkMemberTypeBase{
Paul Duffin2da04242021-04-23 19:43:28 +0100102 PropertyName: "java_header_libs",
103 SupportsSdk: true,
104 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000105 func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin2da04242021-04-23 19:43:28 +0100106 headerJars := j.HeaderJars()
107 if len(headerJars) != 1 {
108 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
109 }
110
111 return headerJars[0]
112 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000113 sdkSnapshotFilePathForJar,
114 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100115 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000116
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000117 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100118 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000119 implementationJars := j.ImplementationAndResourcesJars()
120 if len(implementationJars) != 1 {
121 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
122 }
123 return implementationJars[0]
124 }
125
Paul Duffin2da04242021-04-23 19:43:28 +0100126 // Supports adding java implementation libraries to module_exports but not sdk.
127 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000128 android.SdkMemberTypeBase{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000129 PropertyName: "java_libs",
130 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000131 exportImplementationClassesJar,
132 sdkSnapshotFilePathForJar,
133 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100134 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000135
Paul Duffin13648912022-07-15 13:12:35 +0000136 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
137 // In the S build the build will break if updatable-media does not provide a full implementation
138 // jar. That issue was fixed in Tiramisu by b/229932396.
139 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
140 return true
141 }
142
143 return false
144 }
145
Paul Duffin2da04242021-04-23 19:43:28 +0100146 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000147 //
148 // The build has some implicit dependencies (via the boot jars configuration) on a number of
149 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
150 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
151 // used outside those mainline modules.
152 //
153 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
154 // either java_libs, or java_header_libs would end up exporting more information than was strictly
155 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
156 // sdk/module_exports without exposing any unnecessary information.
Spandan Das159b2642024-03-20 21:22:47 +0000157 JavaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000158 android.SdkMemberTypeBase{
Paul Duffindb170e42020-12-08 17:48:25 +0000159 PropertyName: "java_boot_libs",
160 SupportsSdk: true,
161 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000162 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000163 if snapshotRequiresImplementationJar(ctx) {
164 return exportImplementationClassesJar(ctx, j)
165 }
166
Paul Duffin5c211452021-07-15 12:42:44 +0100167 // Java boot libs are only provided in the SDK to provide access to their dex implementation
168 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
169 // actual implementation jar but the java_import will need a file that exists so just copy an
170 // empty file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000171 return ctx.SnapshotBuilder().EmptyFile()
Paul Duffin5c211452021-07-15 12:42:44 +0100172 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000173 func(ctx android.SdkMemberContext, osPrefix, name string) string {
Paul Duffin13648912022-07-15 13:12:35 +0000174 if snapshotRequiresImplementationJar(ctx) {
175 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
176 }
177
Paul Duffin5c211452021-07-15 12:42:44 +0100178 // Create a special name for the implementation jar to try and provide some useful information
179 // to a developer that attempts to compile against this.
180 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
181 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
182 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000183 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100184 }
Paul Duffindb170e42020-12-08 17:48:25 +0000185
Jiakai Zhangea180332021-09-26 08:58:02 +0000186 // Supports adding java systemserver libraries to module_exports and sdk.
187 //
188 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
189 // of modules that are part of the java systemserver classpath and which are provided by mainline
190 // modules but which are not otherwise used outside those mainline modules.
191 //
192 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
193 // either java_libs, or java_header_libs would end up exporting more information than was strictly
194 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
195 // the sdk/module_exports without exposing any unnecessary information.
Spandan Das159b2642024-03-20 21:22:47 +0000196 JavaSystemserverLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000197 android.SdkMemberTypeBase{
Jiakai Zhangea180332021-09-26 08:58:02 +0000198 PropertyName: "java_systemserver_libs",
199 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000200
201 // This was only added in Tiramisu.
202 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000203 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000204 func(ctx android.SdkMemberContext, j *Library) android.Path {
Jiakai Zhangea180332021-09-26 08:58:02 +0000205 // Java systemserver libs are only provided in the SDK to provide access to their dex
206 // implementation jar for use by dexpreopting. They do not need to provide an actual
207 // implementation jar but the java_import will need a file that exists so just copy an empty
208 // file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000209 return ctx.SnapshotBuilder().EmptyFile()
Jiakai Zhangea180332021-09-26 08:58:02 +0000210 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000211 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000212 // Create a special name for the implementation jar to try and provide some useful information
213 // to a developer that attempts to compile against this.
214 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
215 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
216 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000217 onlyCopyJarToSnapshot,
Jiakai Zhangea180332021-09-26 08:58:02 +0000218 }
219
Paul Duffin2da04242021-04-23 19:43:28 +0100220 // Supports adding java test libraries to module_exports but not sdk.
221 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000222 SdkMemberTypeBase: android.SdkMemberTypeBase{
223 PropertyName: "java_tests",
224 },
Paul Duffin2da04242021-04-23 19:43:28 +0100225 }
Zi Wangca65b402022-10-10 13:45:06 -0700226
227 // Rule for generating device binary default wrapper
228 deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
Colin Cross7cd1d422024-11-13 13:05:49 -0800229 Command: `printf '#!/system/bin/sh\n` +
Zi Wangca65b402022-10-10 13:45:06 -0700230 `export CLASSPATH=/system/framework/$jar_name\n` +
Colin Cross7cd1d422024-11-13 13:05:49 -0800231 `exec app_process /$partition/bin $main_class "$$@"\n'> ${out}`,
Zi Wangca65b402022-10-10 13:45:06 -0700232 Description: "Generating device binary wrapper ${jar_name}",
233 }, "jar_name", "partition", "main_class")
Paul Duffin2da04242021-04-23 19:43:28 +0100234)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900235
Sam Delmerico95d70942023-08-02 18:00:35 -0400236type ProguardSpecInfo struct {
237 // If true, proguard flags files will be exported to reverse dependencies across libs edges
238 // If false, proguard flags files will only be exported to reverse dependencies across
239 // static_libs edges.
240 Export_proguard_flags_files bool
241
242 // TransitiveDepsProguardSpecFiles is a depset of paths to proguard flags files that are exported from
243 // all transitive deps. This list includes all proguard flags files from transitive static dependencies,
244 // and all proguard flags files from transitive libs dependencies which set `export_proguard_spec: true`.
Colin Crossa14fb6a2024-10-23 16:57:06 -0700245 ProguardFlagsFiles depset.DepSet[android.Path]
Sam Delmerico95d70942023-08-02 18:00:35 -0400246
247 // implementation detail to store transitive proguard flags files from exporting shared deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700248 UnconditionallyExportedProguardFlags depset.DepSet[android.Path]
Sam Delmerico95d70942023-08-02 18:00:35 -0400249}
250
Colin Crossbc7d76c2023-12-12 16:39:03 -0800251var ProguardSpecInfoProvider = blueprint.NewProvider[ProguardSpecInfo]()
Sam Delmerico95d70942023-08-02 18:00:35 -0400252
Yu Liu460cf372025-01-10 00:34:06 +0000253type AndroidLibraryDependencyInfo struct {
254 ExportPackage android.Path
255 ResourcesNodeDepSet depset.DepSet[*resourcesNode]
256 RRODirsDepSet depset.DepSet[rroDir]
257 ManifestsDepSet depset.DepSet[android.Path]
258}
259
260type UsesLibraryDependencyInfo struct {
261 DexJarBuildPath OptionalDexJarPath
262 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
Colin Crossdcf71b22021-02-01 13:59:03 -0800279// JavaInfo contains information about a java module for use by modules that depend on it.
280type JavaInfo struct {
281 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
282 // against this module. If empty, ImplementationJars should be used instead.
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700283 // Unlike LocalHeaderJars, HeaderJars includes classes from static dependencies.
Colin Crossdcf71b22021-02-01 13:59:03 -0800284 HeaderJars android.Paths
285
Joe Onorato349ae8d2024-02-05 22:46:00 +0000286 RepackagedHeaderJars android.Paths
287
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500288 // set of header jars for all transitive libs deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700289 TransitiveLibsHeaderJarsForR8 depset.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500290
291 // set of header jars for all transitive static libs deps
Colin Crossa14fb6a2024-10-23 16:57:06 -0700292 TransitiveStaticLibsHeaderJarsForR8 depset.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500293
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700294 // depset of header jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700295 TransitiveStaticLibsHeaderJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700296
297 // depset of implementation jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700298 TransitiveStaticLibsImplementationJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700299
300 // depset of resource jars for this module and all transitive static dependencies
Colin Crossa14fb6a2024-10-23 16:57:06 -0700301 TransitiveStaticLibsResourceJars depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700302
Colin Crossdcf71b22021-02-01 13:59:03 -0800303 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
304 // in the module as well as any resources included in the module.
305 ImplementationAndResourcesJars android.Paths
306
307 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin27819362024-07-22 21:03:50 +0100308 // module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800309 ImplementationJars android.Paths
310
311 // ResourceJars is a list of jars that contain the resources included in the module.
312 ResourceJars android.Paths
313
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700314 // LocalHeaderJars is a list of jars that contain classes from this module, but not from any static dependencies.
315 LocalHeaderJars android.Paths
316
Colin Crossdcf71b22021-02-01 13:59:03 -0800317 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
318 // depending on this module.
319 AidlIncludeDirs android.Paths
320
321 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
322 // module.
323 SrcJarArgs []string
324
325 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
326 SrcJarDeps android.Paths
327
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000328 // The source files of this module and all its transitive static dependencies.
Colin Crossa14fb6a2024-10-23 16:57:06 -0700329 TransitiveSrcFiles depset.DepSet[android.Path]
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000330
Colin Crossdcf71b22021-02-01 13:59:03 -0800331 // ExportedPlugins is a list of paths that should be used as annotation processors for any
332 // module that depends on this module.
333 ExportedPlugins android.Paths
334
335 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
336 // any module that depends on this module.
337 ExportedPluginClasses []string
338
339 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
340 // requiring disbling turbine for any modules that depend on it.
341 ExportedPluginDisableTurbine bool
342
343 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
344 // instrumented by jacoco.
345 JacocoReportClassesFile android.Path
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000346
347 // StubsLinkType provides information about whether the provided jars are stub jars or
348 // implementation jars. If the provider is set by java_sdk_library, the link type is "unknown"
349 // and selection between the stub jar vs implementation jar is deferred to SdkLibrary.sdkJars(...)
350 StubsLinkType StubsLinkType
Jihoon Kang705e63e2024-03-13 01:21:16 +0000351
352 // AconfigIntermediateCacheOutputPaths is a path to the cache files collected from the
353 // java_aconfig_library modules that are statically linked to this module.
354 AconfigIntermediateCacheOutputPaths android.Paths
Yu Liu63bdf632024-12-03 19:54:05 +0000355
356 SdkVersion android.SdkSpec
Yu Liu460cf372025-01-10 00:34:06 +0000357
358 AndroidLibraryDependencyInfo *AndroidLibraryDependencyInfo
359
360 UsesLibraryDependencyInfo *UsesLibraryDependencyInfo
361
362 SdkLibraryComponentDependencyInfo *SdkLibraryComponentDependencyInfo
363
364 ProvidesUsesLibInfo *ProvidesUsesLibInfo
365
366 ModuleWithUsesLibraryInfo *ModuleWithUsesLibraryInfo
Colin Crossdcf71b22021-02-01 13:59:03 -0800367}
368
Colin Cross7727c7f2024-07-18 15:36:32 -0700369var JavaInfoProvider = blueprint.NewProvider[*JavaInfo]()
Colin Crossdcf71b22021-02-01 13:59:03 -0800370
Colin Cross75ce9ec2021-02-26 16:20:32 -0800371// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
372// the sysprop implementation library.
373type SyspropPublicStubInfo struct {
374 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
375 // the sysprop implementation library.
Colin Cross7727c7f2024-07-18 15:36:32 -0700376 JavaInfo *JavaInfo
Colin Cross75ce9ec2021-02-26 16:20:32 -0800377}
378
Colin Crossbc7d76c2023-12-12 16:39:03 -0800379var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]()
Colin Cross75ce9ec2021-02-26 16:20:32 -0800380
Paul Duffin44b481b2020-06-17 16:59:43 +0100381// Methods that need to be implemented for a module that is added to apex java_libs property.
382type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700383 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100384 ImplementationAndResourcesJars() android.Paths
385}
386
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100387// Provides build path and install path to DEX jars.
388type UsesLibraryDependency interface {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000389 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100390 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000391 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100392}
393
Jaewoong Jung26342642021-03-17 15:56:23 -0700394// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800395type xref interface {
396 XrefJavaFiles() android.Paths
Spandan Das1028d5a2024-08-19 21:45:48 +0000397 XrefKotlinFiles() android.Paths
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800398}
399
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800400func (j *Module) XrefJavaFiles() android.Paths {
401 return j.kytheFiles
402}
403
Spandan Das1028d5a2024-08-19 21:45:48 +0000404func (j *Module) XrefKotlinFiles() android.Paths {
405 return j.kytheKotlinFiles
406}
407
Yu Liu67a28422024-03-05 00:36:31 +0000408func (d dependencyTag) PropagateAconfigValidation() bool {
409 return d.static
410}
411
412var _ android.PropagateAconfigValidationDependencyTag = dependencyTag{}
413
Colin Crossbe1da472017-07-07 15:59:46 -0700414type dependencyTag struct {
415 blueprint.BaseDependencyTag
416 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000417
418 // True if the dependency is relinked at runtime.
419 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800420
421 // True if the dependency is a toolchain, for example an annotation processor.
422 toolchain bool
Yu Liu67a28422024-03-05 00:36:31 +0000423
424 static bool
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000425
426 installable bool
Colin Cross2fe66872015-03-30 17:20:39 -0700427}
428
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000429var _ android.InstallNeededDependencyTag = (*dependencyTag)(nil)
430
431func (d dependencyTag) InstallDepNeeded() bool {
432 return d.installable
Colin Crosse9fe2942020-11-10 18:12:15 -0800433}
434
Colin Cross65cb3142021-12-10 23:05:02 +0000435func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
436 if d.runtimeLinked {
437 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800438 } else if d.toolchain {
439 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000440 }
441 return nil
442}
443
444var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
445
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100446type usesLibraryDependencyTag struct {
447 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100448 sdkVersion int // SDK version in which the library appared as a standalone library.
449 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100450}
451
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100452func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100453 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000454 dependencyTag: dependencyTag{
455 name: fmt.Sprintf("uses-library-%d", sdkVersion),
456 runtimeLinked: true,
457 },
458 sdkVersion: sdkVersion,
459 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100460 }
461}
462
Jiyong Park8be103b2019-11-08 15:53:48 +0900463func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000464 return depTag == jniLibTag || depTag == jniInstallTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900465}
466
Colin Crossbe1da472017-07-07 15:59:46 -0700467var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800468 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000469 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Yu Liu67a28422024-03-05 00:36:31 +0000470 staticLibTag = dependencyTag{name: "staticlib", static: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000471 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400472 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000473 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800474 pluginTag = dependencyTag{name: "plugin", toolchain: true}
475 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
476 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000477 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
478 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800479 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Crossce564252022-01-12 11:13:32 -0800480 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800481 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
482 certificateTag = dependencyTag{name: "certificate"}
483 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800484 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000485 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500486 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800487 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000488 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
Jihoon Kang84b25892023-12-01 22:01:06 +0000489 aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"}
Jiyong Parkc1e5b182024-05-17 22:58:54 +0000490 jniInstallTag = dependencyTag{name: "jni install", runtimeLinked: true, installable: true}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100491 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
492 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
493 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
494 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
495 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700496)
Colin Cross2fe66872015-03-30 17:20:39 -0700497
Spandan Das8aac9932024-07-18 23:14:13 +0000498// A list of tags for deps used for compiling a module.
499// Any dependency tags that modifies the following properties of `deps` in `Module.collectDeps` should be
500// added to this list:
501// - bootClasspath
502// - classpath
503// - java9Classpath
504// - systemModules
505// - kotlin deps...
506var (
507 compileDependencyTags = []blueprint.DependencyTag{
508 sdkLibTag,
509 libTag,
510 staticLibTag,
511 bootClasspathTag,
512 systemModulesTag,
513 java9LibTag,
Spandan Das8aac9932024-07-18 23:14:13 +0000514 kotlinPluginTag,
515 syspropPublicStubDepTag,
516 instrumentationForTag,
517 }
518)
519
Jiyong Park83dc74b2020-01-14 18:38:44 +0900520func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400521 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900522}
523
524func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
525 return depTag == staticLibTag
526}
527
Colin Crossfc3674a2017-09-18 17:41:52 -0700528type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100529 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700530
Colin Cross6cef4812019-10-17 14:23:50 -0700531 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
532 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100533
534 // The default system modules to use. Will be an empty string if no system
535 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700536 systemModules string
537
Pete Gilline3d44b22020-06-29 11:28:51 +0100538 // The modules that will be added to the classpath regardless of the Java language level targeted
539 classpath []string
540
Colin Cross6cef4812019-10-17 14:23:50 -0700541 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100542 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700543 java9Classpath []string
544
Colin Crossa97c5d32018-03-28 14:58:31 -0700545 frameworkResModule string
546
Colin Cross86a60ae2018-05-29 14:44:55 -0700547 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700548 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100549
550 noStandardLibs, noFrameworksLibs bool
551}
552
553func (s sdkDep) hasStandardLibs() bool {
554 return !s.noStandardLibs
555}
556
557func (s sdkDep) hasFrameworkLibs() bool {
558 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700559}
560
Colin Crossa4f08812018-10-02 22:03:40 -0700561type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700562 name string
563 path android.Path
564 target android.Target
565 coverageFile android.OptionalPath
566 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000567 partition string
Jiyong Park25b92222024-05-17 22:58:54 +0000568 installPaths android.InstallPaths
Colin Crossa4f08812018-10-02 22:03:40 -0700569}
570
Jiyong Parkf1691d22021-03-29 20:11:58 +0900571func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700572 sdkDep := decodeSdkDep(ctx, sdkContext)
573 if sdkDep.useModule {
574 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
575 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400576 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700577 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000578 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000579 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000580 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700581 }
582 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
583 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
584 }
585 }
586 if sdkDep.systemModules != "" {
587 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
588 }
589}
590
Colin Cross32f676a2017-09-06 13:41:06 -0700591type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700592 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
593 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
594 // systemModules and java9Classpath instead.
595 bootClasspath classpath
596
597 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
598 // contains header jars for all static and non-static dependencies.
599 classpath classpath
600
601 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
602 // header jars for all non-static dependencies. Static dependencies have already been
603 // combined into the program jar.
604 dexClasspath classpath
605
606 // java9Classpath is the list of jars that will be added to the classpath when targeting
607 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
608 // are provided by systemModules.
609 java9Classpath classpath
610
Colin Crossfdaa6722024-08-23 11:58:08 -0700611 processorPath classpath ``
Colin Cross748b2d82020-11-19 13:52:06 -0800612 errorProneProcessorPath classpath
613 processorClasses []string
614 staticJars android.Paths
615 staticHeaderJars android.Paths
616 staticResourceJars android.Paths
617 aidlIncludeDirs android.Paths
618 srcs android.Paths
619 srcJars android.Paths
620 systemModules *systemModules
621 aidlPreprocess android.OptionalPath
Colin Crossa1ff7c62021-09-17 14:11:52 -0700622 kotlinPlugins android.Paths
Jihoon Kang6592e872023-12-19 01:13:16 +0000623 aconfigProtoFiles android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800624
625 disableTurbine bool
Colin Crossc9b4f6b2024-07-26 15:25:46 -0700626
Colin Crossa14fb6a2024-10-23 16:57:06 -0700627 transitiveStaticLibsHeaderJars []depset.DepSet[android.Path]
628 transitiveStaticLibsImplementationJars []depset.DepSet[android.Path]
629 transitiveStaticLibsResourceJars []depset.DepSet[android.Path]
Colin Cross32f676a2017-09-06 13:41:06 -0700630}
Colin Cross2fe66872015-03-30 17:20:39 -0700631
Colin Cross54250902017-12-05 09:28:08 -0800632func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
633 for _, f := range dep.Srcs() {
634 if f.Ext() != ".jar" {
635 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
636 ctx.OtherModuleName(dep.(blueprint.Module)))
637 }
638 }
639}
640
Jiyong Parkf1691d22021-03-29 20:11:58 +0900641func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700642 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700643 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700644 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900645 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca253f8c02024-05-23 10:28:24 +0100646 } else if ctx.Config().TargetsJava21() {
Sorin Basca37cc2712024-10-16 10:25:36 +0100647 // Build flag that controls whether Java 21 is used as the default
648 // target version, or Java 17.
Sorin Basca253f8c02024-05-23 10:28:24 +0100649 return JAVA_VERSION_21
Sorin Basca384250c2023-02-02 17:56:19 +0000650 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000651 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700652 }
Nan Zhang357466b2018-04-17 17:38:36 -0700653}
654
Jihoon Kangff878bf2022-12-22 21:26:06 +0000655// Java version for stubs generation
656func getStubsJavaVersion() javaVersion {
657 return JAVA_VERSION_8
658}
659
Colin Cross1e743852019-10-28 11:37:20 -0700660type javaVersion int
661
662const (
663 JAVA_VERSION_UNSUPPORTED = 0
664 JAVA_VERSION_6 = 6
665 JAVA_VERSION_7 = 7
666 JAVA_VERSION_8 = 8
667 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000668 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100669 JAVA_VERSION_17 = 17
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100670 JAVA_VERSION_21 = 21
Colin Cross1e743852019-10-28 11:37:20 -0700671)
672
673func (v javaVersion) String() string {
674 switch v {
675 case JAVA_VERSION_6:
Sorin Bascad567a512024-01-15 16:38:46 +0000676 // Java version 1.6 no longer supported, bumping to 1.8
677 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700678 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000679 // Java version 1.7 no longer supported, bumping to 1.8
680 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700681 case JAVA_VERSION_8:
682 return "1.8"
683 case JAVA_VERSION_9:
684 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000685 case JAVA_VERSION_11:
686 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100687 case JAVA_VERSION_17:
688 return "17"
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100689 case JAVA_VERSION_21:
690 return "21"
Colin Cross1e743852019-10-28 11:37:20 -0700691 default:
692 return "unsupported"
693 }
694}
695
Cole Faustd96eebf2022-06-28 14:41:27 -0700696func (v javaVersion) StringForKotlinc() string {
697 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
698 // error: unknown JVM target version: foo
Sorin Bascad567a512024-01-15 16:38:46 +0000699 // Supported versions: 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
Cole Faustd96eebf2022-06-28 14:41:27 -0700700 switch v {
Sorin Bascad567a512024-01-15 16:38:46 +0000701 case JAVA_VERSION_6:
702 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700703 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000704 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700705 case JAVA_VERSION_9:
706 return "9"
707 default:
708 return v.String()
709 }
710}
711
Colin Cross1e743852019-10-28 11:37:20 -0700712// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
713func (v javaVersion) usesJavaModules() bool {
714 return v >= 9
715}
716
717func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100718 switch javaVersion {
719 case "1.6", "6":
Sorin Bascad567a512024-01-15 16:38:46 +0000720 // Java version 1.6 no longer supported, bumping to 1.8
721 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100722 case "1.7", "7":
Sorin Bascad567a512024-01-15 16:38:46 +0000723 // Java version 1.7 no longer supported, bumping to 1.8
724 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100725 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700726 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100727 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700728 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000729 case "11":
730 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100731 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100732 return JAVA_VERSION_17
Sorin Basca1fe2cc82024-04-19 10:45:55 +0100733 case "21":
734 return JAVA_VERSION_21
Sorin Bascace720c32022-05-24 12:13:50 +0100735 case "10", "12", "13", "14", "15", "16":
736 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700737 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100738 default:
739 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700740 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100741 }
742}
743
Colin Cross2fe66872015-03-30 17:20:39 -0700744//
745// Java libraries (.jar file)
746//
747
Colin Crossf506d872017-07-19 15:53:04 -0700748type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700749 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700750
Colin Cross312634e2023-11-21 15:13:56 -0800751 combinedExportedProguardFlagsFile android.Path
Jared Duke5979b302022-12-19 21:08:39 +0000752
Colin Cross09ad3a62023-11-15 12:29:33 -0800753 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Colin Cross2fe66872015-03-30 17:20:39 -0700754}
755
Jiyong Park45bf82e2020-12-15 22:29:02 +0900756var _ android.ApexModule = (*Library)(nil)
757
Jihoon Kanga3a05462024-04-05 00:36:44 +0000758func (j *Library) CheckDepsMinSdkVersion(ctx android.ModuleContext) {
759 CheckMinSdkVersion(ctx, j)
760}
761
satayevd604b212021-07-21 14:23:52 +0100762// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100763type PermittedPackagesForUpdatableBootJars interface {
764 PermittedPackagesForUpdatableBootJars() []string
765}
766
767var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
768
769func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
770 return j.properties.Permitted_packages
771}
772
Spandan Dase21a8d42024-01-23 23:56:29 +0000773func shouldUncompressDex(ctx android.ModuleContext, libName string, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000774 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Crossff694a82023-12-13 15:54:49 -0800775 if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000776 return true
777 }
778
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000779 // Store uncompressed (and do not strip) dex files from boot class path jars.
780 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
781 return true
782 }
783
Jared Dukea561efb2024-02-09 18:45:24 +0000784 // Store uncompressed dex files that are preopted on /system or /system_other.
785 if !dexpreopter.dexpreoptDisabled(ctx, libName) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000786 return true
787 }
Jared Dukea561efb2024-02-09 18:45:24 +0000788
Colin Cross083a2aa2019-02-06 16:37:12 -0800789 if ctx.Config().UncompressPrivAppDex() &&
790 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
791 return true
792 }
793
Colin Cross2fc72f62018-12-21 12:59:54 -0800794 return false
795}
796
Jiakai Zhang22450f22021-10-11 03:05:20 +0000797// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
798func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
799 if dexer.dexProperties.Uncompress_dex == nil {
800 // If the value was not force-set by the user, use reasonable default based on the module.
Spandan Dase21a8d42024-01-23 23:56:29 +0000801 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexpreopter))
Jiakai Zhang22450f22021-10-11 03:05:20 +0000802 }
803}
804
Spandan Das8469e932024-02-20 16:47:07 +0000805// list of java_library modules that set platform_apis: true
806// this property is a no-op for java_library
807// TODO (b/215379393): Remove this allowlist
808var (
809 aospPlatformApiAllowlist = map[string]bool{
810 "adservices-test-scenarios": true,
811 "aidl-cpp-java-test-interface-java": true,
812 "aidl-test-extras-java": true,
813 "aidl-test-interface-java": true,
814 "aidl-test-interface-permission-java": true,
815 "aidl_test_java_client_permission": true,
816 "aidl_test_java_client_sdk1": true,
817 "aidl_test_java_client_sdk29": true,
818 "aidl_test_java_client": true,
819 "aidl_test_java_service_permission": true,
820 "aidl_test_java_service_sdk1": true,
821 "aidl_test_java_service_sdk29": true,
822 "aidl_test_java_service": true,
823 "aidl_test_loggable_interface-java": true,
824 "aidl_test_nonvintf_parcelable-V1-java": true,
825 "aidl_test_nonvintf_parcelable-V2-java": true,
826 "aidl_test_unstable_parcelable-java": true,
827 "aidl_test_vintf_parcelable-V1-java": true,
828 "aidl_test_vintf_parcelable-V2-java": true,
829 "android.aidl.test.trunk-V1-java": true,
830 "android.aidl.test.trunk-V2-java": true,
831 "android.frameworks.location.altitude-V1-java": true,
832 "android.frameworks.location.altitude-V2-java": true,
833 "android.frameworks.stats-V1-java": true,
834 "android.frameworks.stats-V2-java": true,
835 "android.frameworks.stats-V3-java": true,
836 "android.hardware.authsecret-V1-java": true,
837 "android.hardware.authsecret-V2-java": true,
838 "android.hardware.biometrics.common-V1-java": true,
839 "android.hardware.biometrics.common-V2-java": true,
840 "android.hardware.biometrics.common-V3-java": true,
841 "android.hardware.biometrics.common-V4-java": true,
842 "android.hardware.biometrics.face-V1-java": true,
843 "android.hardware.biometrics.face-V2-java": true,
844 "android.hardware.biometrics.face-V3-java": true,
845 "android.hardware.biometrics.face-V4-java": true,
846 "android.hardware.biometrics.fingerprint-V1-java": true,
847 "android.hardware.biometrics.fingerprint-V2-java": true,
848 "android.hardware.biometrics.fingerprint-V3-java": true,
849 "android.hardware.biometrics.fingerprint-V4-java": true,
850 "android.hardware.bluetooth.lmp_event-V1-java": true,
851 "android.hardware.confirmationui-V1-java": true,
852 "android.hardware.confirmationui-V2-java": true,
853 "android.hardware.gatekeeper-V1-java": true,
854 "android.hardware.gatekeeper-V2-java": true,
855 "android.hardware.gnss-V1-java": true,
856 "android.hardware.gnss-V2-java": true,
857 "android.hardware.gnss-V3-java": true,
858 "android.hardware.gnss-V4-java": true,
859 "android.hardware.graphics.common-V1-java": true,
860 "android.hardware.graphics.common-V2-java": true,
861 "android.hardware.graphics.common-V3-java": true,
862 "android.hardware.graphics.common-V4-java": true,
863 "android.hardware.graphics.common-V5-java": true,
864 "android.hardware.identity-V1-java": true,
865 "android.hardware.identity-V2-java": true,
866 "android.hardware.identity-V3-java": true,
867 "android.hardware.identity-V4-java": true,
868 "android.hardware.identity-V5-java": true,
869 "android.hardware.identity-V6-java": true,
870 "android.hardware.keymaster-V1-java": true,
871 "android.hardware.keymaster-V2-java": true,
872 "android.hardware.keymaster-V3-java": true,
873 "android.hardware.keymaster-V4-java": true,
874 "android.hardware.keymaster-V5-java": true,
875 "android.hardware.oemlock-V1-java": true,
876 "android.hardware.oemlock-V2-java": true,
877 "android.hardware.power.stats-V1-java": true,
878 "android.hardware.power.stats-V2-java": true,
879 "android.hardware.power.stats-V3-java": true,
880 "android.hardware.power-V1-java": true,
881 "android.hardware.power-V2-java": true,
882 "android.hardware.power-V3-java": true,
883 "android.hardware.power-V4-java": true,
884 "android.hardware.power-V5-java": true,
885 "android.hardware.rebootescrow-V1-java": true,
886 "android.hardware.rebootescrow-V2-java": true,
887 "android.hardware.security.authgraph-V1-java": true,
888 "android.hardware.security.keymint-V1-java": true,
889 "android.hardware.security.keymint-V2-java": true,
890 "android.hardware.security.keymint-V3-java": true,
891 "android.hardware.security.keymint-V4-java": true,
Nikolay Elenkov7ee98922024-03-21 06:41:34 +0000892 "android.hardware.security.secretkeeper-V1-java": true,
Spandan Das8469e932024-02-20 16:47:07 +0000893 "android.hardware.security.secureclock-V1-java": true,
894 "android.hardware.security.secureclock-V2-java": true,
895 "android.hardware.thermal-V1-java": true,
896 "android.hardware.thermal-V2-java": true,
897 "android.hardware.threadnetwork-V1-java": true,
898 "android.hardware.weaver-V1-java": true,
899 "android.hardware.weaver-V2-java": true,
900 "android.hardware.weaver-V3-java": true,
901 "android.security.attestationmanager-java": true,
902 "android.security.authorization-java": true,
903 "android.security.compat-java": true,
904 "android.security.legacykeystore-java": true,
905 "android.security.maintenance-java": true,
906 "android.security.metrics-java": true,
907 "android.system.keystore2-V1-java": true,
908 "android.system.keystore2-V2-java": true,
909 "android.system.keystore2-V3-java": true,
910 "android.system.keystore2-V4-java": true,
911 "binderReadParcelIface-java": true,
912 "binderRecordReplayTestIface-java": true,
913 "car-experimental-api-static-lib": true,
914 "collector-device-lib-platform": true,
915 "com.android.car.oem": true,
916 "com.google.hardware.pixel.display-V10-java": true,
917 "com.google.hardware.pixel.display-V1-java": true,
918 "com.google.hardware.pixel.display-V2-java": true,
919 "com.google.hardware.pixel.display-V3-java": true,
920 "com.google.hardware.pixel.display-V4-java": true,
921 "com.google.hardware.pixel.display-V5-java": true,
922 "com.google.hardware.pixel.display-V6-java": true,
923 "com.google.hardware.pixel.display-V7-java": true,
924 "com.google.hardware.pixel.display-V8-java": true,
925 "com.google.hardware.pixel.display-V9-java": true,
926 "conscrypt-support": true,
927 "cts-keystore-test-util": true,
928 "cts-keystore-user-auth-helper-library": true,
929 "ctsmediautil": true,
930 "CtsNetTestsNonUpdatableLib": true,
931 "DpmWrapper": true,
932 "flickerlib-apphelpers": true,
933 "flickerlib-helpers": true,
934 "flickerlib-parsers": true,
935 "flickerlib": true,
936 "hardware.google.bluetooth.ccc-V1-java": true,
937 "hardware.google.bluetooth.sar-V1-java": true,
938 "monet": true,
939 "pixel-power-ext-V1-java": true,
940 "pixel-power-ext-V2-java": true,
941 "pixel_stateresidency_provider_aidl_interface-java": true,
942 "pixel-thermal-ext-V1-java": true,
943 "protolog-lib": true,
944 "RkpRegistrationCheck": true,
945 "rotary-service-javastream-protos": true,
946 "service_based_camera_extensions": true,
947 "statsd-helper-test": true,
948 "statsd-helper": true,
949 "test-piece-2-V1-java": true,
950 "test-piece-2-V2-java": true,
951 "test-piece-3-V1-java": true,
952 "test-piece-3-V2-java": true,
953 "test-piece-3-V3-java": true,
954 "test-piece-4-V1-java": true,
955 "test-piece-4-V2-java": true,
956 "test-root-package-V1-java": true,
957 "test-root-package-V2-java": true,
958 "test-root-package-V3-java": true,
959 "test-root-package-V4-java": true,
960 "testServiceIface-java": true,
961 "wm-flicker-common-app-helpers": true,
962 "wm-flicker-common-assertions": true,
963 "wm-shell-flicker-utils": true,
964 "wycheproof-keystore": true,
965 }
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000966
Spandan Das8469e932024-02-20 16:47:07 +0000967 // Union of aosp and internal allowlists
968 PlatformApiAllowlist = map[string]bool{}
969)
970
971func init() {
972 for k, v := range aospPlatformApiAllowlist {
973 PlatformApiAllowlist[k] = v
974 }
975}
976
977func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Spandan Das5ae65ee2024-04-16 22:03:26 +0000978 if disableSourceApexVariant(ctx) {
979 // Prebuilts are active, do not create the installation rules for the source javalib.
980 // Even though the source javalib is not used, we need to hide it to prevent duplicate installation rules.
981 // TODO (b/331665856): Implement a principled solution for this.
982 j.HideFromMake()
Spandan Das034af2c2024-10-30 21:45:09 +0000983 j.SkipInstall()
Spandan Das5ae65ee2024-04-16 22:03:26 +0000984 }
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000985 j.provideHiddenAPIPropertyInfo(ctx)
986
Jiyong Park92315372021-04-02 08:45:46 +0900987 j.sdkVersion = j.SdkVersion(ctx)
988 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000989 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900990
Jihoon Kanga3a05462024-04-05 00:36:44 +0000991 // Check min_sdk_version of the transitive dependencies if this module is created from
992 // java_sdk_library.
Spandan Dasb9c58352024-05-13 18:29:45 +0000993 if j.overridableProperties.Min_sdk_version != nil && j.SdkLibraryName() != nil {
Jihoon Kanga3a05462024-04-05 00:36:44 +0000994 j.CheckDepsMinSdkVersion(ctx)
995 }
996
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000997 // SdkLibrary.GenerateAndroidBuildActions(ctx) sets the stubsLinkType to Unknown.
998 // If the stubsLinkType has already been set to Unknown, the stubsLinkType should
999 // not be overridden.
1000 if j.stubsLinkType != Unknown {
1001 if proptools.Bool(j.properties.Is_stubs_module) {
1002 j.stubsLinkType = Stubs
1003 } else {
1004 j.stubsLinkType = Implementation
1005 }
1006 }
1007
yangbill2af0b6e2024-03-15 09:29:29 +00001008 j.stem = proptools.StringDefault(j.overridableProperties.Stem, ctx.ModuleName())
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001009
Sam Delmericoc8e040c2023-10-31 17:27:02 +00001010 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
Colin Cross40213022023-12-13 15:19:49 -08001011 android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo)
Colin Cross312634e2023-11-21 15:13:56 -08001012 exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList()
1013 j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...)
1014
1015 combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags")
1016 writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles)
1017 j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile
Sam Delmericoc8e040c2023-10-31 17:27:02 +00001018
Colin Crossff694a82023-12-13 15:54:49 -08001019 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07001020 if !apexInfo.IsForPlatform() {
1021 j.hideApexVariantFromMake = true
1022 }
1023
Artur Satayev2db1c3f2020-04-08 19:09:30 +01001024 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +00001025 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -08001026 if ctx.Device() {
Jihoon Kanga3a05462024-04-05 00:36:44 +00001027 libName := j.Name()
1028 if j.SdkLibraryName() != nil && strings.HasSuffix(libName, ".impl") {
1029 libName = proptools.String(j.SdkLibraryName())
1030 }
Colin Cross61df14a2021-12-01 13:04:46 -08001031 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Jihoon Kanga3a05462024-04-05 00:36:44 +00001032 ctx, libName, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross61df14a2021-12-01 13:04:46 -08001033 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
1034 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
1035 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
1036 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Spandan Das0727ba72024-02-13 16:37:43 +00001037 if j.usesLibrary.shouldDisableDexpreopt {
1038 j.dexpreopter.disableDexpreopt()
1039 }
Colin Cross61df14a2021-12-01 13:04:46 -08001040 }
Yu Liu460cf372025-01-10 00:34:06 +00001041 javaInfo := j.compile(ctx, nil, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -07001042
Cole Faustb9c67e22024-10-08 16:39:56 -07001043 j.setInstallRules(ctx)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001044
1045 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
1046 TestOnly: Bool(j.sourceProperties.Test_only),
1047 TopLevelTarget: j.sourceProperties.Top_level_test_target,
1048 })
mrziwang9f7b9f42024-07-10 12:18:06 -07001049
Yu Liu460cf372025-01-10 00:34:06 +00001050 if javaInfo != nil {
1051 setExtraJavaInfo(ctx, j, javaInfo)
1052 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
1053 }
1054
mrziwang9f7b9f42024-07-10 12:18:06 -07001055 setOutputFiles(ctx, j.Module)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001056}
1057
Cole Faustb9c67e22024-10-08 16:39:56 -07001058func (j *Library) getJarInstallDir(ctx android.ModuleContext) android.InstallPath {
1059 var installDir android.InstallPath
1060 if ctx.InstallInTestcases() {
1061 var archDir string
1062 if !ctx.Host() {
1063 archDir = ctx.DeviceConfig().DeviceArch()
1064 }
1065 installModuleName := ctx.ModuleName()
1066 // If this module is an impl library created from java_sdk_library,
1067 // install the files under the java_sdk_library module outdir instead of this module outdir.
1068 if j.SdkLibraryName() != nil && strings.HasSuffix(j.Name(), ".impl") {
1069 installModuleName = proptools.String(j.SdkLibraryName())
1070 }
1071 installDir = android.PathForModuleInstall(ctx, installModuleName, archDir)
1072 } else {
1073 installDir = android.PathForModuleInstall(ctx, "framework")
1074 }
1075 return installDir
1076}
1077
1078func (j *Library) setInstallRules(ctx android.ModuleContext) {
Jihoon Kanga3a05462024-04-05 00:36:44 +00001079 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
1080
1081 if (Bool(j.properties.Installable) || ctx.Host()) && apexInfo.IsForPlatform() {
Colin Cross09ad3a62023-11-15 12:29:33 -08001082 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -07001083 if j.InstallMixin != nil {
1084 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
1085 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001086 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
1087 if hostDexNeeded {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07001088 j.hostdexInstallFile = ctx.InstallFileWithoutCheckbuild(
Colin Cross3108ce12021-11-10 14:38:50 -08001089 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001090 j.Stem()+"-hostdex.jar", j.outputFile)
1091 }
Cole Faustb9c67e22024-10-08 16:39:56 -07001092 j.installFile = ctx.InstallFileWithoutCheckbuild(j.getJarInstallDir(ctx), j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -07001093 }
Colin Crossb7a63242015-04-16 14:09:14 -07001094}
1095
Colin Crossf506d872017-07-19 15:53:04 -07001096func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Ulya Trafimoviche4432872021-08-18 16:57:11 +01001097 j.usesLibrary.deps(ctx, false)
Jiakai Zhangf98da192024-04-15 11:15:41 +00001098 j.deps(ctx)
Jihoon Kanga3a05462024-04-05 00:36:44 +00001099
1100 if j.SdkLibraryName() != nil && strings.HasSuffix(j.Name(), ".impl") {
1101 if dexpreopt.IsDex2oatNeeded(ctx) {
1102 dexpreopt.RegisterToolDeps(ctx)
1103 }
1104 prebuiltSdkLibExists := ctx.OtherModuleExists(android.PrebuiltNameFromSource(proptools.String(j.SdkLibraryName())))
1105 if prebuiltSdkLibExists && ctx.OtherModuleExists("all_apex_contributions") {
1106 ctx.AddDependency(ctx.Module(), android.AcDepTag, "all_apex_contributions")
1107 }
1108 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001109}
1110
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001111const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001112 aidlIncludeDir = "aidl"
1113 javaDir = "java"
1114 jarFileSuffix = ".jar"
1115 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001116)
1117
Paul Duffina0dbf432019-12-05 11:25:53 +00001118// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +00001119func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +00001120 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001121}
1122
Paul Duffina04c1072020-03-02 10:16:35 +00001123func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
1124 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001125}
1126
Paul Duffin13879572019-11-28 14:31:38 +00001127type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +00001128 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +00001129
1130 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001131 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +00001132 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
1133
1134 // Function to compute the snapshot relative path to which the named library's
1135 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +00001136 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +00001137
1138 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
1139 // files like aidl files should also be copied.
1140 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +00001141}
1142
Paul Duffindb170e42020-12-08 17:48:25 +00001143const (
1144 onlyCopyJarToSnapshot = true
1145 copyEverythingToSnapshot = false
1146)
1147
Paul Duffin296701e2021-07-14 10:29:36 +01001148func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1149 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +00001150}
1151
1152func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
1153 _, ok := module.(*Library)
1154 return ok
1155}
1156
Paul Duffin3a4eb502020-03-19 16:11:18 +00001157func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1158 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001159}
Paul Duffina0dbf432019-12-05 11:25:53 +00001160
Paul Duffin14eb4672020-03-02 11:33:02 +00001161func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +00001162 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +00001163}
1164
1165type librarySdkMemberProperties struct {
1166 android.SdkMemberPropertiesBase
1167
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001168 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +00001169 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +01001170
1171 // The list of permitted packages that need to be passed to the prebuilts as they are used to
1172 // create the updatable-bcp-packages.txt file.
1173 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +00001174
1175 // The value of the min_sdk_version property, translated into a number where possible.
1176 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001177
1178 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +00001179}
1180
Paul Duffin3a4eb502020-03-19 16:11:18 +00001181func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +00001182 j := variant.(*Library)
1183
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001184 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +00001185
Paul Duffina551a1c2020-03-17 21:04:24 +00001186 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +01001187
1188 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +00001189
1190 // If the min_sdk_version was set then add the canonical representation of the API level to the
1191 // snapshot.
Spandan Dasb9c58352024-05-13 18:29:45 +00001192 if j.overridableProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -07001193 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
1194 if err != nil {
1195 ctx.ModuleErrorf("%s", err)
1196 }
Paul Duffinbb638eb2022-11-26 13:36:38 +00001197 p.MinSdkVersion = proptools.StringPtr(canonical)
1198 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001199
1200 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
1201 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
1202 }
Paul Duffin14eb4672020-03-02 11:33:02 +00001203}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001204
Paul Duffin3a4eb502020-03-19 16:11:18 +00001205func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001206 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001207
Paul Duffindb170e42020-12-08 17:48:25 +00001208 memberType := ctx.MemberType().(*librarySdkMemberType)
1209
Paul Duffina551a1c2020-03-17 21:04:24 +00001210 exportedJar := p.JarToExport
1211 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +00001212 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +00001213 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +00001214
1215 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +00001216 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
1217
Paul Duffina551a1c2020-03-17 21:04:24 +00001218 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
1219 }
1220
Paul Duffinbb638eb2022-11-26 13:36:38 +00001221 if p.MinSdkVersion != nil {
1222 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
1223 }
1224
Paul Duffin869de142021-07-15 14:14:41 +01001225 if len(p.PermittedPackages) > 0 {
1226 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
1227 }
1228
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08001229 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
1230 if p.DexPreoptProfileGuided != nil {
1231 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
1232 }
1233
Paul Duffindb170e42020-12-08 17:48:25 +00001234 // Do not copy anything else to the snapshot.
1235 if memberType.onlyCopyJarToSnapshot {
1236 return
1237 }
1238
Paul Duffina551a1c2020-03-17 21:04:24 +00001239 aidlIncludeDirs := p.AidlIncludeDirs
1240 if len(aidlIncludeDirs) != 0 {
1241 sdkModuleContext := ctx.SdkModuleContext()
1242 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +00001243 // TODO(jiyong): copy parcelable declarations only
1244 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
1245 for _, file := range aidlFiles {
1246 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
1247 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001248 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001249
Paul Duffina551a1c2020-03-17 21:04:24 +00001250 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +00001251 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001252}
1253
Colin Cross1b16b0e2019-02-12 14:41:32 -08001254// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
1255//
1256// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
1257// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
1258// as a `static_libs` dependency of another module.
1259//
1260// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
1261// a device.
1262//
1263// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1264// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -07001265func LibraryFactory() android.Module {
1266 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -07001267
Colin Crossce6734e2020-06-15 16:09:53 -07001268 module.addHostAndDeviceProperties()
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001269 module.AddProperties(&module.sourceProperties)
Colin Cross2fe66872015-03-30 17:20:39 -07001270
Paul Duffin71b33cc2021-06-23 11:39:47 +01001271 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01001272
Jiyong Park7f7766d2019-07-25 22:02:35 +09001273 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001274 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -07001275 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001276}
1277
Colin Cross1b16b0e2019-02-12 14:41:32 -08001278// java_library_static is an obsolete alias for java_library.
1279func LibraryStaticFactory() android.Module {
1280 return LibraryFactory()
1281}
1282
1283// java_library_host builds and links sources into a `.jar` file for the host.
1284//
1285// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
1286// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001287func LibraryHostFactory() android.Module {
1288 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -07001289
Colin Crossce6734e2020-06-15 16:09:53 -07001290 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -07001291
Colin Cross9ae1b922018-06-26 17:59:05 -07001292 module.Module.properties.Installable = proptools.BoolPtr(true)
1293
Jiyong Park7f7766d2019-07-25 22:02:35 +09001294 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09001295 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -07001296 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001297}
1298
1299//
Colin Crossb628ea52018-08-14 16:42:33 -07001300// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -07001301//
1302
Dan Shi95d19422020-08-15 12:24:26 -07001303// Test option struct.
1304type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +08001305 android.CommonTestOptions
1306
Dan Shi95d19422020-08-15 12:24:26 -07001307 // a list of extra test configuration files that should be installed with the module.
1308 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -08001309
1310 // Extra <option> tags to add to the auto generated test xml file. The "key"
1311 // is optional in each of these.
1312 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +00001313
1314 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
1315 // The "key" is optional in each of these.
1316 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -07001317}
1318
Colin Cross05638fc2018-04-09 18:40:24 -07001319type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -07001320 // list of compatibility suites (for example "cts", "vts") that the module should be
1321 // installed into.
1322 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -07001323
1324 // the name of the test configuration (for example "AndroidTest.xml") that should be
1325 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -08001326 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -07001327
Jack He33338892018-09-19 02:21:28 -07001328 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
1329 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -08001330 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -07001331
Colin Crossd96ca352018-08-10 16:06:24 -07001332 // list of files or filegroup modules that provide data that should be installed alongside
1333 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +09001334 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001335
Cole Faust65cb40a2024-10-21 15:41:42 -07001336 // Same as data, but will add dependencies on modules using the device's os variation and
1337 // the common arch variation. Useful for a host test that wants to embed a module built for
1338 // device.
1339 Device_common_data []string `android:"path_device_common"`
1340
1341 // same as data, but adds dependencies using the device's os variation and the device's first
1342 // architecture's variation. Can be used to add a module built for device to the data of a
1343 // host test.
1344 Device_first_data []string `android:"path_device_first"`
1345
Cole Faust18f03f12024-10-23 14:51:11 -07001346 // same as data, but adds dependencies using the device's os variation and the device's first
1347 // 32-bit architecture's variation. If a 32-bit arch doesn't exist for this device, it will use
1348 // a 64 bit arch instead. Can be used to add a module built for device to the data of a
1349 // host test.
1350 Device_first_prefer32_data []string `android:"path_device_first_prefer32"`
1351
Dan Shi6ffaaa82019-09-26 11:41:36 -07001352 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1353 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1354 // explicitly.
1355 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +08001356
1357 // Add parameterized mainline modules to auto generated test config. The options will be
1358 // handled by TradeFed to do downloading and installing the specified modules on the device.
1359 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -07001360
1361 // Test options.
1362 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -08001363
1364 // Names of modules containing JNI libraries that should be installed alongside the test.
Jihoon Kang6d39c702024-09-30 20:50:38 +00001365 Jni_libs proptools.Configurable[[]string]
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001366
1367 // Install the test into a folder named for the module in all test suites.
1368 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -07001369}
1370
Liz Kammerdd849a82020-06-12 16:38:45 -07001371type hostTestProperties struct {
1372 // list of native binary modules that should be installed alongside the test
1373 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +00001374
1375 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +00001376 // This property only adds the first variant of the dependency
1377 Data_device_bins_first []string `android:"arch_variant"`
1378
1379 // list of device binary modules that should be installed alongside the test
1380 // This property adds 64bit AND 32bit variants of the dependency
1381 Data_device_bins_both []string `android:"arch_variant"`
1382
1383 // list of device binary modules that should be installed alongside the test
1384 // This property only adds 64bit variants of the dependency
1385 Data_device_bins_64 []string `android:"arch_variant"`
1386
1387 // list of device binary modules that should be installed alongside the test
1388 // This property adds 32bit variants of the dependency if available, or else
1389 // defaults to the 64bit variant
1390 Data_device_bins_prefer32 []string `android:"arch_variant"`
1391
1392 // list of device binary modules that should be installed alongside the test
1393 // This property only adds 32bit variants of the dependency
1394 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001395}
1396
Paul Duffin42df1442019-03-20 12:45:53 +00001397type testHelperLibraryProperties struct {
1398 // list of compatibility suites (for example "cts", "vts") that the module should be
1399 // installed into.
1400 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001401
1402 // Install the test into a folder named for the module in all test suites.
1403 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001404}
1405
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001406type prebuiltTestProperties struct {
1407 // list of compatibility suites (for example "cts", "vts") that the module should be
1408 // installed into.
1409 Test_suites []string `android:"arch_variant"`
1410
1411 // the name of the test configuration (for example "AndroidTest.xml") that should be
1412 // installed with the module.
1413 Test_config *string `android:"path,arch_variant"`
1414}
1415
Colin Cross05638fc2018-04-09 18:40:24 -07001416type Test struct {
1417 Library
1418
1419 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001420
Dan Shi95d19422020-08-15 12:24:26 -07001421 testConfig android.Path
1422 extraTestConfigs android.Paths
1423 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001424}
1425
Liz Kammerdd849a82020-06-12 16:38:45 -07001426type TestHost struct {
1427 Test
1428
1429 testHostProperties hostTestProperties
1430}
1431
Paul Duffin42df1442019-03-20 12:45:53 +00001432type TestHelperLibrary struct {
1433 Library
1434
1435 testHelperLibraryProperties testHelperLibraryProperties
1436}
1437
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001438type JavaTestImport struct {
1439 Import
1440
1441 prebuiltTestProperties prebuiltTestProperties
1442
1443 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001444 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001445}
1446
Colin Cross24cc4be62021-11-03 14:09:41 -07001447func (j *Test) InstallInTestcases() bool {
1448 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1449 // testcases by base_rules.mk.
1450 return !j.Host()
1451}
1452
1453func (j *TestHelperLibrary) InstallInTestcases() bool {
1454 return true
1455}
1456
1457func (j *JavaTestImport) InstallInTestcases() bool {
1458 return true
1459}
1460
Colin Crosse1a85552024-06-14 12:17:37 -07001461func (j *TestHost) IsNativeCoverageNeeded(ctx cc.IsNativeCoverageNeededContext) bool {
Yu Liud8aa2002023-10-05 11:40:06 -07001462 return ctx.DeviceConfig().NativeCoverageEnabled()
1463}
1464
Sam Delmericocc271e22022-06-01 15:45:02 +00001465func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1466 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1467 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1468 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1469 }
1470
1471 var maybeAndroid32Target *android.Target
1472 var maybeAndroid64Target *android.Target
1473 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1474 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1475 if len(android32TargetList) > 0 {
1476 maybeAndroid32Target = &android32TargetList[0]
1477 }
1478 if len(android64TargetList) > 0 {
1479 maybeAndroid64Target = &android64TargetList[0]
1480 }
1481
1482 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1483 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1484 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1485 return
1486 }
1487 if maybeAndroid32Target != nil {
1488 ctx.AddFarVariationDependencies(
1489 maybeAndroid32Target.Variations(),
1490 dataDeviceBinsTag,
1491 j.testHostProperties.Data_device_bins_both...,
1492 )
1493 }
1494 if maybeAndroid64Target != nil {
1495 ctx.AddFarVariationDependencies(
1496 maybeAndroid64Target.Variations(),
1497 dataDeviceBinsTag,
1498 j.testHostProperties.Data_device_bins_both...,
1499 )
1500 }
1501 }
1502
1503 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1504 if maybeAndroid32Target != nil {
1505 ctx.AddFarVariationDependencies(
1506 maybeAndroid32Target.Variations(),
1507 dataDeviceBinsTag,
1508 j.testHostProperties.Data_device_bins_prefer32...,
1509 )
1510 } else {
1511 if maybeAndroid64Target == nil {
1512 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1513 return
1514 }
1515 ctx.AddFarVariationDependencies(
1516 maybeAndroid64Target.Variations(),
1517 dataDeviceBinsTag,
1518 j.testHostProperties.Data_device_bins_prefer32...,
1519 )
1520 }
1521 }
1522
1523 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1524 if maybeAndroid32Target == nil {
1525 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1526 return
1527 }
1528 deviceVariations := maybeAndroid32Target.Variations()
1529 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1530 }
1531
1532 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1533 if maybeAndroid64Target == nil {
1534 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1535 return
1536 }
1537 deviceVariations := maybeAndroid64Target.Variations()
1538 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1539 }
1540}
1541
Liz Kammerdd849a82020-06-12 16:38:45 -07001542func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1543 if len(j.testHostProperties.Data_native_bins) > 0 {
1544 for _, target := range ctx.MultiTargets() {
1545 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1546 }
1547 }
1548
Jihoon Kang6d39c702024-09-30 20:50:38 +00001549 jniLibs := j.testProperties.Jni_libs.GetOrDefault(ctx, nil)
1550 if len(jniLibs) > 0 {
Colin Crossf8d9c492021-01-26 11:01:43 -08001551 for _, target := range ctx.MultiTargets() {
1552 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
Jihoon Kang6d39c702024-09-30 20:50:38 +00001553 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, jniLibs...)
Colin Crossf8d9c492021-01-26 11:01:43 -08001554 }
1555 }
1556
Sam Delmericocc271e22022-06-01 15:45:02 +00001557 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001558 j.deps(ctx)
1559}
1560
Yuexi Ma627263f2021-03-04 13:47:56 -08001561func (j *TestHost) AddExtraResource(p android.Path) {
1562 j.extraResources = append(j.extraResources, p)
1563}
1564
Sam Delmericocc271e22022-06-01 15:45:02 +00001565func (j *TestHost) dataDeviceBins() []string {
1566 ret := make([]string, 0,
1567 len(j.testHostProperties.Data_device_bins_first)+
1568 len(j.testHostProperties.Data_device_bins_both)+
1569 len(j.testHostProperties.Data_device_bins_prefer32)+
1570 len(j.testHostProperties.Data_device_bins_32)+
1571 len(j.testHostProperties.Data_device_bins_64),
1572 )
1573
1574 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1575 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1576 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1577 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1578 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1579
1580 return ret
1581}
1582
Sam Delmericob3342ce2022-01-20 21:10:28 +00001583func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1584 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001585 dataDeviceBins := j.dataDeviceBins()
1586 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001587 // add Tradefed configuration to push device bins to device for testing
1588 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1589 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001590 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001591 fullPath := filepath.Join(remoteDir, bin)
1592 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1593 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001594 configs = append(configs, tradefed.Object{
1595 Type: "target_preparer",
1596 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1597 Options: options,
1598 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001599 }
1600
1601 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +00001602 android.SetProvider(ctx, tradefed.BaseTestProviderKey, tradefed.BaseTestProviderData{
Ronald Braunsteinf424c9a2024-10-22 01:41:20 +00001603 TestcaseRelDataFiles: testcaseRel(j.data),
1604 OutputFile: j.outputFile,
1605 TestConfig: j.testConfig,
1606 RequiredModuleNames: j.RequiredModuleNames(ctx),
1607 TestSuites: j.testProperties.Test_suites,
1608 IsHost: true,
1609 LocalSdkVersion: j.sdkVersion.String(),
1610 IsUnitTest: Bool(j.testProperties.Test_options.Unit_test),
1611 MkInclude: "$(BUILD_SYSTEM)/soong_java_prebuilt.mk",
1612 MkAppClass: "JAVA_LIBRARIES",
Ronald Braunstein1a6e7c02024-03-14 21:14:39 +00001613 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001614}
1615
Colin Cross303e21f2018-08-07 16:49:25 -07001616func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Spandan Dasb0410872024-06-25 03:30:03 +00001617 checkMinSdkVersionMts(ctx, j.MinSdkVersion(ctx))
Sam Delmericob3342ce2022-01-20 21:10:28 +00001618 j.generateAndroidBuildActionsWithConfig(ctx, nil)
1619}
1620
1621func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001622 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1623 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001624 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001625 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1626 }
Cole Faust21680542022-12-07 18:18:37 -08001627 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1628 TestConfigProp: j.testProperties.Test_config,
1629 TestConfigTemplateProp: j.testProperties.Test_config_template,
1630 TestSuites: j.testProperties.Test_suites,
1631 Config: configs,
1632 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001633 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001634 AutoGenConfig: j.testProperties.Auto_gen_config,
1635 UnitTest: j.testProperties.Test_options.Unit_test,
1636 DeviceTemplate: "${JavaTestConfigTemplate}",
1637 HostTemplate: "${JavaHostTestConfigTemplate}",
1638 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1639 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001640
Colin Cross8a497952019-03-05 22:25:09 -08001641 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Cole Faust65cb40a2024-10-21 15:41:42 -07001642 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_common_data)...)
1643 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_first_data)...)
Cole Faust18f03f12024-10-23 14:51:11 -07001644 j.data = append(j.data, android.PathsForModuleSrc(ctx, j.testProperties.Device_first_prefer32_data)...)
Colin Cross303e21f2018-08-07 16:49:25 -07001645
Dan Shi95d19422020-08-15 12:24:26 -07001646 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1647
Liz Kammerdd849a82020-06-12 16:38:45 -07001648 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1649 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1650 })
1651
Sam Delmericob3342ce2022-01-20 21:10:28 +00001652 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1653 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1654 })
1655
Colin Crossb614cd42024-10-11 12:52:21 -07001656 var directImplementationDeps android.Paths
1657 var transitiveImplementationDeps []depset.DepSet[android.Path]
Colin Crossf8d9c492021-01-26 11:01:43 -08001658 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001659 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
Colin Crossf8d9c492021-01-26 11:01:43 -08001660 if sharedLibInfo.SharedLibrary != nil {
1661 // Copy to an intermediate output directory to append "lib[64]" to the path,
1662 // so that it's compatible with the default rpath values.
1663 var relPath string
1664 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1665 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1666 } else {
1667 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1668 }
1669 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1670 ctx.Build(pctx, android.BuildParams{
1671 Rule: android.Cp,
1672 Input: sharedLibInfo.SharedLibrary,
1673 Output: relocatedLib,
1674 })
1675 j.data = append(j.data, relocatedLib)
Colin Crossb614cd42024-10-11 12:52:21 -07001676
1677 directImplementationDeps = append(directImplementationDeps, android.OutputFileForModule(ctx, dep, ""))
1678 if info, ok := android.OtherModuleProvider(ctx, dep, cc.ImplementationDepInfoProvider); ok {
1679 transitiveImplementationDeps = append(transitiveImplementationDeps, info.ImplementationDeps)
1680 }
Colin Crossf8d9c492021-01-26 11:01:43 -08001681 } else {
1682 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1683 }
1684 })
1685
Colin Crossb614cd42024-10-11 12:52:21 -07001686 android.SetProvider(ctx, cc.ImplementationDepInfoProvider, &cc.ImplementationDepInfo{
1687 ImplementationDeps: depset.New(depset.PREORDER, directImplementationDeps, transitiveImplementationDeps),
1688 })
1689
Colin Cross303e21f2018-08-07 16:49:25 -07001690 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001691}
1692
Paul Duffin42df1442019-03-20 12:45:53 +00001693func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1694 j.Library.GenerateAndroidBuildActions(ctx)
1695}
1696
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001697func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001698 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1699 TestConfigProp: j.prebuiltTestProperties.Test_config,
1700 TestSuites: j.prebuiltTestProperties.Test_suites,
1701 DeviceTemplate: "${JavaTestConfigTemplate}",
1702 HostTemplate: "${JavaHostTestConfigTemplate}",
1703 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1704 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001705
1706 j.Import.GenerateAndroidBuildActions(ctx)
1707}
1708
1709type testSdkMemberType struct {
1710 android.SdkMemberTypeBase
1711}
1712
Paul Duffin296701e2021-07-14 10:29:36 +01001713func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1714 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001715}
1716
1717func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1718 _, ok := module.(*Test)
1719 return ok
1720}
1721
Paul Duffin3a4eb502020-03-19 16:11:18 +00001722func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1723 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001724}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001725
Paul Duffin14eb4672020-03-02 11:33:02 +00001726func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1727 return &testSdkMemberProperties{}
1728}
1729
1730type testSdkMemberProperties struct {
1731 android.SdkMemberPropertiesBase
1732
Paul Duffina551a1c2020-03-17 21:04:24 +00001733 JarToExport android.Path
1734 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001735}
1736
Paul Duffin3a4eb502020-03-19 16:11:18 +00001737func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001738 test := variant.(*Test)
1739
1740 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001741 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001742 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001743 }
1744
Paul Duffina551a1c2020-03-17 21:04:24 +00001745 p.JarToExport = implementationJars[0]
1746 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001747}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001748
Paul Duffin3a4eb502020-03-19 16:11:18 +00001749func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001750 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001751
Paul Duffina551a1c2020-03-17 21:04:24 +00001752 exportedJar := p.JarToExport
1753 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001754 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001755 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001756
1757 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001758 }
1759
1760 testConfig := p.TestConfig
1761 if testConfig != nil {
1762 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1763 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001764 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1765 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001766}
1767
Colin Cross1b16b0e2019-02-12 14:41:32 -08001768// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1769// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1770//
1771// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1772// compiled against the device bootclasspath.
1773//
1774// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1775// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001776func TestFactory() android.Module {
1777 module := &Test{}
1778
Colin Crossce6734e2020-06-15 16:09:53 -07001779 module.addHostAndDeviceProperties()
1780 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001781
Colin Cross9ae1b922018-06-26 17:59:05 -07001782 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001783 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001784 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001785 module.Module.sourceProperties.Test_only = proptools.BoolPtr(true)
1786 module.Module.sourceProperties.Top_level_test_target = true
Colin Cross9ae1b922018-06-26 17:59:05 -07001787
Colin Cross05638fc2018-04-09 18:40:24 -07001788 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001789 return module
1790}
1791
Paul Duffin42df1442019-03-20 12:45:53 +00001792// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1793func TestHelperLibraryFactory() android.Module {
1794 module := &TestHelperLibrary{}
1795
Colin Crossce6734e2020-06-15 16:09:53 -07001796 module.addHostAndDeviceProperties()
1797 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001798
Colin Cross9a4abed2019-04-24 13:19:28 -07001799 module.Module.properties.Installable = proptools.BoolPtr(true)
1800 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001801 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001802 module.Module.sourceProperties.Test_only = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001803
Paul Duffin42df1442019-03-20 12:45:53 +00001804 InitJavaModule(module, android.HostAndDeviceSupported)
1805 return module
1806}
1807
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001808// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1809// and makes sure that it is added to the appropriate test suite.
1810//
1811// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1812// compiled against an Android classpath.
1813//
1814// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1815// for host modules.
1816func JavaTestImportFactory() android.Module {
1817 module := &JavaTestImport{}
1818
1819 module.AddProperties(
1820 &module.Import.properties,
1821 &module.prebuiltTestProperties)
1822
1823 module.Import.properties.Installable = proptools.BoolPtr(true)
1824
1825 android.InitPrebuiltModule(module, &module.properties.Jars)
1826 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001827 InitJavaModule(module, android.HostAndDeviceSupported)
1828 return module
1829}
1830
Colin Cross1b16b0e2019-02-12 14:41:32 -08001831// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1832// allow running the test with `atest` or a `TEST_MAPPING` file.
1833//
1834// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1835// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001836func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001837 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001838
Colin Crossce6734e2020-06-15 16:09:53 -07001839 module.addHostProperties()
1840 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001841 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001842
Yuexi Ma627263f2021-03-04 13:47:56 -08001843 InitTestHost(
1844 module,
1845 proptools.BoolPtr(true),
1846 nil,
1847 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001848
Liz Kammerdd849a82020-06-12 16:38:45 -07001849 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001850
Colin Cross05638fc2018-04-09 18:40:24 -07001851 return module
1852}
1853
Yuexi Ma627263f2021-03-04 13:47:56 -08001854func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1855 th.properties.Installable = installable
1856 th.testProperties.Auto_gen_config = autoGenConfig
1857 th.testProperties.Test_suites = testSuites
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001858 th.sourceProperties.Test_only = proptools.BoolPtr(true)
1859 th.sourceProperties.Top_level_test_target = true
Yuexi Ma627263f2021-03-04 13:47:56 -08001860}
1861
Colin Cross05638fc2018-04-09 18:40:24 -07001862//
Colin Cross2fe66872015-03-30 17:20:39 -07001863// Java Binaries (.jar file plus wrapper script)
1864//
1865
Colin Crossf506d872017-07-19 15:53:04 -07001866type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001867 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001868 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001869
1870 // Name of the class containing main to be inserted into the manifest as Main-Class.
1871 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001872
Spandan Dase42c5d92024-10-03 22:39:52 +00001873 // Names of modules containing JNI libraries that should be installed alongside the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001874 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001875}
1876
Colin Crossf506d872017-07-19 15:53:04 -07001877type Binary struct {
1878 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001879
Colin Crossf506d872017-07-19 15:53:04 -07001880 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001881
Colin Crossc3315992017-12-08 19:12:36 -08001882 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001883 binaryFile android.InstallPath
Spandan Dase42c5d92024-10-03 22:39:52 +00001884
1885 androidMkNamesOfJniLibs []string
Colin Cross2fe66872015-03-30 17:20:39 -07001886}
1887
Alex Light24237172017-10-26 09:46:21 -07001888func (j *Binary) HostToolPath() android.OptionalPath {
1889 return android.OptionalPathForPath(j.binaryFile)
1890}
1891
Colin Crossf506d872017-07-19 15:53:04 -07001892func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
yangbill2af0b6e2024-03-15 09:29:29 +00001893 j.stem = proptools.StringDefault(j.overridableProperties.Stem, ctx.ModuleName())
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001894
Cole Faustb9c67e22024-10-08 16:39:56 -07001895 // Handle the binary wrapper. This comes before compiling the jar so that the wrapper
1896 // is the first PackagingSpec
1897 if j.binaryProperties.Wrapper != nil {
1898 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Nan Zhang3c807db2017-11-03 14:53:31 -07001899 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001900 if ctx.Windows() {
Cole Faustb9c67e22024-10-08 16:39:56 -07001901 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001902 }
1903
Cole Faustb9c67e22024-10-08 16:39:56 -07001904 if ctx.Device() {
1905 // device binary should have a main_class property if it does not
1906 // have a specific wrapper, so that a default wrapper can
1907 // be generated for it.
1908 if j.binaryProperties.Main_class == nil {
1909 ctx.PropertyErrorf("main_class", "main_class property "+
1910 "is required for device binary if no default wrapper is assigned")
1911 } else {
1912 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1913 jarName := j.Stem() + ".jar"
1914 partition := j.PartitionTag(ctx.DeviceConfig())
1915 ctx.Build(pctx, android.BuildParams{
1916 Rule: deviceBinaryWrapper,
1917 Output: wrapper,
1918 Args: map[string]string{
1919 "jar_name": jarName,
1920 "partition": partition,
1921 "main_class": String(j.binaryProperties.Main_class),
1922 },
1923 })
1924 j.wrapperFile = wrapper
Spandan Dase42c5d92024-10-03 22:39:52 +00001925 }
Cole Faustb9c67e22024-10-08 16:39:56 -07001926 } else {
1927 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1928 }
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001929 }
Cole Faustb9c67e22024-10-08 16:39:56 -07001930
1931 ext := ""
1932 if ctx.Windows() {
1933 ext = ".bat"
1934 }
1935
1936 // The host installation rules make the installed wrapper depend on all the dependencies
1937 // of the wrapper variant, which will include the common variant's jar file and any JNI
1938 // libraries. This is verified by TestBinary. Also make it depend on the jar file so that
1939 // the binary file timestamp will update when the jar file timestamp does. The jar file is
1940 // built later on, in j.Library.GenerateAndroidBuildActions, so we have to create an identical
1941 // installpath representing it here.
1942 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
1943 ctx.ModuleName()+ext, j.wrapperFile, j.getJarInstallDir(ctx).Join(ctx, j.Stem()+".jar"))
1944
1945 // Set the jniLibs of this binary.
1946 // These will be added to `LOCAL_REQUIRED_MODULES`, and the kati packaging system will
1947 // install these alongside the java binary.
1948 ctx.VisitDirectDepsWithTag(jniInstallTag, func(jni android.Module) {
1949 // Use the BaseModuleName of the dependency (without any prebuilt_ prefix)
1950 bmn, _ := jni.(interface{ BaseModuleName() string })
1951 j.androidMkNamesOfJniLibs = append(j.androidMkNamesOfJniLibs, bmn.BaseModuleName()+":"+jni.Target().Arch.ArchType.Bitness())
1952 })
1953 // Check that native libraries are not listed in `required`. Prompt users to use `jni_libs` instead.
1954 ctx.VisitDirectDepsWithTag(android.RequiredDepTag, func(dep android.Module) {
1955 if _, hasSharedLibraryInfo := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider); hasSharedLibraryInfo {
1956 ctx.ModuleErrorf("cc_library %s is no longer supported in `required` of java_binary modules. Please use jni_libs instead.", dep.Name())
1957 }
1958 })
1959
1960 // Compile the jar
1961 if j.binaryProperties.Main_class != nil {
1962 if j.properties.Manifest != nil {
1963 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1964 }
1965 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1966 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1967 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1968 }
1969
1970 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross2fe66872015-03-30 17:20:39 -07001971}
1972
Colin Crossf506d872017-07-19 15:53:04 -07001973func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Cole Faustb9c67e22024-10-08 16:39:56 -07001974 j.deps(ctx)
Cole Faust3dac4862024-08-19 16:56:11 -07001975 // These dependencies ensure the installation rules will install the jar file when the
Spandan Dase42c5d92024-10-03 22:39:52 +00001976 // wrapper is installed, and the jni libraries when the wrapper is installed.
Cole Faustb9c67e22024-10-08 16:39:56 -07001977 if ctx.Os().Class == android.Host {
1978 ctx.AddVariationDependencies(ctx.Config().BuildOSTarget.Variations(), jniInstallTag, j.binaryProperties.Jni_libs...)
1979 } else if ctx.Os().Class == android.Device {
1980 ctx.AddVariationDependencies(ctx.Config().AndroidFirstDeviceTarget.Variations(), jniInstallTag, j.binaryProperties.Jni_libs...)
1981 } else {
1982 ctx.ModuleErrorf("Unknown os class")
Colin Cross6b4a32d2017-12-05 13:42:45 -08001983 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001984}
1985
Colin Cross1b16b0e2019-02-12 14:41:32 -08001986// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1987// as well.
1988//
1989// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1990// compiled against the device bootclasspath.
1991//
1992// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1993// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001994func BinaryFactory() android.Module {
1995 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001996
Colin Crossce6734e2020-06-15 16:09:53 -07001997 module.addHostAndDeviceProperties()
Ronald Braunsteincdc66f42024-04-12 11:23:19 -07001998 module.AddProperties(&module.binaryProperties, &module.sourceProperties)
Colin Cross36242852017-06-23 15:06:31 -07001999
Colin Cross9ae1b922018-06-26 17:59:05 -07002000 module.Module.properties.Installable = proptools.BoolPtr(true)
2001
Cole Faustb9c67e22024-10-08 16:39:56 -07002002 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Colin Cross6b4a32d2017-12-05 13:42:45 -08002003 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08002004
Colin Cross36242852017-06-23 15:06:31 -07002005 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002006}
2007
Colin Cross1b16b0e2019-02-12 14:41:32 -08002008// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
2009//
2010// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
2011// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07002012func BinaryHostFactory() android.Module {
2013 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07002014
Colin Crossce6734e2020-06-15 16:09:53 -07002015 module.addHostProperties()
2016 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07002017
Colin Cross9ae1b922018-06-26 17:59:05 -07002018 module.Module.properties.Installable = proptools.BoolPtr(true)
2019
Cole Faustb9c67e22024-10-08 16:39:56 -07002020 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommon)
Colin Cross6b4a32d2017-12-05 13:42:45 -08002021 android.InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -07002022 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002023}
2024
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002025type JavaApiContribution struct {
2026 android.ModuleBase
2027 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00002028 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002029
2030 properties struct {
2031 // name of the API surface
2032 Api_surface *string
2033
2034 // relative path to the API signature text file
2035 Api_file *string `android:"path"`
2036 }
2037}
2038
2039func ApiContributionFactory() android.Module {
2040 module := &JavaApiContribution{}
2041 android.InitAndroidModule(module)
2042 android.InitDefaultableModule(module)
2043 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002044 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002045 return module
2046}
2047
2048type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00002049 ApiFile android.Path
2050 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002051}
2052
Colin Crossbc7d76c2023-12-12 16:39:03 -08002053var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]()
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002054
2055func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00002056 var apiFile android.Path = nil
2057 if apiFileString := ap.properties.Api_file; apiFileString != nil {
2058 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
2059 }
2060
Colin Cross40213022023-12-13 15:19:49 -08002061 android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00002062 ApiFile: apiFile,
2063 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002064 })
2065}
2066
2067type ApiLibrary struct {
2068 android.ModuleBase
2069 android.DefaultableModuleBase
2070
Spandan Dascb368ea2023-03-22 04:27:05 +00002071 hiddenAPI
2072 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00002073 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00002074
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002075 properties JavaApiLibraryProperties
2076
Jihoon Kang01e522c2023-03-14 01:09:34 +00002077 stubsSrcJar android.WritablePath
2078 stubsJar android.WritablePath
2079 stubsJarWithoutStaticLibs android.WritablePath
2080 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00002081 // .dex of stubs, used for hiddenapi processing
2082 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00002083
2084 validationPaths android.Paths
Jihoon Kang5d701272024-02-15 21:53:49 +00002085
2086 stubsType StubsType
2087
2088 aconfigProtoFiles android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002089}
2090
2091type JavaApiLibraryProperties struct {
2092 // name of the API surface
2093 Api_surface *string
2094
Jihoon Kang60d4a092022-11-17 23:47:43 +00002095 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00002096 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00002097 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002098
2099 // List of flags to be passed to the javac compiler to generate jar file
2100 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002101
2102 // List of shared java libs that this module has dependencies to and
2103 // should be passed as classpath in javac invocation
Cole Faustb7493472024-08-28 11:55:52 -07002104 Libs proptools.Configurable[[]string]
Jihoon Kange30fff02023-02-14 20:18:20 +00002105
2106 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00002107 // merge zipped after metalava invocation
Cole Faustb7493472024-08-28 11:55:52 -07002108 Static_libs proptools.Configurable[[]string]
Jihoon Kang01e522c2023-03-14 01:09:34 +00002109
Jihoon Kang862da6f2023-08-01 06:28:51 +00002110 // Version of previously released API file for compatibility check.
2111 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00002112
2113 // java_system_modules module providing the jar to be added to the
2114 // bootclasspath when compiling the stubs.
2115 // The jar will also be passed to metalava as a classpath to
2116 // generate compilable stubs.
2117 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00002118
2119 // If true, the module runs validation on the API signature files provided
2120 // by the modules passed via api_contributions by checking if the files are
2121 // in sync with the source Java files. However, the environment variable
2122 // DISABLE_STUB_VALIDATION has precedence over this property.
2123 Enable_validation *bool
Jihoon Kang5d701272024-02-15 21:53:49 +00002124
2125 // Type of stubs the module should generate. Must be one of "everything", "runtime" or
2126 // "exportable". Defaults to "everything".
2127 // - "everything" stubs include all non-flagged apis and flagged apis, regardless of the state
2128 // of the flag.
2129 // - "runtime" stubs include all non-flagged apis and flagged apis that are ENABLED or
2130 // READ_WRITE, and all other flagged apis are stripped.
2131 // - "exportable" stubs include all non-flagged apis and flagged apis that are ENABLED and
2132 // READ_ONLY, and all other flagged apis are stripped.
2133 Stubs_type *string
2134
2135 // List of aconfig_declarations module names that the stubs generated in this module
2136 // depend on.
2137 Aconfig_declarations []string
Paul Duffin27819362024-07-22 21:03:50 +01002138
2139 // List of hard coded filegroups containing Metalava config files that are passed to every
2140 // Metalava invocation that this module performs. See addMetalavaConfigFilesToCmd.
2141 ConfigFiles []string `android:"path" blueprint:"mutated"`
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002142
2143 // If not blank, set to the version of the sdk to compile against.
2144 // Defaults to an empty string, which compiles the module against the private platform APIs.
2145 // Values are of one of the following forms:
2146 // 1) numerical API level, "current", "none", or "core_platform"
2147 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
2148 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
2149 // If the SDK kind is empty, it will be set to public.
2150 Sdk_version *string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002151}
2152
2153func ApiLibraryFactory() android.Module {
2154 module := &ApiLibrary{}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002155 module.AddProperties(&module.properties)
Paul Duffin27819362024-07-22 21:03:50 +01002156 module.properties.ConfigFiles = getMetalavaConfigFilegroupReference()
2157 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002158 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00002159 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002160 return module
2161}
2162
2163func (al *ApiLibrary) ApiSurface() *string {
2164 return al.properties.Api_surface
2165}
2166
2167func (al *ApiLibrary) StubsJar() android.Path {
2168 return al.stubsJar
2169}
2170
2171func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00002172 srcs android.Paths, homeDir android.WritablePath,
Paul Duffin27819362024-07-22 21:03:50 +01002173 classpath android.Paths, configFiles android.Paths) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002174 rule.Command().Text("rm -rf").Flag(homeDir.String())
2175 rule.Command().Text("mkdir -p").Flag(homeDir.String())
2176
2177 cmd := rule.Command()
2178 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
2179
2180 if metalavaUseRbe(ctx) {
2181 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
2182 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
2183 labels := map[string]string{"type": "tool", "name": "metalava"}
2184
2185 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
2186 rule.Rewrapper(&remoteexec.REParams{
2187 Labels: labels,
2188 ExecStrategy: execStrategy,
2189 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
2190 Platform: map[string]string{remoteexec.PoolKey: pool},
2191 })
2192 }
2193
2194 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
2195 Flag(config.JavacVmFlags).
2196 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002197 FlagWithInputList("--source-files ", srcs, " ")
2198
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02002199 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002200 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00002201 Flag("--include-annotations").
2202 // The flag makes nullability issues as warnings rather than errors by replacing
2203 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
2204 // and these packages are meant to have everything annotated
2205 // @RecentlyNullable/@RecentlyNonNull.
2206 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002207 FlagWithArg("--repeat-errors-max ", "10").
2208 FlagWithArg("--hide ", "UnresolvedImport").
2209 FlagWithArg("--hide ", "InvalidNullabilityOverride").
2210 FlagWithArg("--hide ", "ChangedDefault")
2211
Paul Duffin27819362024-07-22 21:03:50 +01002212 addMetalavaConfigFilesToCmd(cmd, configFiles)
2213
Jihoon Kang4ec24872023-10-05 17:26:09 +00002214 if len(classpath) == 0 {
2215 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
2216 // classes on the classpath when an API file contains missing classes. However, as this command
2217 // does not specify `--classpath` this is not needed for that. However, this is also used as a
2218 // signal to the special metalava code for generating stubs from text files that it needs to add
2219 // some additional items into the API (e.g. default constructors).
2220 cmd.FlagWithArg("--api-class-resolution ", "api")
2221 } else {
2222 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
2223 cmd.FlagWithInputList("--classpath ", classpath, ":")
2224 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01002225
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002226 return cmd
2227}
2228
Jihoon Kang1bff0342023-01-17 20:40:22 +00002229func (al *ApiLibrary) HeaderJars() android.Paths {
2230 return android.Paths{al.stubsJar}
2231}
2232
2233func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
2234 return nil, nil
2235}
2236
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002237func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
2238 if stubsDir.Valid() {
2239 cmd.FlagWithArg("--stubs ", stubsDir.String())
2240 }
2241}
2242
Jihoon Kang063ec002023-06-28 01:16:23 +00002243func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
2244 for _, validationPath := range validationPaths {
2245 cmd.Validation(validationPath)
2246 }
2247}
2248
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002249func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00002250 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00002251 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
Jihoon Kang4f04df92024-01-30 02:30:06 +00002252 !ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") &&
Jihoon Kang063ec002023-06-28 01:16:23 +00002253 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00002254 for _, apiContributionName := range apiContributions {
2255 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00002256
2257 // Add the java_api_contribution module generating droidstubs module
2258 // as dependency when validation adding conditions are met and
2259 // the java_api_contribution module name has ".api.contribution" suffix.
2260 // All droidstubs-generated modules possess the suffix in the name,
2261 // but there is no such guarantee for tests.
2262 if addValidations {
2263 if strings.HasSuffix(apiContributionName, ".api.contribution") {
2264 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
2265 } else {
2266 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
2267 "current timestamp provider is not found for the api "+
2268 "contribution %s",
2269 ctx.ModuleName(),
2270 apiContributionName,
2271 )
2272 }
2273 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002274 }
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002275 if ctx.Device() {
2276 sdkDep := decodeSdkDep(ctx, android.SdkContext(al))
2277 if sdkDep.useModule {
2278 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
2279 ctx.AddVariationDependencies(nil, libTag, sdkDep.classpath...)
2280 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
2281
2282 }
2283 }
Cole Faustb7493472024-08-28 11:55:52 -07002284 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs.GetOrDefault(ctx, nil)...)
2285 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002286
Jihoon Kang5d701272024-02-15 21:53:49 +00002287 for _, aconfigDeclarationsName := range al.properties.Aconfig_declarations {
2288 ctx.AddDependency(ctx.Module(), aconfigDeclarationTag, aconfigDeclarationsName)
2289 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002290}
2291
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002292// Map where key is the api scope name and value is the int value
2293// representing the order of the api scope, narrowest to the widest
Jihoon Kang98aa8fa2024-06-07 11:06:57 +00002294var scopeOrderMap = AllApiScopes.MapToIndex(
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002295 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00002296
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002297func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
2298 for _, srcFileInfo := range srcFilesInfo {
2299 if srcFileInfo.ApiSurface == "" {
2300 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00002301 }
2302 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002303 sort.Slice(srcFilesInfo, func(i, j int) bool {
2304 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
2305 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00002306
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002307 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00002308}
2309
Jihoon Kang5d701272024-02-15 21:53:49 +00002310var validstubsType = []StubsType{Everything, Runtime, Exportable}
2311
2312func (al *ApiLibrary) validateProperties(ctx android.ModuleContext) {
2313 if al.properties.Stubs_type == nil {
2314 ctx.ModuleErrorf("java_api_library module type must specify stubs_type property.")
2315 } else {
2316 al.stubsType = StringToStubsType(proptools.String(al.properties.Stubs_type))
2317 }
2318
2319 if !android.InList(al.stubsType, validstubsType) {
2320 ctx.PropertyErrorf("stubs_type", "%s is not a valid stubs_type property value. "+
2321 "Must be one of %s.", proptools.String(al.properties.Stubs_type), validstubsType)
2322 }
2323}
2324
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002325func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang5d701272024-02-15 21:53:49 +00002326 al.validateProperties(ctx)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002327
2328 rule := android.NewRuleBuilder(pctx, ctx)
2329
2330 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
2331 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
2332 SandboxInputs()
2333
Jihoon Kang063ec002023-06-28 01:16:23 +00002334 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002335 rule.Command().Text("rm -rf").Text(stubsDir.String())
2336 rule.Command().Text("mkdir -p").Text(stubsDir.String())
2337
2338 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
2339
Jihoon Kang8fe19822023-09-14 06:27:36 +00002340 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002341 var classPaths android.Paths
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002342 var bootclassPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00002343 var staticLibs android.Paths
Jihoon Kang4ec24872023-10-05 17:26:09 +00002344 var systemModulesPaths android.Paths
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002345 ctx.VisitDirectDeps(func(dep android.Module) {
2346 tag := ctx.OtherModuleDependencyTag(dep)
2347 switch tag {
2348 case javaApiContributionTag:
Colin Cross313aa542023-12-13 13:47:44 -08002349 provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider)
Jihoon Kang8fe19822023-09-14 06:27:36 +00002350 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00002351 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
2352 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00002353 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002354 case libTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002355 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2356 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002357 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002358 }
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002359 case bootClasspathTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002360 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2361 bootclassPaths = append(bootclassPaths, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002362 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002363 }
Jihoon Kange30fff02023-02-14 20:18:20 +00002364 case staticLibTag:
Colin Cross7727c7f2024-07-18 15:36:32 -07002365 if provider, ok := android.OtherModuleProvider(ctx, dep, JavaInfoProvider); ok {
2366 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang458fde52024-11-20 21:30:35 +00002367 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.AconfigIntermediateCacheOutputPaths...)
Colin Cross7727c7f2024-07-18 15:36:32 -07002368 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00002369 case systemModulesTag:
Colin Crossb61c2262024-08-08 14:04:42 -07002370 if sm, ok := android.OtherModuleProvider(ctx, dep, SystemModulesProvider); ok {
2371 systemModulesPaths = append(systemModulesPaths, sm.HeaderJars...)
2372 }
Jihoon Kang063ec002023-06-28 01:16:23 +00002373 case metalavaCurrentApiTimestampTag:
2374 if currentApiTimestampProvider, ok := dep.(currentApiTimestampProvider); ok {
2375 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp())
2376 }
Jihoon Kang5d701272024-02-15 21:53:49 +00002377 case aconfigDeclarationTag:
2378 if provider, ok := android.OtherModuleProvider(ctx, dep, android.AconfigDeclarationsProviderKey); ok {
2379 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.IntermediateCacheOutputPath)
Yu Liu67a28422024-03-05 00:36:31 +00002380 } else if provider, ok := android.OtherModuleProvider(ctx, dep, android.CodegenInfoProvider); ok {
Jihoon Kang5d701272024-02-15 21:53:49 +00002381 al.aconfigProtoFiles = append(al.aconfigProtoFiles, provider.IntermediateCacheOutputPaths...)
2382 } else {
2383 ctx.ModuleErrorf("Only aconfig_declarations and aconfig_declarations_group "+
2384 "module type is allowed for flags_packages property, but %s is neither "+
2385 "of these supported module types",
2386 dep.Name(),
2387 )
2388 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002389 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00002390 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002391
Jihoon Kanga96a7b12023-09-20 23:43:32 +00002392 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
2393 var srcFiles android.Paths
2394 for _, srcFileInfo := range srcFilesInfo {
2395 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00002396 }
2397
Jihoon Kang160634c2023-05-25 05:28:29 +00002398 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00002399 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
2400 }
2401
Paul Duffin27819362024-07-22 21:03:50 +01002402 configFiles := android.PathsForModuleSrc(ctx, al.properties.ConfigFiles)
2403
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002404 combinedPaths := append(([]android.Path)(nil), systemModulesPaths...)
2405 combinedPaths = append(combinedPaths, classPaths...)
2406 combinedPaths = append(combinedPaths, bootclassPaths...)
2407 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, combinedPaths, configFiles)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002408
2409 al.stubsFlags(ctx, cmd, stubsDir)
2410
Paul Duffin1b1eb9b2024-06-18 18:17:39 +01002411 previousApi := String(al.properties.Previous_api)
2412 if previousApi != "" {
2413 previousApiFiles := android.PathsForModuleSrc(ctx, []string{previousApi})
2414 cmd.FlagForEachInput("--migrate-nullness ", previousApiFiles)
Jihoon Kang862da6f2023-08-01 06:28:51 +00002415 }
2416
Jihoon Kang063ec002023-06-28 01:16:23 +00002417 al.addValidation(ctx, cmd, al.validationPaths)
2418
Jihoon Kang5d701272024-02-15 21:53:49 +00002419 generateRevertAnnotationArgs(ctx, cmd, al.stubsType, al.aconfigProtoFiles)
2420
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002421 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00002422 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
2423 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00002424
Jihoon Kangca198c22023-06-22 23:13:51 +00002425 rule.Command().
2426 BuiltTool("soong_zip").
2427 Flag("-write_if_changed").
2428 Flag("-jar").
2429 FlagWithOutput("-o ", al.stubsSrcJar).
2430 FlagWithArg("-C ", stubsDir.String()).
2431 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002432
Paul Duffin336b16a2023-08-15 23:10:13 +01002433 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00002434
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002435 javacFlags := javaBuilderFlags{
2436 javaVersion: getStubsJavaVersion(),
2437 javacFlags: strings.Join(al.properties.Javacflags, " "),
2438 classpath: classpath(classPaths),
2439 bootClasspath: classpath(append(systemModulesPaths, bootclassPaths...)),
Jihoon Kangca198c22023-06-22 23:13:51 +00002440 }
Jihoon Kang423d2292022-11-29 23:10:10 +00002441
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002442 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
2443
2444 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
2445 android.Paths{al.stubsSrcJar}, annoSrcJar, javacFlags, android.Paths{})
2446
Jihoon Kange30fff02023-02-14 20:18:20 +00002447 builder := android.NewRuleBuilder(pctx, ctx)
2448 builder.Command().
2449 BuiltTool("merge_zips").
2450 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00002451 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00002452 Inputs(staticLibs)
2453 builder.Build("merge_zips", "merge jar files")
2454
Spandan Dascb368ea2023-03-22 04:27:05 +00002455 // compile stubs to .dex for hiddenapi processing
2456 dexParams := &compileDexParams{
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002457 flags: javacFlags,
Spandan Dascb368ea2023-03-22 04:27:05 +00002458 sdkVersion: al.SdkVersion(ctx),
2459 minSdkVersion: al.MinSdkVersion(ctx),
2460 classesJar: al.stubsJar,
2461 jarName: ctx.ModuleName() + ".jar",
2462 }
Spandan Das3dbda182024-05-20 22:23:10 +00002463 dexOutputFile, _ := al.dexer.compileDex(ctx, dexParams)
Spandan Dascb368ea2023-03-22 04:27:05 +00002464 uncompressed := true
2465 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2466 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2467 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2468
Jihoon Kang423d2292022-11-29 23:10:10 +00002469 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002470
Yu Liu460cf372025-01-10 00:34:06 +00002471 javaInfo := &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002472 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2473 LocalHeaderJars: android.PathsIfNonNil(al.stubsJar),
Colin Crossa14fb6a2024-10-23 16:57:06 -07002474 TransitiveStaticLibsHeaderJars: depset.New(depset.PREORDER, android.PathsIfNonNil(al.stubsJar), nil),
2475 TransitiveStaticLibsImplementationJars: depset.New(depset.PREORDER, android.PathsIfNonNil(al.stubsJar), nil),
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002476 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2477 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2478 AidlIncludeDirs: android.Paths{},
2479 StubsLinkType: Stubs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002480 // No aconfig libraries on api libraries
Yu Liu460cf372025-01-10 00:34:06 +00002481 }
2482 setExtraJavaInfo(ctx, al, javaInfo)
2483 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002484}
2485
Spandan Das59a4a2b2024-01-09 21:35:56 +00002486func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dascb368ea2023-03-22 04:27:05 +00002487 return al.dexJarFile
2488}
2489
2490func (al *ApiLibrary) DexJarInstallPath() android.Path {
2491 return al.dexJarFile.Path()
2492}
2493
2494func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2495 return nil
2496}
2497
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002498// Most java_api_library constitues the sdk, but there are some java_api_library that
2499// does not contribute to the api surface. Such modules are allowed to set sdk_version
2500// other than "none"
Spandan Dascb368ea2023-03-22 04:27:05 +00002501func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002502 return android.SdkSpecFrom(ctx, proptools.String(al.properties.Sdk_version))
Spandan Dascb368ea2023-03-22 04:27:05 +00002503}
2504
2505// java_api_library is always at "current". Return FutureApiLevel
2506func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002507 return al.SdkVersion(ctx).ApiLevel
2508}
2509
2510func (al *ApiLibrary) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
2511 return al.SdkVersion(ctx).ApiLevel
2512}
2513
2514func (al *ApiLibrary) SystemModules() string {
2515 return proptools.String(al.properties.System_modules)
2516}
2517
2518func (al *ApiLibrary) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2519 return al.SdkVersion(ctx).ApiLevel
Spandan Dascb368ea2023-03-22 04:27:05 +00002520}
2521
Cole Faustb36d31d2024-08-27 16:04:28 -07002522func (al *ApiLibrary) IDEInfo(ctx android.BaseModuleContext, i *android.IdeInfo) {
2523 i.Deps = append(i.Deps, al.ideDeps(ctx)...)
Cole Faustb7493472024-08-28 11:55:52 -07002524 i.Libs = append(i.Libs, al.properties.Libs.GetOrDefault(ctx, nil)...)
2525 i.Static_libs = append(i.Static_libs, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Spandan Das4ae68012024-07-18 19:35:31 +00002526 i.SrcJars = append(i.SrcJars, al.stubsSrcJar.String())
2527}
2528
2529// deps of java_api_library for module_bp_java_deps.json
Cole Faustb36d31d2024-08-27 16:04:28 -07002530func (al *ApiLibrary) ideDeps(ctx android.BaseModuleContext) []string {
Spandan Das4ae68012024-07-18 19:35:31 +00002531 ret := []string{}
Cole Faustb7493472024-08-28 11:55:52 -07002532 ret = append(ret, al.properties.Libs.GetOrDefault(ctx, nil)...)
2533 ret = append(ret, al.properties.Static_libs.GetOrDefault(ctx, nil)...)
Spandan Das4f443e72024-10-17 00:04:19 +00002534 if proptools.StringDefault(al.properties.System_modules, "none") != "none" {
Spandan Das4ae68012024-07-18 19:35:31 +00002535 ret = append(ret, proptools.String(al.properties.System_modules))
2536 }
Spandan Das4ae68012024-07-18 19:35:31 +00002537 // Other non java_library dependencies like java_api_contribution are ignored for now.
2538 return ret
2539}
2540
Spandan Dascb368ea2023-03-22 04:27:05 +00002541// implement the following interfaces for hiddenapi processing
2542var _ hiddenAPIModule = (*ApiLibrary)(nil)
2543var _ UsesLibraryDependency = (*ApiLibrary)(nil)
Jihoon Kangb0f4c022024-08-06 00:15:25 +00002544var _ android.SdkContext = (*ApiLibrary)(nil)
Spandan Dascb368ea2023-03-22 04:27:05 +00002545
Spandan Das4ae68012024-07-18 19:35:31 +00002546// implement the following interface for IDE completion.
2547var _ android.IDEInfo = (*ApiLibrary)(nil)
2548
Colin Cross2fe66872015-03-30 17:20:39 -07002549//
2550// Java prebuilts
2551//
2552
Colin Cross74d73e22017-08-02 11:05:49 -07002553type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002554 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002555
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002556 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2557 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002558 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002559
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002560 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2561 // specified.
2562 Min_sdk_version *string
2563
William Loh5a082f92022-05-17 20:21:50 +00002564 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2565 // and uses-permission tags in manifest_fixer.
2566 Replace_max_sdk_version_placeholder *string
2567
Colin Cross535e2cf2017-10-20 17:57:49 -07002568 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002569
Paul Duffin869de142021-07-15 14:14:41 +01002570 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002571 Permitted_packages []string
2572
Jiyong Park1be96912018-05-28 18:02:19 +09002573 // List of shared java libs that this module has dependencies to
2574 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002575
Colin Crossdad2a362024-03-23 04:43:41 +00002576 // List of static java libs that this module has dependencies to
Cole Faustb7493472024-08-28 11:55:52 -07002577 Static_libs proptools.Configurable[[]string]
Colin Crossdad2a362024-03-23 04:43:41 +00002578
Colin Cross37f6d792018-07-12 12:28:41 -07002579 // List of files to remove from the jar file(s)
2580 Exclude_files []string
2581
2582 // List of directories to remove from the jar file(s)
2583 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002584
2585 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002586 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002587
2588 // set the name of the output
2589 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002590
2591 Aidl struct {
2592 // directories that should be added as include directories for any aidl sources of modules
2593 // that depend on this module, as well as to aidl for this module.
2594 Export_include_dirs []string
2595 }
Spandan Das3cf04632024-01-19 00:22:22 +00002596
2597 // Name of the source soong module that gets shadowed by this prebuilt
2598 // If unspecified, follows the naming convention that the source module of
2599 // the prebuilt is Name() without "prebuilt_" prefix
2600 Source_module_name *string
Spandan Das23956d12024-01-19 00:22:22 +00002601
2602 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2603 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2604 // (without any prebuilt_ prefix)
2605 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002606
2607 // Property signifying whether the module provides stubs jar or not.
2608 Is_stubs_module *bool
Colin Cross74d73e22017-08-02 11:05:49 -07002609}
2610
2611type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002612 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002613 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002614 android.ApexModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002615 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002616
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002617 // Functionality common to Module and Import.
2618 embeddableInModuleAndImport
2619
Liz Kammerd6c31d22020-08-05 15:40:41 -07002620 hiddenAPI
2621 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002622 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002623
Colin Cross74d73e22017-08-02 11:05:49 -07002624 properties ImportProperties
2625
Liz Kammerd6c31d22020-08-05 15:40:41 -07002626 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002627 dexJarFile OptionalDexJarPath
Spandan Dasfae468e2023-12-12 23:23:53 +00002628 dexJarFileErr error
Jeongik Chad5fe8782021-07-08 01:13:11 +09002629 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002630
Colin Crossdad2a362024-03-23 04:43:41 +00002631 combinedImplementationFile android.Path
2632 combinedHeaderFile android.Path
2633 classLoaderContexts dexpreopt.ClassLoaderContextMap
2634 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002635
2636 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002637
2638 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002639 minSdkVersion android.ApiLevel
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002640
2641 stubsLinkType StubsLinkType
Colin Cross2fe66872015-03-30 17:20:39 -07002642}
2643
Paul Duffin630b11e2021-07-15 13:35:26 +01002644var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2645
2646func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2647 return j.properties.Permitted_packages
2648}
2649
Jiyong Park92315372021-04-02 08:45:46 +09002650func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2651 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002652}
2653
Jiyong Parkf1691d22021-03-29 20:11:58 +09002654func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002655 return "none"
2656}
2657
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002658func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002659 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002660 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002661 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002662 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002663}
2664
Spandan Dasa26eda72023-03-02 00:56:06 +00002665func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002666 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002667 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002668 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002669 // Default is PrivateApiLevel
2670 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002671}
2672
Spandan Dasca70fc42023-03-01 23:38:49 +00002673func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2674 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002675}
2676
Colin Cross74d73e22017-08-02 11:05:49 -07002677func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002678 return &j.prebuilt
2679}
2680
Colin Cross74d73e22017-08-02 11:05:49 -07002681func (j *Import) PrebuiltSrcs() []string {
2682 return j.properties.Jars
2683}
2684
Spandan Das3cf04632024-01-19 00:22:22 +00002685func (j *Import) BaseModuleName() string {
2686 return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name())
2687}
2688
Colin Cross74d73e22017-08-02 11:05:49 -07002689func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002690 return j.prebuilt.Name(j.ModuleBase.Name())
2691}
2692
Jiyong Park0b238752019-10-29 11:23:10 +09002693func (j *Import) Stem() string {
Spandan Das3cf04632024-01-19 00:22:22 +00002694 return proptools.StringDefault(j.properties.Stem, j.BaseModuleName())
Jiyong Park0b238752019-10-29 11:23:10 +09002695}
2696
Spandan Das23956d12024-01-19 00:22:22 +00002697func (j *Import) CreatedByJavaSdkLibraryName() *string {
2698 return j.properties.Created_by_java_sdk_library_name
2699}
2700
Jiyong Park618922e2020-01-08 13:35:43 +09002701func (a *Import) JacocoReportClassesFile() android.Path {
2702 return nil
2703}
2704
Colin Cross74d73e22017-08-02 11:05:49 -07002705func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002706 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Cole Faustb7493472024-08-28 11:55:52 -07002707 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs.GetOrDefault(ctx, nil)...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002708
2709 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002710 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002711 }
Colin Cross1e676be2016-10-12 14:38:15 -07002712}
2713
Sam Delmerico277795c2022-02-25 17:04:37 +00002714func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09002715 j.sdkVersion = j.SdkVersion(ctx)
2716 j.minSdkVersion = j.MinSdkVersion(ctx)
2717
Colin Crossff694a82023-12-13 15:54:49 -08002718 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
2719 if !apexInfo.IsForPlatform() {
Colin Cross56a83212020-09-15 18:30:11 -07002720 j.hideApexVariantFromMake = true
2721 }
2722
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002723 if ctx.Windows() {
2724 j.HideFromMake()
2725 }
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002726
2727 if proptools.Bool(j.properties.Is_stubs_module) {
2728 j.stubsLinkType = Stubs
2729 } else {
2730 j.stubsLinkType = Implementation
2731 }
Sam Delmerico277795c2022-02-25 17:04:37 +00002732}
2733
2734func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2735 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002736
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002737 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01002738
Liz Kammerd6c31d22020-08-05 15:40:41 -07002739 var flags javaBuilderFlags
2740
Colin Crossa14fb6a2024-10-23 16:57:06 -07002741 var transitiveClasspathHeaderJars []depset.DepSet[android.Path]
2742 var transitiveBootClasspathHeaderJars []depset.DepSet[android.Path]
2743 var transitiveStaticLibsHeaderJars []depset.DepSet[android.Path]
2744 var transitiveStaticLibsImplementationJars []depset.DepSet[android.Path]
2745 var transitiveStaticLibsResourceJars []depset.DepSet[android.Path]
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002746
Colin Cross9ffaf282024-08-12 13:50:09 -07002747 j.collectTransitiveHeaderJarsForR8(ctx)
Colin Crossdad2a362024-03-23 04:43:41 +00002748 var staticJars android.Paths
Colin Cross53529a92024-08-15 17:11:18 -07002749 var staticResourceJars android.Paths
Colin Crossdad2a362024-03-23 04:43:41 +00002750 var staticHeaderJars android.Paths
Jiyong Park1be96912018-05-28 18:02:19 +09002751 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09002752 tag := ctx.OtherModuleDependencyTag(module)
Colin Cross313aa542023-12-13 13:47:44 -08002753 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002754 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002755 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002756 flags.classpath = append(flags.classpath, dep.HeaderJars...)
2757 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07002758 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002759 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002760 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Colin Cross53529a92024-08-15 17:11:18 -07002761 staticJars = append(staticJars, dep.ImplementationJars...)
2762 staticResourceJars = append(staticResourceJars, dep.ResourceJars...)
Colin Crossdad2a362024-03-23 04:43:41 +00002763 staticHeaderJars = append(staticHeaderJars, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07002764 transitiveClasspathHeaderJars = append(transitiveClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2765 transitiveStaticLibsHeaderJars = append(transitiveStaticLibsHeaderJars, dep.TransitiveStaticLibsHeaderJars)
2766 transitiveStaticLibsImplementationJars = append(transitiveStaticLibsImplementationJars, dep.TransitiveStaticLibsImplementationJars)
2767 transitiveStaticLibsResourceJars = append(transitiveStaticLibsResourceJars, dep.TransitiveStaticLibsResourceJars)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002768 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002769 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Colin Crossa14fb6a2024-10-23 16:57:06 -07002770 transitiveBootClasspathHeaderJars = append(transitiveBootClasspathHeaderJars, dep.TransitiveStaticLibsHeaderJars)
Jiyong Park1be96912018-05-28 18:02:19 +09002771 }
Jihoon Kang98e9ac62024-09-25 23:42:30 +00002772 } else if _, ok := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002773 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002774 case libTag, sdkLibTag:
Jihoon Kangc4db1092024-09-18 23:10:55 +00002775 sdkInfo, _ := android.OtherModuleProvider(ctx, module, SdkLibraryInfoProvider)
2776 generatingLibsString := android.PrettyConcat(
2777 getGeneratingLibs(ctx, j.SdkVersion(ctx), module.Name(), sdkInfo), true, "or")
2778 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 +09002779 }
2780 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002781
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002782 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09002783 })
2784
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002785 localJars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crossdad2a362024-03-23 04:43:41 +00002786 jarName := j.Stem() + ".jar"
2787
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002788 // Combine only the local jars together for use in transitive classpaths.
2789 // Always pass input jar through TransformJarsToJar to strip module-info.class from prebuilts.
2790 localCombinedHeaderJar := android.PathForModuleOut(ctx, "local-combined", jarName)
2791 TransformJarsToJar(ctx, localCombinedHeaderJar, "combine local prebuilt implementation jars", localJars, android.OptionalPath{},
2792 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
2793 localStrippedJars := android.Paths{localCombinedHeaderJar}
2794
Colin Crossa14fb6a2024-10-23 16:57:06 -07002795 completeStaticLibsHeaderJars := depset.New(depset.PREORDER, localStrippedJars, transitiveStaticLibsHeaderJars)
2796 completeStaticLibsImplementationJars := depset.New(depset.PREORDER, localStrippedJars, transitiveStaticLibsImplementationJars)
2797 completeStaticLibsResourceJars := depset.New(depset.PREORDER, nil, transitiveStaticLibsResourceJars)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002798
Colin Crossdad2a362024-03-23 04:43:41 +00002799 // Always pass the input jars to TransformJarsToJar, even if there is only a single jar, we need the output
2800 // file of the module to be named jarName.
Colin Cross77965d92024-08-15 17:11:08 -07002801 var outputFile android.Path
2802 combinedImplementationJar := android.PathForModuleOut(ctx, "combined", jarName)
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002803 var implementationJars android.Paths
2804 if ctx.Config().UseTransitiveJarsInClasspath() {
2805 implementationJars = completeStaticLibsImplementationJars.ToList()
2806 } else {
2807 implementationJars = append(slices.Clone(localJars), staticJars...)
2808 }
Colin Cross77965d92024-08-15 17:11:08 -07002809 TransformJarsToJar(ctx, combinedImplementationJar, "combine prebuilt implementation jars", implementationJars, android.OptionalPath{},
Colin Crossdad2a362024-03-23 04:43:41 +00002810 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross77965d92024-08-15 17:11:08 -07002811 outputFile = combinedImplementationJar
Colin Crossdad2a362024-03-23 04:43:41 +00002812
2813 // If no dependencies have separate header jars then there is no need to create a separate
2814 // header jar for this module.
2815 reuseImplementationJarAsHeaderJar := slices.Equal(staticJars, staticHeaderJars)
2816
Colin Cross53529a92024-08-15 17:11:18 -07002817 var resourceJarFile android.Path
2818 if len(staticResourceJars) > 1 {
2819 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
2820 TransformJarsToJar(ctx, combinedJar, "for resources", staticResourceJars, android.OptionalPath{},
2821 false, nil, nil)
2822 resourceJarFile = combinedJar
2823 } else if len(staticResourceJars) == 1 {
2824 resourceJarFile = staticResourceJars[0]
2825 }
2826
Colin Cross77965d92024-08-15 17:11:08 -07002827 var headerJar android.Path
Colin Crossdad2a362024-03-23 04:43:41 +00002828 if reuseImplementationJarAsHeaderJar {
Colin Cross77965d92024-08-15 17:11:08 -07002829 headerJar = outputFile
Colin Crossdad2a362024-03-23 04:43:41 +00002830 } else {
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002831 var headerJars android.Paths
2832 if ctx.Config().UseTransitiveJarsInClasspath() {
2833 headerJars = completeStaticLibsHeaderJars.ToList()
2834 } else {
2835 headerJars = append(slices.Clone(localJars), staticHeaderJars...)
2836 }
Colin Cross77965d92024-08-15 17:11:08 -07002837 headerOutputFile := android.PathForModuleOut(ctx, "turbine-combined", jarName)
Colin Crossdad2a362024-03-23 04:43:41 +00002838 TransformJarsToJar(ctx, headerOutputFile, "combine prebuilt header jars", headerJars, android.OptionalPath{},
2839 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross77965d92024-08-15 17:11:08 -07002840 headerJar = headerOutputFile
Colin Crossdad2a362024-03-23 04:43:41 +00002841 }
2842
2843 if Bool(j.properties.Jetifier) {
Colin Cross77965d92024-08-15 17:11:08 -07002844 jetifierOutputFile := android.PathForModuleOut(ctx, "jetifier", jarName)
2845 TransformJetifier(ctx, jetifierOutputFile, outputFile)
2846 outputFile = jetifierOutputFile
Colin Crossdad2a362024-03-23 04:43:41 +00002847
2848 if !reuseImplementationJarAsHeaderJar {
Colin Cross77965d92024-08-15 17:11:08 -07002849 jetifierHeaderJar := android.PathForModuleOut(ctx, "jetifier-headers", jarName)
2850 TransformJetifier(ctx, jetifierHeaderJar, headerJar)
2851 headerJar = jetifierHeaderJar
Colin Crossdad2a362024-03-23 04:43:41 +00002852 } else {
Colin Cross77965d92024-08-15 17:11:08 -07002853 headerJar = outputFile
Colin Crossdad2a362024-03-23 04:43:41 +00002854 }
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002855
2856 // Enabling jetifier requires modifying classes from transitive dependencies, disable transitive
2857 // classpath and use the combined header jar instead.
Colin Crossa14fb6a2024-10-23 16:57:06 -07002858 completeStaticLibsHeaderJars = depset.New(depset.PREORDER, android.Paths{headerJar}, nil)
2859 completeStaticLibsImplementationJars = depset.New(depset.PREORDER, android.Paths{outputFile}, nil)
Colin Crossdad2a362024-03-23 04:43:41 +00002860 }
Colin Cross5e87f342024-04-11 15:28:18 -07002861
Colin Cross53529a92024-08-15 17:11:18 -07002862 implementationJarFile := outputFile
2863
2864 // merge implementation jar with resources if necessary
2865 if resourceJarFile != nil {
2866 jars := android.Paths{resourceJarFile, outputFile}
2867 combinedJar := android.PathForModuleOut(ctx, "withres", jarName)
2868 TransformJarsToJar(ctx, combinedJar, "for resources", jars, android.OptionalPath{},
2869 false, nil, nil)
2870 outputFile = combinedJar
2871 }
2872
Luca Stefani172c56d2024-12-17 14:19:09 +01002873 proguardFlags := android.PathForModuleOut(ctx, "proguard_flags")
2874 TransformJarToR8Rules(ctx, proguardFlags, outputFile)
2875
2876 transitiveProguardFlags, transitiveUnconditionalExportedFlags := collectDepProguardSpecInfo(ctx)
2877 android.SetProvider(ctx, ProguardSpecInfoProvider, ProguardSpecInfo{
2878 ProguardFlagsFiles: depset.New[android.Path](
2879 depset.POSTORDER,
2880 android.Paths{proguardFlags},
2881 transitiveProguardFlags,
2882 ),
2883 UnconditionallyExportedProguardFlags: depset.New[android.Path](
2884 depset.POSTORDER,
2885 nil,
2886 transitiveUnconditionalExportedFlags,
2887 ),
2888 })
2889
Colin Cross5e87f342024-04-11 15:28:18 -07002890 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource.
2891 // Also strip the relative path from the header output file so that the reuseImplementationJarAsHeaderJar check
2892 // in a module that depends on this module considers them equal.
Colin Cross77965d92024-08-15 17:11:08 -07002893 j.combinedHeaderFile = headerJar.WithoutRel()
Colin Cross5e87f342024-04-11 15:28:18 -07002894 j.combinedImplementationFile = outputFile.WithoutRel()
Colin Crossdad2a362024-03-23 04:43:41 +00002895
Sam Delmerico277795c2022-02-25 17:04:37 +00002896 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09002897
2898 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002899
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002900 if ctx.Config().UseTransitiveJarsInClasspath() {
2901 ctx.CheckbuildFile(localJars...)
2902 } else {
2903 ctx.CheckbuildFile(outputFile)
2904 }
Colin Crossa6182ab2024-08-21 10:47:44 -07002905
Paul Duffin064b70c2020-11-02 17:32:38 +00002906 if ctx.Device() {
Spandan Dasa326b322024-09-19 21:02:52 +00002907 // Shared libraries deapexed from prebuilt apexes are no longer supported.
2908 // Set the dexJarBuildPath to a fake path.
2909 // This allows soong analysis pass, but will be an error during ninja execution if there are
2910 // any rdeps.
Colin Crossff694a82023-12-13 15:54:49 -08002911 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Paul Duffin064b70c2020-11-02 17:32:38 +00002912 if ai.ForPrebuiltApex {
Spandan Dasa326b322024-09-19 21:02:52 +00002913 j.dexJarFile = makeDexJarPathFromPath(android.PathForModuleInstall(ctx, "intentionally_no_longer_supported"))
2914 j.initHiddenAPI(ctx, j.dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin064b70c2020-11-02 17:32:38 +00002915 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002916 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00002917 if sdkDep.invalidVersion {
2918 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2919 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2920 } else if sdkDep.useFiles {
2921 // sdkDep.jar is actually equivalent to turbine header.jar.
2922 flags.classpath = append(flags.classpath, sdkDep.jars...)
2923 }
2924
2925 // Dex compilation
2926
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002927 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00002928 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00002929 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00002930 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
2931
Colin Cross7707b242024-07-26 12:02:36 -07002932 var dexOutputFile android.Path
Spandan Dasc404cc72023-02-23 18:05:05 +00002933 dexParams := &compileDexParams{
2934 flags: flags,
2935 sdkVersion: j.SdkVersion(ctx),
2936 minSdkVersion: j.MinSdkVersion(ctx),
2937 classesJar: outputFile,
2938 jarName: jarName,
2939 }
2940
Spandan Das3dbda182024-05-20 22:23:10 +00002941 dexOutputFile, _ = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00002942 if ctx.Failed() {
2943 return
2944 }
Colin Crossa6182ab2024-08-21 10:47:44 -07002945 ctx.CheckbuildFile(dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002946
Paul Duffin74d18d12021-05-14 14:18:47 +01002947 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002948 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01002949
2950 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01002951 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002952
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002953 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09002954 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002955 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002956 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002957
Yu Liu460cf372025-01-10 00:34:06 +00002958 javaInfo := &JavaInfo{
Colin Crossc9b4f6b2024-07-26 15:25:46 -07002959 HeaderJars: android.PathsIfNonNil(j.combinedHeaderFile),
2960 LocalHeaderJars: android.PathsIfNonNil(j.combinedHeaderFile),
2961 TransitiveLibsHeaderJarsForR8: j.transitiveLibsHeaderJarsForR8,
2962 TransitiveStaticLibsHeaderJarsForR8: j.transitiveStaticLibsHeaderJarsForR8,
2963 TransitiveStaticLibsHeaderJars: completeStaticLibsHeaderJars,
2964 TransitiveStaticLibsImplementationJars: completeStaticLibsImplementationJars,
2965 TransitiveStaticLibsResourceJars: completeStaticLibsResourceJars,
2966 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedImplementationFile),
2967 ImplementationJars: android.PathsIfNonNil(implementationJarFile.WithoutRel()),
2968 ResourceJars: android.PathsIfNonNil(resourceJarFile),
2969 AidlIncludeDirs: j.exportAidlIncludeDirs,
2970 StubsLinkType: j.stubsLinkType,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002971 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Yu Liu460cf372025-01-10 00:34:06 +00002972 }
2973 setExtraJavaInfo(ctx, j, javaInfo)
2974 android.SetProvider(ctx, JavaInfoProvider, javaInfo)
mrziwang68786d82024-07-09 10:41:55 -07002975
2976 ctx.SetOutputFiles(android.Paths{j.combinedImplementationFile}, "")
2977 ctx.SetOutputFiles(android.Paths{j.combinedImplementationFile}, ".jar")
Colin Cross2fe66872015-03-30 17:20:39 -07002978}
2979
Sam Delmerico277795c2022-02-25 17:04:37 +00002980func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
2981 if !Bool(j.properties.Installable) {
2982 return
2983 }
2984
2985 var installDir android.InstallPath
2986 if ctx.InstallInTestcases() {
2987 var archDir string
2988 if !ctx.Host() {
2989 archDir = ctx.DeviceConfig().DeviceArch()
2990 }
2991 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
2992 } else {
2993 installDir = android.PathForModuleInstall(ctx, "framework")
2994 }
2995 ctx.InstallFile(installDir, jarName, outputFile)
2996}
2997
Nan Zhanged19fc32017-10-19 13:06:22 -07002998func (j *Import) HeaderJars() android.Paths {
Colin Crossdad2a362024-03-23 04:43:41 +00002999 return android.PathsIfNonNil(j.combinedHeaderFile)
Nan Zhanged19fc32017-10-19 13:06:22 -07003000}
3001
Colin Cross331a1212018-08-15 20:40:52 -07003002func (j *Import) ImplementationAndResourcesJars() android.Paths {
Colin Crossdad2a362024-03-23 04:43:41 +00003003 return android.PathsIfNonNil(j.combinedImplementationFile)
Colin Cross331a1212018-08-15 20:40:52 -07003004}
3005
Spandan Das59a4a2b2024-01-09 21:35:56 +00003006func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dasfae468e2023-12-12 23:23:53 +00003007 if j.dexJarFileErr != nil {
Spandan Das59a4a2b2024-01-09 21:35:56 +00003008 ctx.ModuleErrorf(j.dexJarFileErr.Error())
Spandan Dasfae468e2023-12-12 23:23:53 +00003009 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07003010 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08003011}
3012
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01003013func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09003014 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01003015}
3016
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01003017func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
3018 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09003019}
3020
Jiyong Park45bf82e2020-12-15 22:29:02 +09003021var _ android.ApexModule = (*Import)(nil)
3022
3023// Implements android.ApexModule
Colin Crossf7bbd2f2024-12-05 13:57:10 -08003024func (j *Import) OutgoingDepIsInSameApex(tag blueprint.DependencyTag) bool {
3025 return j.depIsInSameApex(tag)
Jiyong Park0f80c182020-01-31 02:49:53 +09003026}
3027
Jiyong Park45bf82e2020-12-15 22:29:02 +09003028// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07003029func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
3030 sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00003031 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00003032 minSdkVersion := j.MinSdkVersion(ctx)
3033 if !minSdkVersion.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00003034 return fmt.Errorf("min_sdk_version is not specified")
3035 }
Spandan Das7fa982c2023-02-24 18:38:56 +00003036 // If the module is compiling against core (via sdk_version), skip comparison check.
3037 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00003038 return nil
3039 }
Spandan Das7fa982c2023-02-24 18:38:56 +00003040 if minSdkVersion.GreaterThan(sdkVersion) {
3041 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00003042 }
Jooyung Han749dc692020-04-15 11:03:39 +09003043 return nil
3044}
3045
Paul Duffinfef55002021-06-17 14:56:05 +01003046// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
3047// java_sdk_library_import with the specified base module name requires to be exported from a
3048// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08003049func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
Spandan Das5be63332023-12-13 00:06:32 +00003050 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003051 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08003052 files := []string{
3053 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01003054 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08003055 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
3056 files = append(files, dexJarFileApexRootRelative+".prof")
3057 }
3058 return files
Paul Duffinfef55002021-06-17 14:56:05 +01003059}
3060
Spandan Das5be63332023-12-13 00:06:32 +00003061// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003062// the java library with the specified name.
Spandan Das5be63332023-12-13 00:06:32 +00003063func ApexRootRelativePathToJavaLib(name string) string {
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003064 return filepath.Join("javalib", name+".jar")
3065}
3066
Paul Duffinfef55002021-06-17 14:56:05 +01003067var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
3068
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01003069func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01003070 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08003071 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01003072}
3073
Spandan Das2ea84dd2024-01-25 22:12:50 +00003074func (j *Import) UseProfileGuidedDexpreopt() bool {
3075 return proptools.Bool(j.importDexpreoptProperties.Dex_preopt.Profile_guided)
3076}
3077
albaltai36ff7dc2018-12-25 14:35:23 +08003078// Add compile time check for interface implementation
3079var _ android.IDEInfo = (*Import)(nil)
3080var _ android.IDECustomizedModuleName = (*Import)(nil)
3081
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003082// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003083
Cole Faustb36d31d2024-08-27 16:04:28 -07003084func (j *Import) IDEInfo(ctx android.BaseModuleContext, dpInfo *android.IdeInfo) {
Spandan Das65bfc292025-01-02 22:55:56 +00003085 dpInfo.Jars = append(dpInfo.Jars, j.combinedImplementationFile.String())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003086}
3087
3088func (j *Import) IDECustomizedModuleName() string {
3089 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
3090 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
3091 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01003092 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07003093}
3094
Colin Cross74d73e22017-08-02 11:05:49 -07003095var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07003096
Bill Peckhamff89ffa2020-12-23 16:13:04 -08003097func (j *Import) IsInstallable() bool {
3098 return Bool(j.properties.Installable)
3099}
3100
Jiakai Zhang519c5c82021-09-16 06:15:39 +00003101var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08003102
Colin Cross1b16b0e2019-02-12 14:41:32 -08003103// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
3104//
3105// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
3106// compiled against an Android classpath.
3107//
3108// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
3109// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07003110func ImportFactory() android.Module {
3111 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07003112
Liz Kammerd6c31d22020-08-05 15:40:41 -07003113 module.AddProperties(
3114 &module.properties,
3115 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08003116 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07003117 )
Colin Cross74d73e22017-08-02 11:05:49 -07003118
Paul Duffin71b33cc2021-06-23 11:39:47 +01003119 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01003120
Liz Kammerd6c31d22020-08-05 15:40:41 -07003121 module.dexProperties.Optimize.EnabledByDefault = false
3122
Colin Cross74d73e22017-08-02 11:05:49 -07003123 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003124 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003125 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07003126 return module
Colin Cross2fe66872015-03-30 17:20:39 -07003127}
3128
Colin Cross1b16b0e2019-02-12 14:41:32 -08003129// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
3130// module.
3131//
3132// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
3133// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07003134func ImportFactoryHost() android.Module {
3135 module := &Import{}
3136
3137 module.AddProperties(&module.properties)
3138
3139 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003140 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003141 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07003142 return module
3143}
3144
Colin Cross42be7612019-02-21 18:12:14 -08003145// dex_import module
3146
3147type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07003148 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09003149
3150 // set the name of the output
3151 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08003152}
3153
3154type DexImport struct {
3155 android.ModuleBase
3156 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09003157 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08003158 prebuilt android.Prebuilt
3159
3160 properties DexImportProperties
3161
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003162 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08003163
3164 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07003165
3166 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08003167}
3168
3169func (j *DexImport) Prebuilt() *android.Prebuilt {
3170 return &j.prebuilt
3171}
3172
3173func (j *DexImport) PrebuiltSrcs() []string {
3174 return j.properties.Jars
3175}
3176
3177func (j *DexImport) Name() string {
3178 return j.prebuilt.Name(j.ModuleBase.Name())
3179}
3180
Jiyong Park0b238752019-10-29 11:23:10 +09003181func (j *DexImport) Stem() string {
3182 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
3183}
3184
Jiyong Park77acec62020-06-01 21:39:15 +09003185func (a *DexImport) JacocoReportClassesFile() android.Path {
3186 return nil
3187}
3188
Martin Stjernholm6d415272020-01-31 17:10:36 +00003189func (j *DexImport) IsInstallable() bool {
3190 return true
3191}
3192
Colin Cross42be7612019-02-21 18:12:14 -08003193func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3194 if len(j.properties.Jars) != 1 {
3195 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
3196 }
3197
Colin Crossff694a82023-12-13 15:54:49 -08003198 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07003199 if !apexInfo.IsForPlatform() {
3200 j.hideApexVariantFromMake = true
3201 }
3202
Jiakai Zhang519c5c82021-09-16 06:15:39 +00003203 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00003204 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
3205 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &j.dexpreopter)
Colin Cross42be7612019-02-21 18:12:14 -08003206
3207 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
3208 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
3209
3210 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08003211 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08003212
3213 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
3214 rule.Temporary(temporary)
3215
3216 // use zip2zip to uncompress classes*.dex files
3217 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08003218 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08003219 FlagWithInput("-i ", inputJar).
3220 FlagWithOutput("-o ", temporary).
3221 FlagWithArg("-0 ", "'classes*.dex'")
3222
3223 // use zipalign to align uncompressed classes*.dex files
3224 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08003225 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08003226 Flag("-f").
3227 Text("4").
3228 Input(temporary).
3229 Output(dexOutputFile)
3230
3231 rule.DeleteTemporaryFiles()
3232
Colin Crossf1a035e2020-11-16 17:32:30 -08003233 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08003234 } else {
3235 ctx.Build(pctx, android.BuildParams{
3236 Rule: android.Cp,
3237 Input: inputJar,
3238 Output: dexOutputFile,
3239 })
3240 }
3241
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01003242 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08003243
Spandan Dase21a8d42024-01-23 23:56:29 +00003244 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08003245
Colin Cross56a83212020-09-15 18:30:11 -07003246 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09003247 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
3248 j.Stem()+".jar", dexOutputFile)
3249 }
Colin Cross42be7612019-02-21 18:12:14 -08003250}
3251
Spandan Das59a4a2b2024-01-09 21:35:56 +00003252func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08003253 return j.dexJarFile
3254}
3255
Jiyong Park45bf82e2020-12-15 22:29:02 +09003256var _ android.ApexModule = (*DexImport)(nil)
3257
3258// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07003259func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
3260 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09003261 // we don't check prebuilt modules for sdk_version
3262 return nil
3263}
3264
Colin Cross42be7612019-02-21 18:12:14 -08003265// dex_import imports a `.jar` file containing classes.dex files.
3266//
3267// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
3268// to the device.
3269func DexImportFactory() android.Module {
3270 module := &DexImport{}
3271
3272 module.AddProperties(&module.properties)
3273
3274 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09003275 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09003276 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08003277 return module
3278}
3279
Colin Cross89536d42017-07-07 14:35:50 -07003280// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07003281type Defaults struct {
3282 android.ModuleBase
3283 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09003284 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07003285}
3286
Colin Cross1b16b0e2019-02-12 14:41:32 -08003287// java_defaults provides a set of properties that can be inherited by other java or android modules.
3288//
3289// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
3290// property in the defaults module that exists in the depending module will be prepended to the depending module's
3291// value for that property.
3292//
3293// Example:
3294//
Sam Delmerico277795c2022-02-25 17:04:37 +00003295// java_defaults {
3296// name: "example_defaults",
3297// srcs: ["common/**/*.java"],
3298// javacflags: ["-Xlint:all"],
3299// aaptflags: ["--auto-add-overlay"],
3300// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08003301//
Sam Delmerico277795c2022-02-25 17:04:37 +00003302// java_library {
3303// name: "example",
3304// defaults: ["example_defaults"],
3305// srcs: ["example/**/*.java"],
3306// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08003307//
3308// is functionally identical to:
3309//
Sam Delmerico277795c2022-02-25 17:04:37 +00003310// java_library {
3311// name: "example",
3312// srcs: [
3313// "common/**/*.java",
3314// "example/**/*.java",
3315// ],
3316// javacflags: ["-Xlint:all"],
3317// }
Paul Duffin47357662019-12-05 14:07:14 +00003318func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07003319 module := &Defaults{}
3320
Colin Cross89536d42017-07-07 14:35:50 -07003321 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08003322 &CommonProperties{},
3323 &DeviceProperties{},
yangbill2af0b6e2024-03-15 09:29:29 +00003324 &OverridableProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07003325 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08003326 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08003327 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07003328 &aaptProperties{},
3329 &androidLibraryProperties{},
3330 &appProperties{},
3331 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08003332 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00003333 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00003334 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07003335 &ImportProperties{},
3336 &AARImportProperties{},
3337 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01003338 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08003339 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09003340 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07003341 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07003342 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08003343 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00003344 &JavaApiLibraryProperties{},
Jihoon Kang9272dcc2024-01-12 00:08:30 +00003345 &bootclasspathFragmentProperties{},
3346 &SourceOnlyBootclasspathProperties{},
John Wu878b2fc2024-10-28 22:29:35 +00003347 &ravenwoodTestProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07003348 )
3349
3350 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07003351 return module
3352}
Nan Zhangea568a42017-11-08 21:20:04 -08003353
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003354func kytheExtractJavaFactory() android.Singleton {
3355 return &kytheExtractJavaSingleton{}
3356}
3357
3358type kytheExtractJavaSingleton struct {
3359}
3360
3361func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
3362 var xrefTargets android.Paths
Spandan Das1028d5a2024-08-19 21:45:48 +00003363 var xrefKotlinTargets android.Paths
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003364 ctx.VisitAllModules(func(module android.Module) {
3365 if javaModule, ok := module.(xref); ok {
3366 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
Spandan Das1028d5a2024-08-19 21:45:48 +00003367 xrefKotlinTargets = append(xrefKotlinTargets, javaModule.XrefKotlinFiles()...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003368 }
3369 })
3370 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
3371 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07003372 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003373 }
Spandan Das1028d5a2024-08-19 21:45:48 +00003374 if len(xrefKotlinTargets) > 0 {
3375 ctx.Phony("xref_kotlin", xrefKotlinTargets...)
3376 }
Sasha Smundak2a4549e2018-11-05 16:49:08 -08003377}
3378
Nan Zhangea568a42017-11-08 21:20:04 -08003379var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07003380var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08003381var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04003382var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003383
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003384// Add class loader context (CLC) of a given dependency to the current CLC.
3385func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
3386 clcMap dexpreopt.ClassLoaderContextMap) {
3387
Yu Liu460cf372025-01-10 00:34:06 +00003388 dep, ok := android.OtherModuleProvider(ctx, depModule, JavaInfoProvider)
3389 if !ok || dep.UsesLibraryDependencyInfo == nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003390 return
3391 }
3392
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003393 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
3394
3395 var sdkLib *string
Jihoon Kang98e9ac62024-09-25 23:42:30 +00003396 if lib, ok := android.OtherModuleProvider(ctx, depModule, SdkLibraryInfoProvider); ok && lib.SharedLibrary {
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003397 // A shared SDK library. This should be added as a top-level CLC element.
3398 sdkLib = &depName
Yu Liu460cf372025-01-10 00:34:06 +00003399 } else if lib := dep.SdkLibraryComponentDependencyInfo; lib != nil && lib.OptionalSdkLibraryImplementation != nil {
3400 if depModule.Name() == proptools.String(lib.OptionalSdkLibraryImplementation)+".impl" {
3401 sdkLib = lib.OptionalSdkLibraryImplementation
Jihoon Kangddda6ea2024-09-18 00:56:52 +00003402 }
Yu Liu460cf372025-01-10 00:34:06 +00003403 } else if ulib := dep.ProvidesUsesLibInfo; ulib != nil {
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003404 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
3405 // property. This should be handled in the same way as a shared SDK library.
Yu Liu460cf372025-01-10 00:34:06 +00003406 sdkLib = ulib.ProvidesUsesLib
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003407 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003408
3409 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04003410 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003411 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01003412 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
3413 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003414 } else if depTag == staticLibTag {
3415 // Propagate <uses-library> through static library dependencies, unless it is a component
3416 // library (such as stubs). Component libraries have a dependency on their SDK library,
3417 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003418 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003419 return
3420 }
3421 } else {
3422 // Don't propagate <uses-library> for other dependency tags.
3423 return
3424 }
3425
Ulya Trafimovich840efb62021-07-15 14:34:40 +01003426 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
3427 // and its CLC should be added as subtree of that node. Otherwise the library is not a
3428 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
3429 // from its CLC should be added to the current CLC.
3430 if sdkLib != nil {
Jiakai Zhangf98da192024-04-15 11:15:41 +00003431 optional := false
3432 if module, ok := ctx.Module().(ModuleWithUsesLibrary); ok {
Cole Faust64f2d842024-10-17 13:28:34 -07003433 if android.InList(*sdkLib, module.UsesLibrary().usesLibraryProperties.Optional_uses_libs.GetOrDefault(ctx, nil)) {
Jiakai Zhangf98da192024-04-15 11:15:41 +00003434 optional = true
3435 }
3436 }
3437 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, optional,
Yu Liu460cf372025-01-10 00:34:06 +00003438 dep.UsesLibraryDependencyInfo.DexJarBuildPath.PathOrNil(),
3439 dep.UsesLibraryDependencyInfo.DexJarInstallPath, dep.UsesLibraryDependencyInfo.ClassLoaderContexts)
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003440 } else {
Yu Liu460cf372025-01-10 00:34:06 +00003441 clcMap.AddContextMap(dep.UsesLibraryDependencyInfo.ClassLoaderContexts, depName)
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00003442 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00003443}
Wei Libafb6d62021-12-10 03:14:59 -08003444
Jiakai Zhang36937082024-04-15 11:15:50 +00003445func addMissingOptionalUsesLibsFromDep(ctx android.ModuleContext, depModule android.Module,
3446 usesLibrary *usesLibrary) {
3447
Yu Liu460cf372025-01-10 00:34:06 +00003448 dep, ok := android.OtherModuleProvider(ctx, depModule, JavaInfoProvider)
3449 if !ok || dep.ModuleWithUsesLibraryInfo == nil {
Jiakai Zhang36937082024-04-15 11:15:50 +00003450 return
3451 }
3452
Yu Liu460cf372025-01-10 00:34:06 +00003453 for _, lib := range dep.ModuleWithUsesLibraryInfo.UsesLibrary.usesLibraryProperties.Missing_optional_uses_libs {
Jiakai Zhang36937082024-04-15 11:15:50 +00003454 if !android.InList(lib, usesLibrary.usesLibraryProperties.Missing_optional_uses_libs) {
3455 usesLibrary.usesLibraryProperties.Missing_optional_uses_libs =
3456 append(usesLibrary.usesLibraryProperties.Missing_optional_uses_libs, lib)
3457 }
3458 }
3459}
3460
Jihoon Kangfdf32362023-09-12 00:36:43 +00003461type JavaApiContributionImport struct {
3462 JavaApiContribution
3463
Spandan Das23956d12024-01-19 00:22:22 +00003464 prebuilt android.Prebuilt
3465 prebuiltProperties javaApiContributionImportProperties
3466}
3467
3468type javaApiContributionImportProperties struct {
3469 // Name of the source soong module that gets shadowed by this prebuilt
3470 // If unspecified, follows the naming convention that the source module of
3471 // the prebuilt is Name() without "prebuilt_" prefix
3472 Source_module_name *string
3473
3474 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
3475 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
3476 // (without any prebuilt_ prefix)
3477 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfdf32362023-09-12 00:36:43 +00003478}
3479
3480func ApiContributionImportFactory() android.Module {
3481 module := &JavaApiContributionImport{}
3482 android.InitAndroidModule(module)
3483 android.InitDefaultableModule(module)
3484 android.InitPrebuiltModule(module, &[]string{""})
Spandan Das23956d12024-01-19 00:22:22 +00003485 module.AddProperties(&module.properties, &module.prebuiltProperties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00003486 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00003487 return module
3488}
3489
3490func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
3491 return &module.prebuilt
3492}
3493
3494func (module *JavaApiContributionImport) Name() string {
3495 return module.prebuilt.Name(module.ModuleBase.Name())
3496}
3497
Spandan Das23956d12024-01-19 00:22:22 +00003498func (j *JavaApiContributionImport) BaseModuleName() string {
3499 return proptools.StringDefault(j.prebuiltProperties.Source_module_name, j.ModuleBase.Name())
3500}
3501
3502func (j *JavaApiContributionImport) CreatedByJavaSdkLibraryName() *string {
3503 return j.prebuiltProperties.Created_by_java_sdk_library_name
3504}
3505
Jihoon Kangfdf32362023-09-12 00:36:43 +00003506func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
3507 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
3508}
Yu Liu460cf372025-01-10 00:34:06 +00003509
3510func setExtraJavaInfo(ctx android.ModuleContext, module android.Module, javaInfo *JavaInfo) {
3511 if alDep, ok := module.(AndroidLibraryDependency); ok {
3512 javaInfo.AndroidLibraryDependencyInfo = &AndroidLibraryDependencyInfo{
3513 ExportPackage: alDep.ExportPackage(),
3514 ResourcesNodeDepSet: alDep.ResourcesNodeDepSet(),
3515 RRODirsDepSet: alDep.RRODirsDepSet(),
3516 ManifestsDepSet: alDep.ManifestsDepSet(),
3517 }
3518 }
3519
3520 if ulDep, ok := module.(UsesLibraryDependency); ok {
3521 javaInfo.UsesLibraryDependencyInfo = &UsesLibraryDependencyInfo{
3522 DexJarBuildPath: ulDep.DexJarBuildPath(ctx),
3523 DexJarInstallPath: ulDep.DexJarInstallPath(),
3524 ClassLoaderContexts: ulDep.ClassLoaderContexts(),
3525 }
3526 }
3527
3528 if slcDep, ok := module.(SdkLibraryComponentDependency); ok {
3529 javaInfo.SdkLibraryComponentDependencyInfo = &SdkLibraryComponentDependencyInfo{
3530 OptionalSdkLibraryImplementation: slcDep.OptionalSdkLibraryImplementation(),
3531 }
3532 }
3533
3534 if pul, ok := module.(ProvidesUsesLib); ok {
3535 javaInfo.ProvidesUsesLibInfo = &ProvidesUsesLibInfo{
3536 ProvidesUsesLib: pul.ProvidesUsesLib(),
3537 }
3538 }
3539
3540 if mwul, ok := module.(ModuleWithUsesLibrary); ok {
3541 javaInfo.ModuleWithUsesLibraryInfo = &ModuleWithUsesLibraryInfo{
3542 UsesLibrary: mwul.UsesLibrary(),
3543 }
3544 }
3545}