blob: 1a266b8593cebbca40b1fc4732853ad749a5049f [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17// This file contains the module types for compiling Java for Android, and converts the properties
Colin Cross46c9b8b2017-06-22 16:51:17 -070018// into the flags and filenames necessary to pass to the Module. The final creation of the rules
Colin Cross2fe66872015-03-30 17:20:39 -070019// is handled in builder.go
20
21import (
Colin Crossf19b9bb2018-03-26 14:42:44 -070022 "fmt"
Colin Crossfc3674a2017-09-18 17:41:52 -070023 "path/filepath"
Alix289e9c62023-08-16 15:06:31 +000024 "sort"
Wei Libafb6d62021-12-10 03:14:59 -080025 "strings"
Colin Cross2fe66872015-03-30 17:20:39 -070026
Jihoon Kang0ac87c22022-11-15 19:06:14 +000027 "android/soong/remoteexec"
Aditya Choudhary9b593522023-10-06 19:54:58 +000028 "android/soong/testing"
Jihoon Kang6592e872023-12-19 01:13:16 +000029
Colin Cross2fe66872015-03-30 17:20:39 -070030 "github.com/google/blueprint"
Colin Cross76b5f0c2017-08-29 16:02:06 -070031 "github.com/google/blueprint/proptools"
Colin Cross2fe66872015-03-30 17:20:39 -070032
Colin Cross635c3b02016-05-18 15:37:25 -070033 "android/soong/android"
Colin Crossf8d9c492021-01-26 11:01:43 -080034 "android/soong/cc"
Ulya Trafimovich31e444e2020-08-14 17:32:16 +010035 "android/soong/dexpreopt"
Colin Cross3e3e72d2017-06-22 17:20:19 -070036 "android/soong/java/config"
Colin Cross303e21f2018-08-07 16:49:25 -070037 "android/soong/tradefed"
Colin Cross2fe66872015-03-30 17:20:39 -070038)
39
Colin Cross463a90e2015-06-17 14:20:06 -070040func init() {
Paul Duffin535e0a12021-03-30 23:34:32 +010041 registerJavaBuildComponents(android.InitRegistrationContext)
Paul Duffin255f18e2019-12-13 11:22:16 +000042
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080043 RegisterJavaSdkMemberTypes()
44}
45
Paul Duffin535e0a12021-03-30 23:34:32 +010046func registerJavaBuildComponents(ctx android.RegistrationContext) {
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080047 ctx.RegisterModuleType("java_defaults", DefaultsFactory)
48
49 ctx.RegisterModuleType("java_library", LibraryFactory)
50 ctx.RegisterModuleType("java_library_static", LibraryStaticFactory)
51 ctx.RegisterModuleType("java_library_host", LibraryHostFactory)
52 ctx.RegisterModuleType("java_binary", BinaryFactory)
53 ctx.RegisterModuleType("java_binary_host", BinaryHostFactory)
54 ctx.RegisterModuleType("java_test", TestFactory)
55 ctx.RegisterModuleType("java_test_helper_library", TestHelperLibraryFactory)
56 ctx.RegisterModuleType("java_test_host", TestHostFactory)
57 ctx.RegisterModuleType("java_test_import", JavaTestImportFactory)
58 ctx.RegisterModuleType("java_import", ImportFactory)
59 ctx.RegisterModuleType("java_import_host", ImportFactoryHost)
60 ctx.RegisterModuleType("java_device_for_host", DeviceForHostFactory)
61 ctx.RegisterModuleType("java_host_for_device", HostForDeviceFactory)
62 ctx.RegisterModuleType("dex_import", DexImportFactory)
Jihoon Kang0ac87c22022-11-15 19:06:14 +000063 ctx.RegisterModuleType("java_api_library", ApiLibraryFactory)
64 ctx.RegisterModuleType("java_api_contribution", ApiContributionFactory)
Jihoon Kangfdf32362023-09-12 00:36:43 +000065 ctx.RegisterModuleType("java_api_contribution_import", ApiContributionImportFactory)
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080066
Martin Stjernholm0e4cceb2021-05-13 02:38:35 +010067 // This mutator registers dependencies on dex2oat for modules that should be
68 // dexpreopted. This is done late when the final variants have been
69 // established, to not get the dependencies split into the wrong variants and
70 // to support the checks in dexpreoptDisabled().
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080071 ctx.FinalDepsMutators(func(ctx android.RegisterMutatorsContext) {
72 ctx.BottomUp("dexpreopt_tool_deps", dexpreoptToolDepsMutator).Parallel()
Sam Delmerico1e3f78f2022-09-07 12:07:07 -040073 // needs access to ApexInfoProvider which is available after variant creation
74 ctx.BottomUp("jacoco_deps", jacocoDepsMutator).Parallel()
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -080075 })
76
LaMont Jones0c10e4d2023-05-16 00:58:37 +000077 ctx.RegisterParallelSingletonType("logtags", LogtagsSingleton)
78 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)
85 android.RegisterSdkMemberType(javaBootLibsSdkMemberType)
Jiakai Zhangea180332021-09-26 08:58:02 +000086 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.
Paul Duffin2da04242021-04-23 19:43:28 +0100157 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.
196 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{
229 Command: `echo -e '#!/system/bin/sh\n` +
230 `export CLASSPATH=/system/framework/$jar_name\n` +
231 `exec app_process /$partition/bin $main_class "$$@"'> ${out}`,
232 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`.
245 ProguardFlagsFiles *android.DepSet[android.Path]
246
247 // implementation detail to store transitive proguard flags files from exporting shared deps
248 UnconditionallyExportedProguardFlags *android.DepSet[android.Path]
249}
250
Colin Crossbc7d76c2023-12-12 16:39:03 -0800251var ProguardSpecInfoProvider = blueprint.NewProvider[ProguardSpecInfo]()
Sam Delmerico95d70942023-08-02 18:00:35 -0400252
Colin Crossdcf71b22021-02-01 13:59:03 -0800253// JavaInfo contains information about a java module for use by modules that depend on it.
254type JavaInfo struct {
255 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
256 // against this module. If empty, ImplementationJars should be used instead.
257 HeaderJars android.Paths
258
Joe Onorato349ae8d2024-02-05 22:46:00 +0000259 RepackagedHeaderJars android.Paths
260
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500261 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700262 TransitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500263
264 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700265 TransitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500266
Colin Crossdcf71b22021-02-01 13:59:03 -0800267 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
268 // in the module as well as any resources included in the module.
269 ImplementationAndResourcesJars android.Paths
270
271 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000272 //module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800273 ImplementationJars android.Paths
274
275 // ResourceJars is a list of jars that contain the resources included in the module.
276 ResourceJars android.Paths
277
278 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
279 // depending on this module.
280 AidlIncludeDirs android.Paths
281
282 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
283 // module.
284 SrcJarArgs []string
285
286 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
287 SrcJarDeps android.Paths
288
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000289 // The source files of this module and all its transitive static dependencies.
290 TransitiveSrcFiles *android.DepSet[android.Path]
291
Colin Crossdcf71b22021-02-01 13:59:03 -0800292 // ExportedPlugins is a list of paths that should be used as annotation processors for any
293 // module that depends on this module.
294 ExportedPlugins android.Paths
295
296 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
297 // any module that depends on this module.
298 ExportedPluginClasses []string
299
300 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
301 // requiring disbling turbine for any modules that depend on it.
302 ExportedPluginDisableTurbine bool
303
304 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
305 // instrumented by jacoco.
306 JacocoReportClassesFile android.Path
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000307
308 // StubsLinkType provides information about whether the provided jars are stub jars or
309 // implementation jars. If the provider is set by java_sdk_library, the link type is "unknown"
310 // and selection between the stub jar vs implementation jar is deferred to SdkLibrary.sdkJars(...)
311 StubsLinkType StubsLinkType
Colin Crossdcf71b22021-02-01 13:59:03 -0800312}
313
Colin Crossbc7d76c2023-12-12 16:39:03 -0800314var JavaInfoProvider = blueprint.NewProvider[JavaInfo]()
Colin Crossdcf71b22021-02-01 13:59:03 -0800315
Colin Cross75ce9ec2021-02-26 16:20:32 -0800316// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
317// the sysprop implementation library.
318type SyspropPublicStubInfo struct {
319 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
320 // the sysprop implementation library.
321 JavaInfo JavaInfo
322}
323
Colin Crossbc7d76c2023-12-12 16:39:03 -0800324var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]()
Colin Cross75ce9ec2021-02-26 16:20:32 -0800325
Paul Duffin44b481b2020-06-17 16:59:43 +0100326// Methods that need to be implemented for a module that is added to apex java_libs property.
327type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700328 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100329 ImplementationAndResourcesJars() android.Paths
330}
331
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100332// Provides build path and install path to DEX jars.
333type UsesLibraryDependency interface {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000334 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100335 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000336 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100337}
338
Jaewoong Jung26342642021-03-17 15:56:23 -0700339// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800340type xref interface {
341 XrefJavaFiles() android.Paths
342}
343
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800344func (j *Module) XrefJavaFiles() android.Paths {
345 return j.kytheFiles
346}
347
Colin Crossbe1da472017-07-07 15:59:46 -0700348type dependencyTag struct {
349 blueprint.BaseDependencyTag
350 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000351
352 // True if the dependency is relinked at runtime.
353 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800354
355 // True if the dependency is a toolchain, for example an annotation processor.
356 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700357}
358
Colin Crosse9fe2942020-11-10 18:12:15 -0800359// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
360// dependency to be installed when the parent module is installed.
361type installDependencyTag struct {
362 blueprint.BaseDependencyTag
363 android.InstallAlwaysNeededDependencyTag
364 name string
365}
366
Colin Cross65cb3142021-12-10 23:05:02 +0000367func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
368 if d.runtimeLinked {
369 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800370 } else if d.toolchain {
371 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000372 }
373 return nil
374}
375
376var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
377
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100378type usesLibraryDependencyTag struct {
379 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100380 sdkVersion int // SDK version in which the library appared as a standalone library.
381 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100382}
383
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100384func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100385 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000386 dependencyTag: dependencyTag{
387 name: fmt.Sprintf("uses-library-%d", sdkVersion),
388 runtimeLinked: true,
389 },
390 sdkVersion: sdkVersion,
391 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100392 }
393}
394
Jiyong Park8be103b2019-11-08 15:53:48 +0900395func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700396 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900397}
398
Colin Crossbe1da472017-07-07 15:59:46 -0700399var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800400 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000401 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800402 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000403 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400404 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000405 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800406 pluginTag = dependencyTag{name: "plugin", toolchain: true}
407 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
408 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000409 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
410 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800411 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000412 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
413 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800414 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800415 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
416 certificateTag = dependencyTag{name: "certificate"}
417 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800418 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000419 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500420 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800421 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000422 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
423 depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
Jihoon Kang84b25892023-12-01 22:01:06 +0000424 aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800425 jniInstallTag = installDependencyTag{name: "jni install"}
426 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100427 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
428 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
429 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
430 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
431 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700432)
Colin Cross2fe66872015-03-30 17:20:39 -0700433
Jiyong Park83dc74b2020-01-14 18:38:44 +0900434func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400435 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900436}
437
438func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
439 return depTag == staticLibTag
440}
441
Colin Crossfc3674a2017-09-18 17:41:52 -0700442type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100443 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700444
Colin Cross6cef4812019-10-17 14:23:50 -0700445 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
446 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100447
448 // The default system modules to use. Will be an empty string if no system
449 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700450 systemModules string
451
Pete Gilline3d44b22020-06-29 11:28:51 +0100452 // The modules that will be added to the classpath regardless of the Java language level targeted
453 classpath []string
454
Colin Cross6cef4812019-10-17 14:23:50 -0700455 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100456 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700457 java9Classpath []string
458
Colin Crossa97c5d32018-03-28 14:58:31 -0700459 frameworkResModule string
460
Colin Cross86a60ae2018-05-29 14:44:55 -0700461 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700462 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100463
464 noStandardLibs, noFrameworksLibs bool
465}
466
467func (s sdkDep) hasStandardLibs() bool {
468 return !s.noStandardLibs
469}
470
471func (s sdkDep) hasFrameworkLibs() bool {
472 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700473}
474
Colin Crossa4f08812018-10-02 22:03:40 -0700475type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700476 name string
477 path android.Path
478 target android.Target
479 coverageFile android.OptionalPath
480 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000481 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700482}
483
Jiyong Parkf1691d22021-03-29 20:11:58 +0900484func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700485 sdkDep := decodeSdkDep(ctx, sdkContext)
486 if sdkDep.useModule {
487 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
488 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400489 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700490 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000491 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000492 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000493 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700494 }
495 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
496 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
497 }
498 }
499 if sdkDep.systemModules != "" {
500 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
501 }
502}
503
Colin Cross32f676a2017-09-06 13:41:06 -0700504type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700505 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
506 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
507 // systemModules and java9Classpath instead.
508 bootClasspath classpath
509
510 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
511 // contains header jars for all static and non-static dependencies.
512 classpath classpath
513
514 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
515 // header jars for all non-static dependencies. Static dependencies have already been
516 // combined into the program jar.
517 dexClasspath classpath
518
519 // java9Classpath is the list of jars that will be added to the classpath when targeting
520 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
521 // are provided by systemModules.
522 java9Classpath classpath
523
Colin Cross748b2d82020-11-19 13:52:06 -0800524 processorPath classpath
525 errorProneProcessorPath classpath
526 processorClasses []string
527 staticJars android.Paths
528 staticHeaderJars android.Paths
529 staticResourceJars android.Paths
530 aidlIncludeDirs android.Paths
531 srcs android.Paths
532 srcJars android.Paths
533 systemModules *systemModules
534 aidlPreprocess android.OptionalPath
535 kotlinStdlib android.Paths
536 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700537 kotlinPlugins android.Paths
Jihoon Kang6592e872023-12-19 01:13:16 +0000538 aconfigProtoFiles android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800539
540 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700541}
Colin Cross2fe66872015-03-30 17:20:39 -0700542
Colin Cross54250902017-12-05 09:28:08 -0800543func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
544 for _, f := range dep.Srcs() {
545 if f.Ext() != ".jar" {
546 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
547 ctx.OtherModuleName(dep.(blueprint.Module)))
548 }
549 }
550}
551
Jiyong Parkf1691d22021-03-29 20:11:58 +0900552func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700553 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700554 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700555 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900556 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca384250c2023-02-02 17:56:19 +0000557 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000558 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700559 }
Nan Zhang357466b2018-04-17 17:38:36 -0700560}
561
Jihoon Kangff878bf2022-12-22 21:26:06 +0000562// Java version for stubs generation
563func getStubsJavaVersion() javaVersion {
564 return JAVA_VERSION_8
565}
566
Colin Cross1e743852019-10-28 11:37:20 -0700567type javaVersion int
568
569const (
570 JAVA_VERSION_UNSUPPORTED = 0
571 JAVA_VERSION_6 = 6
572 JAVA_VERSION_7 = 7
573 JAVA_VERSION_8 = 8
574 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000575 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100576 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700577)
578
579func (v javaVersion) String() string {
580 switch v {
581 case JAVA_VERSION_6:
Sorin Bascad567a512024-01-15 16:38:46 +0000582 // Java version 1.6 no longer supported, bumping to 1.8
583 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700584 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000585 // Java version 1.7 no longer supported, bumping to 1.8
586 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700587 case JAVA_VERSION_8:
588 return "1.8"
589 case JAVA_VERSION_9:
590 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000591 case JAVA_VERSION_11:
592 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100593 case JAVA_VERSION_17:
594 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700595 default:
596 return "unsupported"
597 }
598}
599
Cole Faustd96eebf2022-06-28 14:41:27 -0700600func (v javaVersion) StringForKotlinc() string {
601 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
602 // error: unknown JVM target version: foo
Sorin Bascad567a512024-01-15 16:38:46 +0000603 // Supported versions: 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
Cole Faustd96eebf2022-06-28 14:41:27 -0700604 switch v {
Sorin Bascad567a512024-01-15 16:38:46 +0000605 case JAVA_VERSION_6:
606 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700607 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000608 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700609 case JAVA_VERSION_9:
610 return "9"
611 default:
612 return v.String()
613 }
614}
615
Colin Cross1e743852019-10-28 11:37:20 -0700616// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
617func (v javaVersion) usesJavaModules() bool {
618 return v >= 9
619}
620
621func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100622 switch javaVersion {
623 case "1.6", "6":
Sorin Bascad567a512024-01-15 16:38:46 +0000624 // Java version 1.6 no longer supported, bumping to 1.8
625 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100626 case "1.7", "7":
Sorin Bascad567a512024-01-15 16:38:46 +0000627 // Java version 1.7 no longer supported, bumping to 1.8
628 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100629 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700630 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100631 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700632 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000633 case "11":
634 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100635 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100636 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100637 case "10", "12", "13", "14", "15", "16":
638 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700639 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100640 default:
641 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700642 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100643 }
644}
645
Colin Cross2fe66872015-03-30 17:20:39 -0700646//
647// Java libraries (.jar file)
648//
649
Colin Crossf506d872017-07-19 15:53:04 -0700650type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700651 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700652
Colin Cross312634e2023-11-21 15:13:56 -0800653 combinedExportedProguardFlagsFile android.Path
Jared Duke5979b302022-12-19 21:08:39 +0000654
Colin Cross09ad3a62023-11-15 12:29:33 -0800655 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Colin Cross2fe66872015-03-30 17:20:39 -0700656}
657
Jiyong Park45bf82e2020-12-15 22:29:02 +0900658var _ android.ApexModule = (*Library)(nil)
659
satayevd604b212021-07-21 14:23:52 +0100660// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100661type PermittedPackagesForUpdatableBootJars interface {
662 PermittedPackagesForUpdatableBootJars() []string
663}
664
665var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
666
667func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
668 return j.properties.Permitted_packages
669}
670
Spandan Dase21a8d42024-01-23 23:56:29 +0000671func shouldUncompressDex(ctx android.ModuleContext, libName string, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000672 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Crossff694a82023-12-13 15:54:49 -0800673 if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000674 return true
675 }
676
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000677 // Store uncompressed (and do not strip) dex files from boot class path jars.
678 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
679 return true
680 }
681
682 // Store uncompressed dex files that are preopted on /system.
Spandan Dase21a8d42024-01-23 23:56:29 +0000683 if !dexpreopter.dexpreoptDisabled(ctx, libName) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, libName, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000684 return true
685 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800686 if ctx.Config().UncompressPrivAppDex() &&
687 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
688 return true
689 }
690
Colin Cross2fc72f62018-12-21 12:59:54 -0800691 return false
692}
693
Jiakai Zhang22450f22021-10-11 03:05:20 +0000694// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
695func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
696 if dexer.dexProperties.Uncompress_dex == nil {
697 // If the value was not force-set by the user, use reasonable default based on the module.
Spandan Dase21a8d42024-01-23 23:56:29 +0000698 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexpreopter))
Jiakai Zhang22450f22021-10-11 03:05:20 +0000699 }
700}
701
Colin Crossf506d872017-07-19 15:53:04 -0700702func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000703
704 j.provideHiddenAPIPropertyInfo(ctx)
705
Jiyong Park92315372021-04-02 08:45:46 +0900706 j.sdkVersion = j.SdkVersion(ctx)
707 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000708 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900709
Jihoon Kangfe914ed2024-02-12 22:49:21 +0000710 // SdkLibrary.GenerateAndroidBuildActions(ctx) sets the stubsLinkType to Unknown.
711 // If the stubsLinkType has already been set to Unknown, the stubsLinkType should
712 // not be overridden.
713 if j.stubsLinkType != Unknown {
714 if proptools.Bool(j.properties.Is_stubs_module) {
715 j.stubsLinkType = Stubs
716 } else {
717 j.stubsLinkType = Implementation
718 }
719 }
720
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000721 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
722
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000723 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
Colin Cross40213022023-12-13 15:19:49 -0800724 android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo)
Colin Cross312634e2023-11-21 15:13:56 -0800725 exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList()
726 j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...)
727
728 combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags")
729 writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles)
730 j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000731
Colin Crossff694a82023-12-13 15:54:49 -0800732 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -0700733 if !apexInfo.IsForPlatform() {
734 j.hideApexVariantFromMake = true
735 }
736
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100737 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +0000738 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800739 if ctx.Device() {
740 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +0000741 ctx, j.Name(), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross61df14a2021-12-01 13:04:46 -0800742 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
743 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
744 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
745 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
746 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700747 j.compile(ctx, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700748
Colin Cross56a83212020-09-15 18:30:11 -0700749 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900750 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Cross09ad3a62023-11-15 12:29:33 -0800751 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700752 if j.InstallMixin != nil {
753 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
754 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700755 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
756 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800757 j.hostdexInstallFile = ctx.InstallFile(
758 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700759 j.Stem()+"-hostdex.jar", j.outputFile)
760 }
761 var installDir android.InstallPath
762 if ctx.InstallInTestcases() {
763 var archDir string
764 if !ctx.Host() {
765 archDir = ctx.DeviceConfig().DeviceArch()
766 }
767 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
768 } else {
769 installDir = android.PathForModuleInstall(ctx, "framework")
770 }
771 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700772 }
Colin Crossb7a63242015-04-16 14:09:14 -0700773}
774
Colin Crossf506d872017-07-19 15:53:04 -0700775func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700776 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100777 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700778}
779
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000780const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000781 aidlIncludeDir = "aidl"
782 javaDir = "java"
783 jarFileSuffix = ".jar"
784 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000785)
786
Paul Duffina0dbf432019-12-05 11:25:53 +0000787// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000788func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000789 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000790}
791
Paul Duffina04c1072020-03-02 10:16:35 +0000792func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
793 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000794}
795
Paul Duffin13879572019-11-28 14:31:38 +0000796type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000797 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000798
799 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000800 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000801 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
802
803 // Function to compute the snapshot relative path to which the named library's
804 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000805 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000806
807 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
808 // files like aidl files should also be copied.
809 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000810}
811
Paul Duffindb170e42020-12-08 17:48:25 +0000812const (
813 onlyCopyJarToSnapshot = true
814 copyEverythingToSnapshot = false
815)
816
Paul Duffin296701e2021-07-14 10:29:36 +0100817func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
818 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000819}
820
821func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
822 _, ok := module.(*Library)
823 return ok
824}
825
Paul Duffin3a4eb502020-03-19 16:11:18 +0000826func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
827 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000828}
Paul Duffina0dbf432019-12-05 11:25:53 +0000829
Paul Duffin14eb4672020-03-02 11:33:02 +0000830func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000831 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000832}
833
834type librarySdkMemberProperties struct {
835 android.SdkMemberPropertiesBase
836
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000837 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000838 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100839
840 // The list of permitted packages that need to be passed to the prebuilts as they are used to
841 // create the updatable-bcp-packages.txt file.
842 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +0000843
844 // The value of the min_sdk_version property, translated into a number where possible.
845 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800846
847 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +0000848}
849
Paul Duffin3a4eb502020-03-19 16:11:18 +0000850func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000851 j := variant.(*Library)
852
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000853 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +0000854
Paul Duffina551a1c2020-03-17 21:04:24 +0000855 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100856
857 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +0000858
859 // If the min_sdk_version was set then add the canonical representation of the API level to the
860 // snapshot.
861 if j.deviceProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -0700862 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
863 if err != nil {
864 ctx.ModuleErrorf("%s", err)
865 }
Paul Duffinbb638eb2022-11-26 13:36:38 +0000866 p.MinSdkVersion = proptools.StringPtr(canonical)
867 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800868
869 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
870 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
871 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000872}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000873
Paul Duffin3a4eb502020-03-19 16:11:18 +0000874func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000875 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000876
Paul Duffindb170e42020-12-08 17:48:25 +0000877 memberType := ctx.MemberType().(*librarySdkMemberType)
878
Paul Duffina551a1c2020-03-17 21:04:24 +0000879 exportedJar := p.JarToExport
880 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000881 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000882 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000883
884 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000885 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
886
Paul Duffina551a1c2020-03-17 21:04:24 +0000887 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
888 }
889
Paul Duffinbb638eb2022-11-26 13:36:38 +0000890 if p.MinSdkVersion != nil {
891 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
892 }
893
Paul Duffin869de142021-07-15 14:14:41 +0100894 if len(p.PermittedPackages) > 0 {
895 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
896 }
897
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800898 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
899 if p.DexPreoptProfileGuided != nil {
900 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
901 }
902
Paul Duffindb170e42020-12-08 17:48:25 +0000903 // Do not copy anything else to the snapshot.
904 if memberType.onlyCopyJarToSnapshot {
905 return
906 }
907
Paul Duffina551a1c2020-03-17 21:04:24 +0000908 aidlIncludeDirs := p.AidlIncludeDirs
909 if len(aidlIncludeDirs) != 0 {
910 sdkModuleContext := ctx.SdkModuleContext()
911 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000912 // TODO(jiyong): copy parcelable declarations only
913 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
914 for _, file := range aidlFiles {
915 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
916 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000917 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000918
Paul Duffina551a1c2020-03-17 21:04:24 +0000919 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000920 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000921}
922
Colin Cross1b16b0e2019-02-12 14:41:32 -0800923// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
924//
925// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
926// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
927// as a `static_libs` dependency of another module.
928//
929// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
930// a device.
931//
932// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
933// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700934func LibraryFactory() android.Module {
935 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700936
Colin Crossce6734e2020-06-15 16:09:53 -0700937 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700938
Paul Duffin71b33cc2021-06-23 11:39:47 +0100939 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100940
Jiyong Park7f7766d2019-07-25 22:02:35 +0900941 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900942 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700943 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700944}
945
Colin Cross1b16b0e2019-02-12 14:41:32 -0800946// java_library_static is an obsolete alias for java_library.
947func LibraryStaticFactory() android.Module {
948 return LibraryFactory()
949}
950
951// java_library_host builds and links sources into a `.jar` file for the host.
952//
953// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
954// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700955func LibraryHostFactory() android.Module {
956 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700957
Colin Crossce6734e2020-06-15 16:09:53 -0700958 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700959
Colin Cross9ae1b922018-06-26 17:59:05 -0700960 module.Module.properties.Installable = proptools.BoolPtr(true)
961
Jiyong Park7f7766d2019-07-25 22:02:35 +0900962 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900963 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700964 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700965}
966
967//
Colin Crossb628ea52018-08-14 16:42:33 -0700968// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700969//
970
Dan Shi95d19422020-08-15 12:24:26 -0700971// Test option struct.
972type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800973 android.CommonTestOptions
974
Dan Shi95d19422020-08-15 12:24:26 -0700975 // a list of extra test configuration files that should be installed with the module.
976 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -0800977
978 // Extra <option> tags to add to the auto generated test xml file. The "key"
979 // is optional in each of these.
980 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +0000981
982 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
983 // The "key" is optional in each of these.
984 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -0700985}
986
Colin Cross05638fc2018-04-09 18:40:24 -0700987type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700988 // list of compatibility suites (for example "cts", "vts") that the module should be
989 // installed into.
990 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700991
992 // the name of the test configuration (for example "AndroidTest.xml") that should be
993 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800994 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700995
Jack He33338892018-09-19 02:21:28 -0700996 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
997 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800998 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700999
Colin Crossd96ca352018-08-10 16:06:24 -07001000 // list of files or filegroup modules that provide data that should be installed alongside
1001 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +09001002 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -07001003
1004 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
1005 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
1006 // explicitly.
1007 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +08001008
1009 // Add parameterized mainline modules to auto generated test config. The options will be
1010 // handled by TradeFed to do downloading and installing the specified modules on the device.
1011 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -07001012
1013 // Test options.
1014 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -08001015
1016 // Names of modules containing JNI libraries that should be installed alongside the test.
1017 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001018
1019 // Install the test into a folder named for the module in all test suites.
1020 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -07001021}
1022
Liz Kammerdd849a82020-06-12 16:38:45 -07001023type hostTestProperties struct {
1024 // list of native binary modules that should be installed alongside the test
1025 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +00001026
1027 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +00001028 // This property only adds the first variant of the dependency
1029 Data_device_bins_first []string `android:"arch_variant"`
1030
1031 // list of device binary modules that should be installed alongside the test
1032 // This property adds 64bit AND 32bit variants of the dependency
1033 Data_device_bins_both []string `android:"arch_variant"`
1034
1035 // list of device binary modules that should be installed alongside the test
1036 // This property only adds 64bit variants of the dependency
1037 Data_device_bins_64 []string `android:"arch_variant"`
1038
1039 // list of device binary modules that should be installed alongside the test
1040 // This property adds 32bit variants of the dependency if available, or else
1041 // defaults to the 64bit variant
1042 Data_device_bins_prefer32 []string `android:"arch_variant"`
1043
1044 // list of device binary modules that should be installed alongside the test
1045 // This property only adds 32bit variants of the dependency
1046 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001047}
1048
Paul Duffin42df1442019-03-20 12:45:53 +00001049type testHelperLibraryProperties struct {
1050 // list of compatibility suites (for example "cts", "vts") that the module should be
1051 // installed into.
1052 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001053
1054 // Install the test into a folder named for the module in all test suites.
1055 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001056}
1057
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001058type prebuiltTestProperties struct {
1059 // list of compatibility suites (for example "cts", "vts") that the module should be
1060 // installed into.
1061 Test_suites []string `android:"arch_variant"`
1062
1063 // the name of the test configuration (for example "AndroidTest.xml") that should be
1064 // installed with the module.
1065 Test_config *string `android:"path,arch_variant"`
1066}
1067
Colin Cross05638fc2018-04-09 18:40:24 -07001068type Test struct {
1069 Library
1070
1071 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001072
Dan Shi95d19422020-08-15 12:24:26 -07001073 testConfig android.Path
1074 extraTestConfigs android.Paths
1075 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001076}
1077
Liz Kammerdd849a82020-06-12 16:38:45 -07001078type TestHost struct {
1079 Test
1080
1081 testHostProperties hostTestProperties
1082}
1083
Paul Duffin42df1442019-03-20 12:45:53 +00001084type TestHelperLibrary struct {
1085 Library
1086
1087 testHelperLibraryProperties testHelperLibraryProperties
1088}
1089
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001090type JavaTestImport struct {
1091 Import
1092
1093 prebuiltTestProperties prebuiltTestProperties
1094
1095 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001096 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001097}
1098
Colin Cross24cc4be62021-11-03 14:09:41 -07001099func (j *Test) InstallInTestcases() bool {
1100 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1101 // testcases by base_rules.mk.
1102 return !j.Host()
1103}
1104
1105func (j *TestHelperLibrary) InstallInTestcases() bool {
1106 return true
1107}
1108
1109func (j *JavaTestImport) InstallInTestcases() bool {
1110 return true
1111}
1112
Colin Crossf5f4ad32024-01-19 15:41:48 -08001113func (j *TestHost) IsNativeCoverageNeeded(ctx android.IncomingTransitionContext) bool {
Yu Liud8aa2002023-10-05 11:40:06 -07001114 return ctx.DeviceConfig().NativeCoverageEnabled()
1115}
1116
Sam Delmericocc271e22022-06-01 15:45:02 +00001117func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1118 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1119 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1120 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1121 }
1122
1123 var maybeAndroid32Target *android.Target
1124 var maybeAndroid64Target *android.Target
1125 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1126 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1127 if len(android32TargetList) > 0 {
1128 maybeAndroid32Target = &android32TargetList[0]
1129 }
1130 if len(android64TargetList) > 0 {
1131 maybeAndroid64Target = &android64TargetList[0]
1132 }
1133
1134 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1135 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1136 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1137 return
1138 }
1139 if maybeAndroid32Target != nil {
1140 ctx.AddFarVariationDependencies(
1141 maybeAndroid32Target.Variations(),
1142 dataDeviceBinsTag,
1143 j.testHostProperties.Data_device_bins_both...,
1144 )
1145 }
1146 if maybeAndroid64Target != nil {
1147 ctx.AddFarVariationDependencies(
1148 maybeAndroid64Target.Variations(),
1149 dataDeviceBinsTag,
1150 j.testHostProperties.Data_device_bins_both...,
1151 )
1152 }
1153 }
1154
1155 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1156 if maybeAndroid32Target != nil {
1157 ctx.AddFarVariationDependencies(
1158 maybeAndroid32Target.Variations(),
1159 dataDeviceBinsTag,
1160 j.testHostProperties.Data_device_bins_prefer32...,
1161 )
1162 } else {
1163 if maybeAndroid64Target == nil {
1164 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1165 return
1166 }
1167 ctx.AddFarVariationDependencies(
1168 maybeAndroid64Target.Variations(),
1169 dataDeviceBinsTag,
1170 j.testHostProperties.Data_device_bins_prefer32...,
1171 )
1172 }
1173 }
1174
1175 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1176 if maybeAndroid32Target == nil {
1177 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1178 return
1179 }
1180 deviceVariations := maybeAndroid32Target.Variations()
1181 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1182 }
1183
1184 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1185 if maybeAndroid64Target == nil {
1186 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1187 return
1188 }
1189 deviceVariations := maybeAndroid64Target.Variations()
1190 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1191 }
1192}
1193
Liz Kammerdd849a82020-06-12 16:38:45 -07001194func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1195 if len(j.testHostProperties.Data_native_bins) > 0 {
1196 for _, target := range ctx.MultiTargets() {
1197 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1198 }
1199 }
1200
Colin Crossf8d9c492021-01-26 11:01:43 -08001201 if len(j.testProperties.Jni_libs) > 0 {
1202 for _, target := range ctx.MultiTargets() {
1203 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1204 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1205 }
1206 }
1207
Sam Delmericocc271e22022-06-01 15:45:02 +00001208 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001209 j.deps(ctx)
1210}
1211
Yuexi Ma627263f2021-03-04 13:47:56 -08001212func (j *TestHost) AddExtraResource(p android.Path) {
1213 j.extraResources = append(j.extraResources, p)
1214}
1215
Sam Delmericocc271e22022-06-01 15:45:02 +00001216func (j *TestHost) dataDeviceBins() []string {
1217 ret := make([]string, 0,
1218 len(j.testHostProperties.Data_device_bins_first)+
1219 len(j.testHostProperties.Data_device_bins_both)+
1220 len(j.testHostProperties.Data_device_bins_prefer32)+
1221 len(j.testHostProperties.Data_device_bins_32)+
1222 len(j.testHostProperties.Data_device_bins_64),
1223 )
1224
1225 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1226 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1227 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1228 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1229 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1230
1231 return ret
1232}
1233
Sam Delmericob3342ce2022-01-20 21:10:28 +00001234func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1235 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001236 dataDeviceBins := j.dataDeviceBins()
1237 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001238 // add Tradefed configuration to push device bins to device for testing
1239 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1240 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001241 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001242 fullPath := filepath.Join(remoteDir, bin)
1243 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1244 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001245 configs = append(configs, tradefed.Object{
1246 Type: "target_preparer",
1247 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1248 Options: options,
1249 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001250 }
1251
1252 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Colin Cross40213022023-12-13 15:19:49 -08001253 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001254}
1255
Colin Cross303e21f2018-08-07 16:49:25 -07001256func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001257 j.generateAndroidBuildActionsWithConfig(ctx, nil)
Colin Cross40213022023-12-13 15:19:49 -08001258 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001259}
1260
1261func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001262 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1263 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001264 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001265 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1266 }
Cole Faust21680542022-12-07 18:18:37 -08001267 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1268 TestConfigProp: j.testProperties.Test_config,
1269 TestConfigTemplateProp: j.testProperties.Test_config_template,
1270 TestSuites: j.testProperties.Test_suites,
1271 Config: configs,
1272 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001273 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001274 AutoGenConfig: j.testProperties.Auto_gen_config,
1275 UnitTest: j.testProperties.Test_options.Unit_test,
1276 DeviceTemplate: "${JavaTestConfigTemplate}",
1277 HostTemplate: "${JavaHostTestConfigTemplate}",
1278 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1279 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001280
Colin Cross8a497952019-03-05 22:25:09 -08001281 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001282
Dan Shi95d19422020-08-15 12:24:26 -07001283 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1284
Liz Kammerdd849a82020-06-12 16:38:45 -07001285 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1286 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1287 })
1288
Sam Delmericob3342ce2022-01-20 21:10:28 +00001289 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1290 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1291 })
1292
Colin Crossf8d9c492021-01-26 11:01:43 -08001293 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001294 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
Colin Crossf8d9c492021-01-26 11:01:43 -08001295 if sharedLibInfo.SharedLibrary != nil {
1296 // Copy to an intermediate output directory to append "lib[64]" to the path,
1297 // so that it's compatible with the default rpath values.
1298 var relPath string
1299 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1300 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1301 } else {
1302 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1303 }
1304 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1305 ctx.Build(pctx, android.BuildParams{
1306 Rule: android.Cp,
1307 Input: sharedLibInfo.SharedLibrary,
1308 Output: relocatedLib,
1309 })
1310 j.data = append(j.data, relocatedLib)
1311 } else {
1312 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1313 }
1314 })
1315
Colin Cross303e21f2018-08-07 16:49:25 -07001316 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001317}
1318
Paul Duffin42df1442019-03-20 12:45:53 +00001319func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1320 j.Library.GenerateAndroidBuildActions(ctx)
1321}
1322
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001323func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001324 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1325 TestConfigProp: j.prebuiltTestProperties.Test_config,
1326 TestSuites: j.prebuiltTestProperties.Test_suites,
1327 DeviceTemplate: "${JavaTestConfigTemplate}",
1328 HostTemplate: "${JavaHostTestConfigTemplate}",
1329 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1330 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001331
1332 j.Import.GenerateAndroidBuildActions(ctx)
1333}
1334
1335type testSdkMemberType struct {
1336 android.SdkMemberTypeBase
1337}
1338
Paul Duffin296701e2021-07-14 10:29:36 +01001339func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1340 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001341}
1342
1343func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1344 _, ok := module.(*Test)
1345 return ok
1346}
1347
Paul Duffin3a4eb502020-03-19 16:11:18 +00001348func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1349 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001350}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001351
Paul Duffin14eb4672020-03-02 11:33:02 +00001352func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1353 return &testSdkMemberProperties{}
1354}
1355
1356type testSdkMemberProperties struct {
1357 android.SdkMemberPropertiesBase
1358
Paul Duffina551a1c2020-03-17 21:04:24 +00001359 JarToExport android.Path
1360 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001361}
1362
Paul Duffin3a4eb502020-03-19 16:11:18 +00001363func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001364 test := variant.(*Test)
1365
1366 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001367 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001368 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001369 }
1370
Paul Duffina551a1c2020-03-17 21:04:24 +00001371 p.JarToExport = implementationJars[0]
1372 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001373}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001374
Paul Duffin3a4eb502020-03-19 16:11:18 +00001375func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001376 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001377
Paul Duffina551a1c2020-03-17 21:04:24 +00001378 exportedJar := p.JarToExport
1379 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001380 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001381 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001382
1383 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001384 }
1385
1386 testConfig := p.TestConfig
1387 if testConfig != nil {
1388 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1389 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001390 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1391 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001392}
1393
Colin Cross1b16b0e2019-02-12 14:41:32 -08001394// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1395// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1396//
1397// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1398// compiled against the device bootclasspath.
1399//
1400// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1401// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001402func TestFactory() android.Module {
1403 module := &Test{}
1404
Colin Crossce6734e2020-06-15 16:09:53 -07001405 module.addHostAndDeviceProperties()
1406 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001407
Colin Cross9ae1b922018-06-26 17:59:05 -07001408 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001409 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001410 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001411
Colin Cross05638fc2018-04-09 18:40:24 -07001412 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001413 return module
1414}
1415
Paul Duffin42df1442019-03-20 12:45:53 +00001416// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1417func TestHelperLibraryFactory() android.Module {
1418 module := &TestHelperLibrary{}
1419
Colin Crossce6734e2020-06-15 16:09:53 -07001420 module.addHostAndDeviceProperties()
1421 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001422
Colin Cross9a4abed2019-04-24 13:19:28 -07001423 module.Module.properties.Installable = proptools.BoolPtr(true)
1424 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001425 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001426
Paul Duffin42df1442019-03-20 12:45:53 +00001427 InitJavaModule(module, android.HostAndDeviceSupported)
1428 return module
1429}
1430
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001431// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1432// and makes sure that it is added to the appropriate test suite.
1433//
1434// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1435// compiled against an Android classpath.
1436//
1437// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1438// for host modules.
1439func JavaTestImportFactory() android.Module {
1440 module := &JavaTestImport{}
1441
1442 module.AddProperties(
1443 &module.Import.properties,
1444 &module.prebuiltTestProperties)
1445
1446 module.Import.properties.Installable = proptools.BoolPtr(true)
1447
1448 android.InitPrebuiltModule(module, &module.properties.Jars)
1449 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001450 InitJavaModule(module, android.HostAndDeviceSupported)
1451 return module
1452}
1453
Colin Cross1b16b0e2019-02-12 14:41:32 -08001454// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1455// allow running the test with `atest` or a `TEST_MAPPING` file.
1456//
1457// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1458// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001459func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001460 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001461
Colin Crossce6734e2020-06-15 16:09:53 -07001462 module.addHostProperties()
1463 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001464 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001465
Yuexi Ma627263f2021-03-04 13:47:56 -08001466 InitTestHost(
1467 module,
1468 proptools.BoolPtr(true),
1469 nil,
1470 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001471
Liz Kammerdd849a82020-06-12 16:38:45 -07001472 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001473
Colin Cross05638fc2018-04-09 18:40:24 -07001474 return module
1475}
1476
Yuexi Ma627263f2021-03-04 13:47:56 -08001477func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1478 th.properties.Installable = installable
1479 th.testProperties.Auto_gen_config = autoGenConfig
1480 th.testProperties.Test_suites = testSuites
1481}
1482
Colin Cross05638fc2018-04-09 18:40:24 -07001483//
Colin Cross2fe66872015-03-30 17:20:39 -07001484// Java Binaries (.jar file plus wrapper script)
1485//
1486
Colin Crossf506d872017-07-19 15:53:04 -07001487type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001488 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001489 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001490
1491 // Name of the class containing main to be inserted into the manifest as Main-Class.
1492 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001493
1494 // Names of modules containing JNI libraries that should be installed alongside the host
1495 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001496 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001497}
1498
Colin Crossf506d872017-07-19 15:53:04 -07001499type Binary struct {
1500 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001501
Colin Crossf506d872017-07-19 15:53:04 -07001502 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001503
Colin Cross6b4a32d2017-12-05 13:42:45 -08001504 isWrapperVariant bool
1505
Colin Crossc3315992017-12-08 19:12:36 -08001506 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001507 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001508}
1509
Alex Light24237172017-10-26 09:46:21 -07001510func (j *Binary) HostToolPath() android.OptionalPath {
1511 return android.OptionalPathForPath(j.binaryFile)
1512}
1513
Colin Crossf506d872017-07-19 15:53:04 -07001514func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001515 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
1516
Colin Cross6b4a32d2017-12-05 13:42:45 -08001517 if ctx.Arch().ArchType == android.Common {
1518 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001519 if j.binaryProperties.Main_class != nil {
1520 if j.properties.Manifest != nil {
1521 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1522 }
1523 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1524 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1525 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1526 }
1527
Colin Cross6b4a32d2017-12-05 13:42:45 -08001528 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001529 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001530 // Handle the binary wrapper
1531 j.isWrapperVariant = true
1532
Colin Cross366938f2017-12-11 16:29:02 -08001533 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001534 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001535 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001536 if ctx.Windows() {
1537 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1538 }
1539
Zi Wangca65b402022-10-10 13:45:06 -07001540 if ctx.Device() {
1541 // device binary should have a main_class property if it does not
1542 // have a specific wrapper, so that a default wrapper can
1543 // be generated for it.
1544 if j.binaryProperties.Main_class == nil {
1545 ctx.PropertyErrorf("main_class", "main_class property "+
1546 "is required for device binary if no default wrapper is assigned")
1547 } else {
1548 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1549 jarName := j.Stem() + ".jar"
1550 partition := j.PartitionTag(ctx.DeviceConfig())
1551 ctx.Build(pctx, android.BuildParams{
1552 Rule: deviceBinaryWrapper,
1553 Output: wrapper,
1554 Args: map[string]string{
1555 "jar_name": jarName,
1556 "partition": partition,
1557 "main_class": String(j.binaryProperties.Main_class),
1558 },
1559 })
1560 j.wrapperFile = wrapper
1561 }
1562 } else {
1563 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1564 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001565 }
1566
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001567 ext := ""
1568 if ctx.Windows() {
1569 ext = ".bat"
1570 }
1571
Colin Crossc179ea62020-10-09 10:54:15 -07001572 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001573 // of the wrapper variant, which will include the common variant's jar file and any JNI
1574 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001575 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001576 ctx.ModuleName()+ext, j.wrapperFile)
1577 }
Colin Cross2fe66872015-03-30 17:20:39 -07001578}
1579
Colin Crossf506d872017-07-19 15:53:04 -07001580func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001581 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001582 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001583 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001584 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001585 // These dependencies ensure the host installation rules will install the jar file and
1586 // the jni libraries when the wrapper is installed.
1587 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1588 ctx.AddVariationDependencies(
1589 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1590 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001591 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001592}
1593
Colin Cross1b16b0e2019-02-12 14:41:32 -08001594// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1595// as well.
1596//
1597// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1598// compiled against the device bootclasspath.
1599//
1600// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1601// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001602func BinaryFactory() android.Module {
1603 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001604
Colin Crossce6734e2020-06-15 16:09:53 -07001605 module.addHostAndDeviceProperties()
1606 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001607
Colin Cross9ae1b922018-06-26 17:59:05 -07001608 module.Module.properties.Installable = proptools.BoolPtr(true)
1609
Colin Cross6b4a32d2017-12-05 13:42:45 -08001610 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1611 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001612
Colin Cross36242852017-06-23 15:06:31 -07001613 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001614}
1615
Colin Cross1b16b0e2019-02-12 14:41:32 -08001616// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1617//
1618// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1619// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001620func BinaryHostFactory() android.Module {
1621 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001622
Colin Crossce6734e2020-06-15 16:09:53 -07001623 module.addHostProperties()
1624 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001625
Colin Cross9ae1b922018-06-26 17:59:05 -07001626 module.Module.properties.Installable = proptools.BoolPtr(true)
1627
Colin Cross6b4a32d2017-12-05 13:42:45 -08001628 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1629 android.InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001630 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001631}
1632
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001633type JavaApiContribution struct {
1634 android.ModuleBase
1635 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00001636 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001637
1638 properties struct {
1639 // name of the API surface
1640 Api_surface *string
1641
1642 // relative path to the API signature text file
1643 Api_file *string `android:"path"`
1644 }
1645}
1646
1647func ApiContributionFactory() android.Module {
1648 module := &JavaApiContribution{}
1649 android.InitAndroidModule(module)
1650 android.InitDefaultableModule(module)
1651 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001652 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001653 return module
1654}
1655
1656type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00001657 ApiFile android.Path
1658 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001659}
1660
Colin Crossbc7d76c2023-12-12 16:39:03 -08001661var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]()
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001662
1663func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001664 var apiFile android.Path = nil
1665 if apiFileString := ap.properties.Api_file; apiFileString != nil {
1666 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
1667 }
1668
Colin Cross40213022023-12-13 15:19:49 -08001669 android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00001670 ApiFile: apiFile,
1671 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001672 })
1673}
1674
1675type ApiLibrary struct {
1676 android.ModuleBase
1677 android.DefaultableModuleBase
1678
Spandan Dascb368ea2023-03-22 04:27:05 +00001679 hiddenAPI
1680 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00001681 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00001682
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001683 properties JavaApiLibraryProperties
1684
Jihoon Kang01e522c2023-03-14 01:09:34 +00001685 stubsSrcJar android.WritablePath
1686 stubsJar android.WritablePath
1687 stubsJarWithoutStaticLibs android.WritablePath
1688 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00001689 // .dex of stubs, used for hiddenapi processing
1690 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00001691
1692 validationPaths android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001693}
1694
1695type JavaApiLibraryProperties struct {
1696 // name of the API surface
1697 Api_surface *string
1698
Jihoon Kang60d4a092022-11-17 23:47:43 +00001699 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00001700 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00001701 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001702
1703 // List of flags to be passed to the javac compiler to generate jar file
1704 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001705
1706 // List of shared java libs that this module has dependencies to and
1707 // should be passed as classpath in javac invocation
1708 Libs []string
Jihoon Kange30fff02023-02-14 20:18:20 +00001709
1710 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00001711 // merge zipped after metalava invocation
Jihoon Kange30fff02023-02-14 20:18:20 +00001712 Static_libs []string
Jihoon Kang01e522c2023-03-14 01:09:34 +00001713
Jihoon Kangca198c22023-06-22 23:13:51 +00001714 // Java Api library to provide the full API surface stub jar file.
1715 // If this property is set, the stub jar of this module is created by
1716 // extracting the compiled class files provided by the
1717 // full_api_surface_stub module.
1718 Full_api_surface_stub *string
Jihoon Kang862da6f2023-08-01 06:28:51 +00001719
1720 // Version of previously released API file for compatibility check.
1721 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00001722
1723 // java_system_modules module providing the jar to be added to the
1724 // bootclasspath when compiling the stubs.
1725 // The jar will also be passed to metalava as a classpath to
1726 // generate compilable stubs.
1727 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00001728
1729 // If true, the module runs validation on the API signature files provided
1730 // by the modules passed via api_contributions by checking if the files are
1731 // in sync with the source Java files. However, the environment variable
1732 // DISABLE_STUB_VALIDATION has precedence over this property.
1733 Enable_validation *bool
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001734}
1735
1736func ApiLibraryFactory() android.Module {
1737 module := &ApiLibrary{}
1738 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001739 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001740 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00001741 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001742 return module
1743}
1744
1745func (al *ApiLibrary) ApiSurface() *string {
1746 return al.properties.Api_surface
1747}
1748
1749func (al *ApiLibrary) StubsJar() android.Path {
1750 return al.stubsJar
1751}
1752
1753func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00001754 srcs android.Paths, homeDir android.WritablePath,
1755 classpath android.Paths) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001756 rule.Command().Text("rm -rf").Flag(homeDir.String())
1757 rule.Command().Text("mkdir -p").Flag(homeDir.String())
1758
1759 cmd := rule.Command()
1760 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
1761
1762 if metalavaUseRbe(ctx) {
1763 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
1764 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
1765 labels := map[string]string{"type": "tool", "name": "metalava"}
1766
1767 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
1768 rule.Rewrapper(&remoteexec.REParams{
1769 Labels: labels,
1770 ExecStrategy: execStrategy,
1771 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
1772 Platform: map[string]string{remoteexec.PoolKey: pool},
1773 })
1774 }
1775
1776 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
1777 Flag(config.JavacVmFlags).
1778 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001779 FlagWithInputList("--source-files ", srcs, " ")
1780
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02001781 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001782 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00001783 Flag("--include-annotations").
1784 // The flag makes nullability issues as warnings rather than errors by replacing
1785 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
1786 // and these packages are meant to have everything annotated
1787 // @RecentlyNullable/@RecentlyNonNull.
1788 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001789 FlagWithArg("--repeat-errors-max ", "10").
1790 FlagWithArg("--hide ", "UnresolvedImport").
1791 FlagWithArg("--hide ", "InvalidNullabilityOverride").
1792 FlagWithArg("--hide ", "ChangedDefault")
1793
Jihoon Kang4ec24872023-10-05 17:26:09 +00001794 if len(classpath) == 0 {
1795 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
1796 // classes on the classpath when an API file contains missing classes. However, as this command
1797 // does not specify `--classpath` this is not needed for that. However, this is also used as a
1798 // signal to the special metalava code for generating stubs from text files that it needs to add
1799 // some additional items into the API (e.g. default constructors).
1800 cmd.FlagWithArg("--api-class-resolution ", "api")
1801 } else {
1802 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
1803 cmd.FlagWithInputList("--classpath ", classpath, ":")
1804 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01001805
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001806 return cmd
1807}
1808
Jihoon Kang1bff0342023-01-17 20:40:22 +00001809func (al *ApiLibrary) HeaderJars() android.Paths {
1810 return android.Paths{al.stubsJar}
1811}
1812
1813func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
1814 return nil, nil
1815}
1816
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001817func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
1818 if stubsDir.Valid() {
1819 cmd.FlagWithArg("--stubs ", stubsDir.String())
1820 }
1821}
1822
Jihoon Kang063ec002023-06-28 01:16:23 +00001823func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
1824 for _, validationPath := range validationPaths {
1825 cmd.Validation(validationPath)
1826 }
1827}
1828
Jihoon Kangca198c22023-06-22 23:13:51 +00001829// This method extracts the stub class files from the stub jar file provided
1830// from full_api_surface_stub module instead of compiling the srcjar generated from invoking metalava.
Jihoon Kang01e522c2023-03-14 01:09:34 +00001831// This method is used because metalava can generate compilable from-text stubs only when
Jihoon Kangca198c22023-06-22 23:13:51 +00001832// the codebase encompasses all classes listed in the input API text file, and a class can extend
Jihoon Kang01e522c2023-03-14 01:09:34 +00001833// a class that is not within the same API domain.
Jihoon Kangca198c22023-06-22 23:13:51 +00001834func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, fullApiSurfaceStubJar android.Path) {
1835 classFilesList := android.PathForModuleOut(ctx, "metalava", "classes.txt")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001836 unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
1837
1838 rule.Command().
1839 BuiltTool("list_files").
1840 Text(stubsDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001841 FlagWithOutput("--out ", classFilesList).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001842 FlagWithArg("--extensions ", ".java").
Jihoon Kangca198c22023-06-22 23:13:51 +00001843 FlagWithArg("--root ", unzippedSrcJarDir.String()).
1844 Flag("--classes")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001845
1846 rule.Command().
1847 Text("unzip").
1848 Flag("-q").
Jihoon Kangca198c22023-06-22 23:13:51 +00001849 Input(fullApiSurfaceStubJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001850 FlagWithArg("-d ", unzippedSrcJarDir.String())
1851
1852 rule.Command().
1853 BuiltTool("soong_zip").
Jihoon Kangca198c22023-06-22 23:13:51 +00001854 Flag("-jar").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001855 Flag("-write_if_changed").
Jihoon Kangca198c22023-06-22 23:13:51 +00001856 Flag("-ignore_missing_files").
Jihoon Kangd02a4362023-09-12 23:54:43 +00001857 Flag("-quiet").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001858 FlagWithArg("-C ", unzippedSrcJarDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001859 FlagWithInput("-l ", classFilesList).
1860 FlagWithOutput("-o ", al.stubsJarWithoutStaticLibs)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001861}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001862
1863func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00001864 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00001865 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
Jihoon Kang4f04df92024-01-30 02:30:06 +00001866 !ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") &&
Jihoon Kang063ec002023-06-28 01:16:23 +00001867 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00001868 for _, apiContributionName := range apiContributions {
1869 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00001870
1871 // Add the java_api_contribution module generating droidstubs module
1872 // as dependency when validation adding conditions are met and
1873 // the java_api_contribution module name has ".api.contribution" suffix.
1874 // All droidstubs-generated modules possess the suffix in the name,
1875 // but there is no such guarantee for tests.
1876 if addValidations {
1877 if strings.HasSuffix(apiContributionName, ".api.contribution") {
1878 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
1879 } else {
1880 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
1881 "current timestamp provider is not found for the api "+
1882 "contribution %s",
1883 ctx.ModuleName(),
1884 apiContributionName,
1885 )
1886 }
1887 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001888 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001889 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001890 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
Jihoon Kangca198c22023-06-22 23:13:51 +00001891 if al.properties.Full_api_surface_stub != nil {
1892 ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Full_api_surface_stub))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001893 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00001894 if al.properties.System_modules != nil {
1895 ctx.AddVariationDependencies(nil, systemModulesTag, String(al.properties.System_modules))
1896 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001897}
1898
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001899// Map where key is the api scope name and value is the int value
1900// representing the order of the api scope, narrowest to the widest
1901var scopeOrderMap = allApiScopes.MapToIndex(
1902 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00001903
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001904func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
1905 for _, srcFileInfo := range srcFilesInfo {
1906 if srcFileInfo.ApiSurface == "" {
1907 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00001908 }
1909 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001910 sort.Slice(srcFilesInfo, func(i, j int) bool {
1911 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
1912 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00001913
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001914 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00001915}
1916
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001917func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1918
1919 rule := android.NewRuleBuilder(pctx, ctx)
1920
1921 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
1922 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
1923 SandboxInputs()
1924
Jihoon Kang063ec002023-06-28 01:16:23 +00001925 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001926 rule.Command().Text("rm -rf").Text(stubsDir.String())
1927 rule.Command().Text("mkdir -p").Text(stubsDir.String())
1928
1929 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
1930
Jihoon Kang8fe19822023-09-14 06:27:36 +00001931 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001932 var classPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00001933 var staticLibs android.Paths
Jihoon Kangca198c22023-06-22 23:13:51 +00001934 var depApiSrcsStubsJar android.Path
Jihoon Kang4ec24872023-10-05 17:26:09 +00001935 var systemModulesPaths android.Paths
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001936 ctx.VisitDirectDeps(func(dep android.Module) {
1937 tag := ctx.OtherModuleDependencyTag(dep)
1938 switch tag {
1939 case javaApiContributionTag:
Colin Cross313aa542023-12-13 13:47:44 -08001940 provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider)
Jihoon Kang8fe19822023-09-14 06:27:36 +00001941 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001942 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
1943 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00001944 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001945 case libTag:
Colin Cross313aa542023-12-13 13:47:44 -08001946 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001947 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001948 case staticLibTag:
Colin Cross313aa542023-12-13 13:47:44 -08001949 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kange30fff02023-02-14 20:18:20 +00001950 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001951 case depApiSrcsTag:
Colin Cross313aa542023-12-13 13:47:44 -08001952 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kangca198c22023-06-22 23:13:51 +00001953 depApiSrcsStubsJar = provider.HeaderJars[0]
Jihoon Kang4ec24872023-10-05 17:26:09 +00001954 case systemModulesTag:
1955 module := dep.(SystemModulesProvider)
1956 systemModulesPaths = append(systemModulesPaths, module.HeaderJars()...)
Jihoon Kang063ec002023-06-28 01:16:23 +00001957 case metalavaCurrentApiTimestampTag:
1958 if currentApiTimestampProvider, ok := dep.(currentApiTimestampProvider); ok {
1959 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp())
1960 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001961 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00001962 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001963
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001964 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
1965 var srcFiles android.Paths
1966 for _, srcFileInfo := range srcFilesInfo {
1967 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00001968 }
1969
Jihoon Kang160634c2023-05-25 05:28:29 +00001970 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00001971 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
1972 }
1973
Jihoon Kang4ec24872023-10-05 17:26:09 +00001974 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001975
1976 al.stubsFlags(ctx, cmd, stubsDir)
1977
Jihoon Kang862da6f2023-08-01 06:28:51 +00001978 migratingNullability := String(al.properties.Previous_api) != ""
1979 if migratingNullability {
1980 previousApi := android.PathForModuleSrc(ctx, String(al.properties.Previous_api))
1981 cmd.FlagWithInput("--migrate-nullness ", previousApi)
1982 }
1983
Jihoon Kang063ec002023-06-28 01:16:23 +00001984 al.addValidation(ctx, cmd, al.validationPaths)
1985
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001986 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00001987 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
1988 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001989
Jihoon Kangca198c22023-06-22 23:13:51 +00001990 if depApiSrcsStubsJar != nil {
1991 al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsJar)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001992 }
Jihoon Kangca198c22023-06-22 23:13:51 +00001993 rule.Command().
1994 BuiltTool("soong_zip").
1995 Flag("-write_if_changed").
1996 Flag("-jar").
1997 FlagWithOutput("-o ", al.stubsSrcJar).
1998 FlagWithArg("-C ", stubsDir.String()).
1999 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002000
Paul Duffin336b16a2023-08-15 23:10:13 +01002001 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00002002
Jihoon Kangca198c22023-06-22 23:13:51 +00002003 if depApiSrcsStubsJar == nil {
2004 var flags javaBuilderFlags
2005 flags.javaVersion = getStubsJavaVersion()
2006 flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
2007 flags.classpath = classpath(classPaths)
Jihoon Kang4ec24872023-10-05 17:26:09 +00002008 flags.bootClasspath = classpath(systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002009
Vadim Spivak3c496f02023-06-08 06:14:59 +00002010 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
2011
Jihoon Kangca198c22023-06-22 23:13:51 +00002012 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
Vadim Spivak3c496f02023-06-08 06:14:59 +00002013 android.Paths{al.stubsSrcJar}, annoSrcJar, flags, android.Paths{})
Jihoon Kangca198c22023-06-22 23:13:51 +00002014 }
Jihoon Kang423d2292022-11-29 23:10:10 +00002015
Jihoon Kange30fff02023-02-14 20:18:20 +00002016 builder := android.NewRuleBuilder(pctx, ctx)
2017 builder.Command().
2018 BuiltTool("merge_zips").
2019 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00002020 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00002021 Inputs(staticLibs)
2022 builder.Build("merge_zips", "merge jar files")
2023
Spandan Dascb368ea2023-03-22 04:27:05 +00002024 // compile stubs to .dex for hiddenapi processing
2025 dexParams := &compileDexParams{
2026 flags: javaBuilderFlags{},
2027 sdkVersion: al.SdkVersion(ctx),
2028 minSdkVersion: al.MinSdkVersion(ctx),
2029 classesJar: al.stubsJar,
2030 jarName: ctx.ModuleName() + ".jar",
2031 }
2032 dexOutputFile := al.dexer.compileDex(ctx, dexParams)
2033 uncompressed := true
2034 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2035 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2036 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2037
Jihoon Kang423d2292022-11-29 23:10:10 +00002038 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002039
Colin Cross40213022023-12-13 15:19:49 -08002040 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jihoon Kang1bff0342023-01-17 20:40:22 +00002041 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2042 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2043 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2044 AidlIncludeDirs: android.Paths{},
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002045 StubsLinkType: Stubs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002046 // No aconfig libraries on api libraries
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002047 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002048}
2049
Spandan Das59a4a2b2024-01-09 21:35:56 +00002050func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dascb368ea2023-03-22 04:27:05 +00002051 return al.dexJarFile
2052}
2053
2054func (al *ApiLibrary) DexJarInstallPath() android.Path {
2055 return al.dexJarFile.Path()
2056}
2057
2058func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2059 return nil
2060}
2061
2062// java_api_library constitutes the sdk, and does not build against one
2063func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2064 return android.SdkSpecNone
2065}
2066
2067// java_api_library is always at "current". Return FutureApiLevel
2068func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2069 return android.FutureApiLevel
2070}
2071
2072// implement the following interfaces for hiddenapi processing
2073var _ hiddenAPIModule = (*ApiLibrary)(nil)
2074var _ UsesLibraryDependency = (*ApiLibrary)(nil)
2075
Colin Cross2fe66872015-03-30 17:20:39 -07002076//
2077// Java prebuilts
2078//
2079
Colin Cross74d73e22017-08-02 11:05:49 -07002080type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002081 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002082
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002083 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2084 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002085 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002086
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002087 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2088 // specified.
2089 Min_sdk_version *string
2090
William Loh5a082f92022-05-17 20:21:50 +00002091 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2092 // and uses-permission tags in manifest_fixer.
2093 Replace_max_sdk_version_placeholder *string
2094
Colin Cross535e2cf2017-10-20 17:57:49 -07002095 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002096
Paul Duffin869de142021-07-15 14:14:41 +01002097 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002098 Permitted_packages []string
2099
Jiyong Park1be96912018-05-28 18:02:19 +09002100 // List of shared java libs that this module has dependencies to
2101 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002102
2103 // List of files to remove from the jar file(s)
2104 Exclude_files []string
2105
2106 // List of directories to remove from the jar file(s)
2107 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002108
2109 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002110 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002111
2112 // set the name of the output
2113 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002114
2115 Aidl struct {
2116 // directories that should be added as include directories for any aidl sources of modules
2117 // that depend on this module, as well as to aidl for this module.
2118 Export_include_dirs []string
2119 }
Spandan Das3cf04632024-01-19 00:22:22 +00002120
2121 // Name of the source soong module that gets shadowed by this prebuilt
2122 // If unspecified, follows the naming convention that the source module of
2123 // the prebuilt is Name() without "prebuilt_" prefix
2124 Source_module_name *string
Spandan Das23956d12024-01-19 00:22:22 +00002125
2126 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2127 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2128 // (without any prebuilt_ prefix)
2129 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002130
2131 // Property signifying whether the module provides stubs jar or not.
2132 Is_stubs_module *bool
Colin Cross74d73e22017-08-02 11:05:49 -07002133}
2134
2135type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002136 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002137 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002138 android.ApexModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002139 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002140
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002141 // Functionality common to Module and Import.
2142 embeddableInModuleAndImport
2143
Liz Kammerd6c31d22020-08-05 15:40:41 -07002144 hiddenAPI
2145 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002146 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002147
Colin Cross74d73e22017-08-02 11:05:49 -07002148 properties ImportProperties
2149
Liz Kammerd6c31d22020-08-05 15:40:41 -07002150 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002151 dexJarFile OptionalDexJarPath
Spandan Dasfae468e2023-12-12 23:23:53 +00002152 dexJarFileErr error
Jeongik Chad5fe8782021-07-08 01:13:11 +09002153 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002154
Colin Cross0a6e0072017-08-30 14:24:55 -07002155 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002156 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09002157 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002158
2159 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002160
2161 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002162 minSdkVersion android.ApiLevel
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002163
2164 stubsLinkType StubsLinkType
Colin Cross2fe66872015-03-30 17:20:39 -07002165}
2166
Paul Duffin630b11e2021-07-15 13:35:26 +01002167var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2168
2169func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2170 return j.properties.Permitted_packages
2171}
2172
Jiyong Park92315372021-04-02 08:45:46 +09002173func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2174 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002175}
2176
Jiyong Parkf1691d22021-03-29 20:11:58 +09002177func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002178 return "none"
2179}
2180
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002181func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002182 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002183 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002184 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002185 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002186}
2187
Spandan Dasa26eda72023-03-02 00:56:06 +00002188func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002189 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002190 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002191 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002192 // Default is PrivateApiLevel
2193 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002194}
2195
Spandan Dasca70fc42023-03-01 23:38:49 +00002196func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2197 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002198}
2199
Colin Cross74d73e22017-08-02 11:05:49 -07002200func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002201 return &j.prebuilt
2202}
2203
Colin Cross74d73e22017-08-02 11:05:49 -07002204func (j *Import) PrebuiltSrcs() []string {
2205 return j.properties.Jars
2206}
2207
Spandan Das3cf04632024-01-19 00:22:22 +00002208func (j *Import) BaseModuleName() string {
2209 return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name())
2210}
2211
Colin Cross74d73e22017-08-02 11:05:49 -07002212func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002213 return j.prebuilt.Name(j.ModuleBase.Name())
2214}
2215
Jiyong Park0b238752019-10-29 11:23:10 +09002216func (j *Import) Stem() string {
Spandan Das3cf04632024-01-19 00:22:22 +00002217 return proptools.StringDefault(j.properties.Stem, j.BaseModuleName())
Jiyong Park0b238752019-10-29 11:23:10 +09002218}
2219
Spandan Das23956d12024-01-19 00:22:22 +00002220func (j *Import) CreatedByJavaSdkLibraryName() *string {
2221 return j.properties.Created_by_java_sdk_library_name
2222}
2223
Jiyong Park618922e2020-01-08 13:35:43 +09002224func (a *Import) JacocoReportClassesFile() android.Path {
2225 return nil
2226}
2227
Bill Peckhama41a6962021-01-11 10:58:54 -08002228func (j *Import) LintDepSets() LintDepSets {
2229 return LintDepSets{}
2230}
2231
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002232func (j *Import) getStrictUpdatabilityLinting() bool {
2233 return false
2234}
2235
2236func (j *Import) setStrictUpdatabilityLinting(bool) {
2237}
2238
Colin Cross74d73e22017-08-02 11:05:49 -07002239func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002240 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002241
2242 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002243 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002244 }
Colin Cross1e676be2016-10-12 14:38:15 -07002245}
2246
Sam Delmerico277795c2022-02-25 17:04:37 +00002247func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09002248 j.sdkVersion = j.SdkVersion(ctx)
2249 j.minSdkVersion = j.MinSdkVersion(ctx)
2250
Colin Crossff694a82023-12-13 15:54:49 -08002251 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
2252 if !apexInfo.IsForPlatform() {
Colin Cross56a83212020-09-15 18:30:11 -07002253 j.hideApexVariantFromMake = true
2254 }
2255
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002256 if ctx.Windows() {
2257 j.HideFromMake()
2258 }
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002259
2260 if proptools.Bool(j.properties.Is_stubs_module) {
2261 j.stubsLinkType = Stubs
2262 } else {
2263 j.stubsLinkType = Implementation
2264 }
Sam Delmerico277795c2022-02-25 17:04:37 +00002265}
2266
2267func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2268 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002269
Colin Cross8a497952019-03-05 22:25:09 -08002270 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07002271
Jiyong Park0b238752019-10-29 11:23:10 +09002272 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07002273 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07002274 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
2275 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07002276 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07002277 inputFile := outputFile
2278 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
2279 TransformJetifier(ctx, outputFile, inputFile)
2280 }
Colin Crosse9a275b2017-10-16 17:09:48 -07002281 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002282 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01002283
Liz Kammerd6c31d22020-08-05 15:40:41 -07002284 var flags javaBuilderFlags
2285
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002286 j.collectTransitiveHeaderJars(ctx)
Jiyong Park1be96912018-05-28 18:02:19 +09002287 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09002288 tag := ctx.OtherModuleDependencyTag(module)
Colin Cross313aa542023-12-13 13:47:44 -08002289 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002290 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002291 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002292 flags.classpath = append(flags.classpath, dep.HeaderJars...)
2293 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
2294 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002295 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002296 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002297 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09002298 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002299 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002300 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002301 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09002302 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09002303 }
2304 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002305
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002306 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09002307 })
2308
Sam Delmerico277795c2022-02-25 17:04:37 +00002309 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09002310
2311 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002312
Paul Duffin064b70c2020-11-02 17:32:38 +00002313 if ctx.Device() {
2314 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
2315 // obtained from the associated deapexer module.
Colin Crossff694a82023-12-13 15:54:49 -08002316 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Paul Duffin064b70c2020-11-02 17:32:38 +00002317 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00002318 // Get the path of the dex implementation jar from the `deapexer` module.
Spandan Dasfae468e2023-12-12 23:23:53 +00002319 di, err := android.FindDeapexerProviderForModule(ctx)
2320 if err != nil {
2321 // An error was found, possibly due to multiple apexes in the tree that export this library
2322 // Defer the error till a client tries to call DexJarBuildPath
2323 j.dexJarFileErr = err
Spandan Das3a392012024-01-17 18:26:27 +00002324 j.initHiddenAPIError(err)
Spandan Dasfae468e2023-12-12 23:23:53 +00002325 return
Martin Stjernholm44825602021-09-17 01:44:12 +01002326 }
Spandan Das5be63332023-12-13 00:06:32 +00002327 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(j.BaseModuleName())
Jiakai Zhang81e46812023-02-08 21:56:07 +08002328 if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002329 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
2330 j.dexJarFile = dexJarFile
Spandan Das5be63332023-12-13 00:06:32 +00002331 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, ApexRootRelativePathToJavaLib(j.BaseModuleName()))
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002332 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01002333
Spandan Dase21a8d42024-01-23 23:56:29 +00002334 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002335 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002336 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Jiakai Zhang81e46812023-02-08 21:56:07 +08002337
2338 if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
2339 j.dexpreopter.inputProfilePathOnHost = profilePath
2340 }
2341
Jiakai Zhang22450f22021-10-11 03:05:20 +00002342 // Initialize the hiddenapi structure.
2343 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00002344 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00002345 // This should never happen as a variant for a prebuilt_apex is only created if the
2346 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01002347 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00002348 }
2349 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002350 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00002351 if sdkDep.invalidVersion {
2352 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2353 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2354 } else if sdkDep.useFiles {
2355 // sdkDep.jar is actually equivalent to turbine header.jar.
2356 flags.classpath = append(flags.classpath, sdkDep.jars...)
2357 }
2358
2359 // Dex compilation
2360
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002361 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00002362 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00002363 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00002364 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
2365
Paul Duffin612e6102021-02-02 13:38:13 +00002366 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00002367 dexParams := &compileDexParams{
2368 flags: flags,
2369 sdkVersion: j.SdkVersion(ctx),
2370 minSdkVersion: j.MinSdkVersion(ctx),
2371 classesJar: outputFile,
2372 jarName: jarName,
2373 }
2374
2375 dexOutputFile = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00002376 if ctx.Failed() {
2377 return
2378 }
2379
Paul Duffin74d18d12021-05-14 14:18:47 +01002380 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002381 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01002382
2383 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01002384 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002385
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002386 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09002387 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002388 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002389 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002390
Colin Cross40213022023-12-13 15:19:49 -08002391 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Colin Crossdcf71b22021-02-01 13:59:03 -08002392 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002393 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
2394 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08002395 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
2396 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
2397 AidlIncludeDirs: j.exportAidlIncludeDirs,
Jihoon Kangfe914ed2024-02-12 22:49:21 +00002398 StubsLinkType: j.stubsLinkType,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002399 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08002400 })
Colin Cross2fe66872015-03-30 17:20:39 -07002401}
2402
Sam Delmerico277795c2022-02-25 17:04:37 +00002403func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
2404 if !Bool(j.properties.Installable) {
2405 return
2406 }
2407
2408 var installDir android.InstallPath
2409 if ctx.InstallInTestcases() {
2410 var archDir string
2411 if !ctx.Host() {
2412 archDir = ctx.DeviceConfig().DeviceArch()
2413 }
2414 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
2415 } else {
2416 installDir = android.PathForModuleInstall(ctx, "framework")
2417 }
2418 ctx.InstallFile(installDir, jarName, outputFile)
2419}
2420
Paul Duffinaa55f742020-10-06 17:20:13 +01002421func (j *Import) OutputFiles(tag string) (android.Paths, error) {
2422 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00002423 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01002424 return android.Paths{j.combinedClasspathFile}, nil
2425 default:
2426 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
2427 }
2428}
2429
2430var _ android.OutputFileProducer = (*Import)(nil)
2431
Nan Zhanged19fc32017-10-19 13:06:22 -07002432func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002433 if j.combinedClasspathFile == nil {
2434 return nil
2435 }
Colin Cross37f6d792018-07-12 12:28:41 -07002436 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07002437}
2438
Colin Cross331a1212018-08-15 20:40:52 -07002439func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002440 if j.combinedClasspathFile == nil {
2441 return nil
2442 }
Colin Cross331a1212018-08-15 20:40:52 -07002443 return android.Paths{j.combinedClasspathFile}
2444}
2445
Spandan Das59a4a2b2024-01-09 21:35:56 +00002446func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dasfae468e2023-12-12 23:23:53 +00002447 if j.dexJarFileErr != nil {
Spandan Das59a4a2b2024-01-09 21:35:56 +00002448 ctx.ModuleErrorf(j.dexJarFileErr.Error())
Spandan Dasfae468e2023-12-12 23:23:53 +00002449 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002450 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08002451}
2452
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002453func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09002454 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002455}
2456
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002457func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2458 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09002459}
2460
Jiyong Park45bf82e2020-12-15 22:29:02 +09002461var _ android.ApexModule = (*Import)(nil)
2462
2463// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09002464func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002465 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09002466}
2467
Jiyong Park45bf82e2020-12-15 22:29:02 +09002468// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002469func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2470 sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002471 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002472 minSdkVersion := j.MinSdkVersion(ctx)
2473 if !minSdkVersion.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002474 return fmt.Errorf("min_sdk_version is not specified")
2475 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002476 // If the module is compiling against core (via sdk_version), skip comparison check.
2477 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002478 return nil
2479 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002480 if minSdkVersion.GreaterThan(sdkVersion) {
2481 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002482 }
Jooyung Han749dc692020-04-15 11:03:39 +09002483 return nil
2484}
2485
Paul Duffinfef55002021-06-17 14:56:05 +01002486// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
2487// java_sdk_library_import with the specified base module name requires to be exported from a
2488// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002489func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
Spandan Das5be63332023-12-13 00:06:32 +00002490 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002491 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002492 files := []string{
2493 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01002494 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08002495 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
2496 files = append(files, dexJarFileApexRootRelative+".prof")
2497 }
2498 return files
Paul Duffinfef55002021-06-17 14:56:05 +01002499}
2500
Spandan Das5be63332023-12-13 00:06:32 +00002501// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002502// the java library with the specified name.
Spandan Das5be63332023-12-13 00:06:32 +00002503func ApexRootRelativePathToJavaLib(name string) string {
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002504 return filepath.Join("javalib", name+".jar")
2505}
2506
Paul Duffinfef55002021-06-17 14:56:05 +01002507var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
2508
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002509func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01002510 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08002511 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01002512}
2513
Spandan Das2ea84dd2024-01-25 22:12:50 +00002514func (j *Import) UseProfileGuidedDexpreopt() bool {
2515 return proptools.Bool(j.importDexpreoptProperties.Dex_preopt.Profile_guided)
2516}
2517
albaltai36ff7dc2018-12-25 14:35:23 +08002518// Add compile time check for interface implementation
2519var _ android.IDEInfo = (*Import)(nil)
2520var _ android.IDECustomizedModuleName = (*Import)(nil)
2521
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002522// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002523
2524func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
2525 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
2526}
2527
2528func (j *Import) IDECustomizedModuleName() string {
2529 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
2530 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
2531 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01002532 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002533}
2534
Colin Cross74d73e22017-08-02 11:05:49 -07002535var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07002536
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002537func (j *Import) IsInstallable() bool {
2538 return Bool(j.properties.Installable)
2539}
2540
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002541var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002542
Colin Cross1b16b0e2019-02-12 14:41:32 -08002543// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
2544//
2545// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
2546// compiled against an Android classpath.
2547//
2548// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
2549// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07002550func ImportFactory() android.Module {
2551 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07002552
Liz Kammerd6c31d22020-08-05 15:40:41 -07002553 module.AddProperties(
2554 &module.properties,
2555 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08002556 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07002557 )
Colin Cross74d73e22017-08-02 11:05:49 -07002558
Paul Duffin71b33cc2021-06-23 11:39:47 +01002559 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01002560
Liz Kammerd6c31d22020-08-05 15:40:41 -07002561 module.dexProperties.Optimize.EnabledByDefault = false
2562
Colin Cross74d73e22017-08-02 11:05:49 -07002563 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002564 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002565 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07002566 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002567}
2568
Colin Cross1b16b0e2019-02-12 14:41:32 -08002569// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
2570// module.
2571//
2572// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
2573// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07002574func ImportFactoryHost() android.Module {
2575 module := &Import{}
2576
2577 module.AddProperties(&module.properties)
2578
2579 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002580 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002581 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07002582 return module
2583}
2584
Colin Cross42be7612019-02-21 18:12:14 -08002585// dex_import module
2586
2587type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07002588 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09002589
2590 // set the name of the output
2591 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08002592}
2593
2594type DexImport struct {
2595 android.ModuleBase
2596 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002597 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08002598 prebuilt android.Prebuilt
2599
2600 properties DexImportProperties
2601
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002602 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08002603
2604 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07002605
2606 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08002607}
2608
2609func (j *DexImport) Prebuilt() *android.Prebuilt {
2610 return &j.prebuilt
2611}
2612
2613func (j *DexImport) PrebuiltSrcs() []string {
2614 return j.properties.Jars
2615}
2616
2617func (j *DexImport) Name() string {
2618 return j.prebuilt.Name(j.ModuleBase.Name())
2619}
2620
Jiyong Park0b238752019-10-29 11:23:10 +09002621func (j *DexImport) Stem() string {
2622 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2623}
2624
Jiyong Park77acec62020-06-01 21:39:15 +09002625func (a *DexImport) JacocoReportClassesFile() android.Path {
2626 return nil
2627}
2628
Colin Cross08dca382020-07-21 20:31:17 -07002629func (a *DexImport) LintDepSets() LintDepSets {
2630 return LintDepSets{}
2631}
2632
Martin Stjernholm6d415272020-01-31 17:10:36 +00002633func (j *DexImport) IsInstallable() bool {
2634 return true
2635}
2636
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002637func (j *DexImport) getStrictUpdatabilityLinting() bool {
2638 return false
2639}
2640
2641func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2642}
2643
Colin Cross42be7612019-02-21 18:12:14 -08002644func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2645 if len(j.properties.Jars) != 1 {
2646 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2647 }
2648
Colin Crossff694a82023-12-13 15:54:49 -08002649 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07002650 if !apexInfo.IsForPlatform() {
2651 j.hideApexVariantFromMake = true
2652 }
2653
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002654 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00002655 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
2656 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &j.dexpreopter)
Colin Cross42be7612019-02-21 18:12:14 -08002657
2658 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2659 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2660
2661 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002662 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002663
2664 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2665 rule.Temporary(temporary)
2666
2667 // use zip2zip to uncompress classes*.dex files
2668 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002669 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002670 FlagWithInput("-i ", inputJar).
2671 FlagWithOutput("-o ", temporary).
2672 FlagWithArg("-0 ", "'classes*.dex'")
2673
2674 // use zipalign to align uncompressed classes*.dex files
2675 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002676 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002677 Flag("-f").
2678 Text("4").
2679 Input(temporary).
2680 Output(dexOutputFile)
2681
2682 rule.DeleteTemporaryFiles()
2683
Colin Crossf1a035e2020-11-16 17:32:30 -08002684 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002685 } else {
2686 ctx.Build(pctx, android.BuildParams{
2687 Rule: android.Cp,
2688 Input: inputJar,
2689 Output: dexOutputFile,
2690 })
2691 }
2692
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002693 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002694
Spandan Dase21a8d42024-01-23 23:56:29 +00002695 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002696
Colin Cross56a83212020-09-15 18:30:11 -07002697 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002698 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2699 j.Stem()+".jar", dexOutputFile)
2700 }
Colin Cross42be7612019-02-21 18:12:14 -08002701}
2702
Spandan Das59a4a2b2024-01-09 21:35:56 +00002703func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002704 return j.dexJarFile
2705}
2706
Jiyong Park45bf82e2020-12-15 22:29:02 +09002707var _ android.ApexModule = (*DexImport)(nil)
2708
2709// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002710func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2711 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002712 // we don't check prebuilt modules for sdk_version
2713 return nil
2714}
2715
Colin Cross42be7612019-02-21 18:12:14 -08002716// dex_import imports a `.jar` file containing classes.dex files.
2717//
2718// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2719// to the device.
2720func DexImportFactory() android.Module {
2721 module := &DexImport{}
2722
2723 module.AddProperties(&module.properties)
2724
2725 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002726 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002727 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002728 return module
2729}
2730
Colin Cross89536d42017-07-07 14:35:50 -07002731// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002732type Defaults struct {
2733 android.ModuleBase
2734 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002735 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002736}
2737
Colin Cross1b16b0e2019-02-12 14:41:32 -08002738// java_defaults provides a set of properties that can be inherited by other java or android modules.
2739//
2740// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2741// property in the defaults module that exists in the depending module will be prepended to the depending module's
2742// value for that property.
2743//
2744// Example:
2745//
Sam Delmerico277795c2022-02-25 17:04:37 +00002746// java_defaults {
2747// name: "example_defaults",
2748// srcs: ["common/**/*.java"],
2749// javacflags: ["-Xlint:all"],
2750// aaptflags: ["--auto-add-overlay"],
2751// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002752//
Sam Delmerico277795c2022-02-25 17:04:37 +00002753// java_library {
2754// name: "example",
2755// defaults: ["example_defaults"],
2756// srcs: ["example/**/*.java"],
2757// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002758//
2759// is functionally identical to:
2760//
Sam Delmerico277795c2022-02-25 17:04:37 +00002761// java_library {
2762// name: "example",
2763// srcs: [
2764// "common/**/*.java",
2765// "example/**/*.java",
2766// ],
2767// javacflags: ["-Xlint:all"],
2768// }
Paul Duffin47357662019-12-05 14:07:14 +00002769func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002770 module := &Defaults{}
2771
Colin Cross89536d42017-07-07 14:35:50 -07002772 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002773 &CommonProperties{},
2774 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002775 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002776 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002777 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002778 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002779 &aaptProperties{},
2780 &androidLibraryProperties{},
2781 &appProperties{},
2782 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002783 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00002784 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002785 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002786 &ImportProperties{},
2787 &AARImportProperties{},
2788 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002789 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002790 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002791 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002792 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002793 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002794 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00002795 &JavaApiLibraryProperties{},
Jihoon Kang9272dcc2024-01-12 00:08:30 +00002796 &bootclasspathFragmentProperties{},
2797 &SourceOnlyBootclasspathProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002798 )
2799
2800 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002801 return module
2802}
Nan Zhangea568a42017-11-08 21:20:04 -08002803
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002804func kytheExtractJavaFactory() android.Singleton {
2805 return &kytheExtractJavaSingleton{}
2806}
2807
2808type kytheExtractJavaSingleton struct {
2809}
2810
2811func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2812 var xrefTargets android.Paths
2813 ctx.VisitAllModules(func(module android.Module) {
2814 if javaModule, ok := module.(xref); ok {
2815 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2816 }
2817 })
2818 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2819 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002820 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002821 }
2822}
2823
Nan Zhangea568a42017-11-08 21:20:04 -08002824var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002825var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002826var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04002827var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002828
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002829// Add class loader context (CLC) of a given dependency to the current CLC.
2830func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2831 clcMap dexpreopt.ClassLoaderContextMap) {
2832
2833 dep, ok := depModule.(UsesLibraryDependency)
2834 if !ok {
2835 return
2836 }
2837
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002838 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2839
2840 var sdkLib *string
2841 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2842 // A shared SDK library. This should be added as a top-level CLC element.
2843 sdkLib = &depName
2844 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2845 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2846 // property. This should be handled in the same way as a shared SDK library.
2847 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002848 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002849
2850 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002851 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002852 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002853 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2854 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002855 } else if depTag == staticLibTag {
2856 // Propagate <uses-library> through static library dependencies, unless it is a component
2857 // library (such as stubs). Component libraries have a dependency on their SDK library,
2858 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002859 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002860 return
2861 }
2862 } else {
2863 // Don't propagate <uses-library> for other dependency tags.
2864 return
2865 }
2866
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002867 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2868 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2869 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2870 // from its CLC should be added to the current CLC.
2871 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002872 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Spandan Das59a4a2b2024-01-09 21:35:56 +00002873 dep.DexJarBuildPath(ctx).PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002874 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002875 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2876 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002877}
Wei Libafb6d62021-12-10 03:14:59 -08002878
Jihoon Kangfdf32362023-09-12 00:36:43 +00002879type JavaApiContributionImport struct {
2880 JavaApiContribution
2881
Spandan Das23956d12024-01-19 00:22:22 +00002882 prebuilt android.Prebuilt
2883 prebuiltProperties javaApiContributionImportProperties
2884}
2885
2886type javaApiContributionImportProperties struct {
2887 // Name of the source soong module that gets shadowed by this prebuilt
2888 // If unspecified, follows the naming convention that the source module of
2889 // the prebuilt is Name() without "prebuilt_" prefix
2890 Source_module_name *string
2891
2892 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2893 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2894 // (without any prebuilt_ prefix)
2895 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfdf32362023-09-12 00:36:43 +00002896}
2897
2898func ApiContributionImportFactory() android.Module {
2899 module := &JavaApiContributionImport{}
2900 android.InitAndroidModule(module)
2901 android.InitDefaultableModule(module)
2902 android.InitPrebuiltModule(module, &[]string{""})
Spandan Das23956d12024-01-19 00:22:22 +00002903 module.AddProperties(&module.properties, &module.prebuiltProperties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002904 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00002905 return module
2906}
2907
2908func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
2909 return &module.prebuilt
2910}
2911
2912func (module *JavaApiContributionImport) Name() string {
2913 return module.prebuilt.Name(module.ModuleBase.Name())
2914}
2915
Spandan Das23956d12024-01-19 00:22:22 +00002916func (j *JavaApiContributionImport) BaseModuleName() string {
2917 return proptools.StringDefault(j.prebuiltProperties.Source_module_name, j.ModuleBase.Name())
2918}
2919
2920func (j *JavaApiContributionImport) CreatedByJavaSdkLibraryName() *string {
2921 return j.prebuiltProperties.Created_by_java_sdk_library_name
2922}
2923
Jihoon Kangfdf32362023-09-12 00:36:43 +00002924func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2925 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
2926}