blob: 576b73b68e6886c003d746a684c06daecbd47750 [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
90var (
91 // Supports adding java header libraries to module_exports and sdk.
92 javaHeaderLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +000093 android.SdkMemberTypeBase{
Paul Duffin2da04242021-04-23 19:43:28 +010094 PropertyName: "java_header_libs",
95 SupportsSdk: true,
96 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +000097 func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin2da04242021-04-23 19:43:28 +010098 headerJars := j.HeaderJars()
99 if len(headerJars) != 1 {
100 panic(fmt.Errorf("there must be only one header jar from %q", j.Name()))
101 }
102
103 return headerJars[0]
104 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000105 sdkSnapshotFilePathForJar,
106 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100107 }
Paul Duffin255f18e2019-12-13 11:22:16 +0000108
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000109 // Export implementation classes jar as part of the sdk.
Paul Duffin2da04242021-04-23 19:43:28 +0100110 exportImplementationClassesJar = func(_ android.SdkMemberContext, j *Library) android.Path {
Paul Duffin22ff0aa2021-02-04 11:15:34 +0000111 implementationJars := j.ImplementationAndResourcesJars()
112 if len(implementationJars) != 1 {
113 panic(fmt.Errorf("there must be only one implementation jar from %q", j.Name()))
114 }
115 return implementationJars[0]
116 }
117
Paul Duffin2da04242021-04-23 19:43:28 +0100118 // Supports adding java implementation libraries to module_exports but not sdk.
119 javaLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000120 android.SdkMemberTypeBase{
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000121 PropertyName: "java_libs",
122 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000123 exportImplementationClassesJar,
124 sdkSnapshotFilePathForJar,
125 copyEverythingToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100126 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000127
Paul Duffin13648912022-07-15 13:12:35 +0000128 snapshotRequiresImplementationJar = func(ctx android.SdkMemberContext) bool {
129 // In the S build the build will break if updatable-media does not provide a full implementation
130 // jar. That issue was fixed in Tiramisu by b/229932396.
131 if ctx.IsTargetBuildBeforeTiramisu() && ctx.Name() == "updatable-media" {
132 return true
133 }
134
135 return false
136 }
137
Paul Duffin2da04242021-04-23 19:43:28 +0100138 // Supports adding java boot libraries to module_exports and sdk.
Paul Duffindb170e42020-12-08 17:48:25 +0000139 //
140 // The build has some implicit dependencies (via the boot jars configuration) on a number of
141 // modules, e.g. core-oj, apache-xml, that are part of the java boot class path and which are
142 // provided by mainline modules (e.g. art, conscrypt, runtime-i18n) but which are not otherwise
143 // used outside those mainline modules.
144 //
145 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
146 // either java_libs, or java_header_libs would end up exporting more information than was strictly
147 // necessary. The java_boot_libs property to allow those modules to be exported as part of the
148 // sdk/module_exports without exposing any unnecessary information.
Paul Duffin2da04242021-04-23 19:43:28 +0100149 javaBootLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000150 android.SdkMemberTypeBase{
Paul Duffindb170e42020-12-08 17:48:25 +0000151 PropertyName: "java_boot_libs",
152 SupportsSdk: true,
153 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000154 func(ctx android.SdkMemberContext, j *Library) android.Path {
Paul Duffin13648912022-07-15 13:12:35 +0000155 if snapshotRequiresImplementationJar(ctx) {
156 return exportImplementationClassesJar(ctx, j)
157 }
158
Paul Duffin5c211452021-07-15 12:42:44 +0100159 // Java boot libs are only provided in the SDK to provide access to their dex implementation
160 // jar for use by dexpreopting and boot jars package check. They do not need to provide an
161 // actual implementation jar but the java_import will need a file that exists so just copy an
162 // empty file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000163 return ctx.SnapshotBuilder().EmptyFile()
Paul Duffin5c211452021-07-15 12:42:44 +0100164 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000165 func(ctx android.SdkMemberContext, osPrefix, name string) string {
Paul Duffin13648912022-07-15 13:12:35 +0000166 if snapshotRequiresImplementationJar(ctx) {
167 return sdkSnapshotFilePathForJar(ctx, osPrefix, name)
168 }
169
Paul Duffin5c211452021-07-15 12:42:44 +0100170 // Create a special name for the implementation jar to try and provide some useful information
171 // to a developer that attempts to compile against this.
172 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
173 return filepath.Join(osPrefix, "java_boot_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
174 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000175 onlyCopyJarToSnapshot,
Paul Duffin2da04242021-04-23 19:43:28 +0100176 }
Paul Duffindb170e42020-12-08 17:48:25 +0000177
Jiakai Zhangea180332021-09-26 08:58:02 +0000178 // Supports adding java systemserver libraries to module_exports and sdk.
179 //
180 // The build has some implicit dependencies (via the systemserver jars configuration) on a number
181 // of modules that are part of the java systemserver classpath and which are provided by mainline
182 // modules but which are not otherwise used outside those mainline modules.
183 //
184 // As they are not needed outside the mainline modules adding them to the sdk/module-exports as
185 // either java_libs, or java_header_libs would end up exporting more information than was strictly
186 // necessary. The java_systemserver_libs property to allow those modules to be exported as part of
187 // the sdk/module_exports without exposing any unnecessary information.
188 javaSystemserverLibsSdkMemberType = &librarySdkMemberType{
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000189 android.SdkMemberTypeBase{
Jiakai Zhangea180332021-09-26 08:58:02 +0000190 PropertyName: "java_systemserver_libs",
191 SupportsSdk: true,
Paul Duffinf861df72022-07-01 15:56:06 +0000192
193 // This was only added in Tiramisu.
194 SupportedBuildReleaseSpecification: "Tiramisu+",
Jiakai Zhangea180332021-09-26 08:58:02 +0000195 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000196 func(ctx android.SdkMemberContext, j *Library) android.Path {
Jiakai Zhangea180332021-09-26 08:58:02 +0000197 // Java systemserver libs are only provided in the SDK to provide access to their dex
198 // implementation jar for use by dexpreopting. They do not need to provide an actual
199 // implementation jar but the java_import will need a file that exists so just copy an empty
200 // file. Any attempt to use that file as a jar will cause a build error.
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000201 return ctx.SnapshotBuilder().EmptyFile()
Jiakai Zhangea180332021-09-26 08:58:02 +0000202 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000203 func(_ android.SdkMemberContext, osPrefix, name string) string {
Jiakai Zhangea180332021-09-26 08:58:02 +0000204 // Create a special name for the implementation jar to try and provide some useful information
205 // to a developer that attempts to compile against this.
206 // TODO(b/175714559): Provide a proper error message in Soong not ninja.
207 return filepath.Join(osPrefix, "java_systemserver_libs", "snapshot", "jars", "are", "invalid", name+jarFileSuffix)
208 },
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000209 onlyCopyJarToSnapshot,
Jiakai Zhangea180332021-09-26 08:58:02 +0000210 }
211
Paul Duffin2da04242021-04-23 19:43:28 +0100212 // Supports adding java test libraries to module_exports but not sdk.
213 javaTestSdkMemberType = &testSdkMemberType{
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000214 SdkMemberTypeBase: android.SdkMemberTypeBase{
215 PropertyName: "java_tests",
216 },
Paul Duffin2da04242021-04-23 19:43:28 +0100217 }
Zi Wangca65b402022-10-10 13:45:06 -0700218
219 // Rule for generating device binary default wrapper
220 deviceBinaryWrapper = pctx.StaticRule("deviceBinaryWrapper", blueprint.RuleParams{
221 Command: `echo -e '#!/system/bin/sh\n` +
222 `export CLASSPATH=/system/framework/$jar_name\n` +
223 `exec app_process /$partition/bin $main_class "$$@"'> ${out}`,
224 Description: "Generating device binary wrapper ${jar_name}",
225 }, "jar_name", "partition", "main_class")
Paul Duffin2da04242021-04-23 19:43:28 +0100226)
Jeongik Cha538c0d02019-07-11 15:54:27 +0900227
Sam Delmerico95d70942023-08-02 18:00:35 -0400228type ProguardSpecInfo struct {
229 // If true, proguard flags files will be exported to reverse dependencies across libs edges
230 // If false, proguard flags files will only be exported to reverse dependencies across
231 // static_libs edges.
232 Export_proguard_flags_files bool
233
234 // TransitiveDepsProguardSpecFiles is a depset of paths to proguard flags files that are exported from
235 // all transitive deps. This list includes all proguard flags files from transitive static dependencies,
236 // and all proguard flags files from transitive libs dependencies which set `export_proguard_spec: true`.
237 ProguardFlagsFiles *android.DepSet[android.Path]
238
239 // implementation detail to store transitive proguard flags files from exporting shared deps
240 UnconditionallyExportedProguardFlags *android.DepSet[android.Path]
241}
242
Colin Crossbc7d76c2023-12-12 16:39:03 -0800243var ProguardSpecInfoProvider = blueprint.NewProvider[ProguardSpecInfo]()
Sam Delmerico95d70942023-08-02 18:00:35 -0400244
Colin Crossdcf71b22021-02-01 13:59:03 -0800245// JavaInfo contains information about a java module for use by modules that depend on it.
246type JavaInfo struct {
247 // HeaderJars is a list of jars that can be passed as the javac classpath in order to link
248 // against this module. If empty, ImplementationJars should be used instead.
249 HeaderJars android.Paths
250
Joe Onorato349ae8d2024-02-05 22:46:00 +0000251 RepackagedHeaderJars android.Paths
252
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500253 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700254 TransitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500255
256 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700257 TransitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500258
Colin Crossdcf71b22021-02-01 13:59:03 -0800259 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
260 // in the module as well as any resources included in the module.
261 ImplementationAndResourcesJars android.Paths
262
263 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000264 //module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800265 ImplementationJars android.Paths
266
267 // ResourceJars is a list of jars that contain the resources included in the module.
268 ResourceJars android.Paths
269
270 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
271 // depending on this module.
272 AidlIncludeDirs android.Paths
273
274 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
275 // module.
276 SrcJarArgs []string
277
278 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
279 SrcJarDeps android.Paths
280
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000281 // The source files of this module and all its transitive static dependencies.
282 TransitiveSrcFiles *android.DepSet[android.Path]
283
Colin Crossdcf71b22021-02-01 13:59:03 -0800284 // ExportedPlugins is a list of paths that should be used as annotation processors for any
285 // module that depends on this module.
286 ExportedPlugins android.Paths
287
288 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
289 // any module that depends on this module.
290 ExportedPluginClasses []string
291
292 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
293 // requiring disbling turbine for any modules that depend on it.
294 ExportedPluginDisableTurbine bool
295
296 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
297 // instrumented by jacoco.
298 JacocoReportClassesFile android.Path
299}
300
Colin Crossbc7d76c2023-12-12 16:39:03 -0800301var JavaInfoProvider = blueprint.NewProvider[JavaInfo]()
Colin Crossdcf71b22021-02-01 13:59:03 -0800302
Colin Cross75ce9ec2021-02-26 16:20:32 -0800303// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
304// the sysprop implementation library.
305type SyspropPublicStubInfo struct {
306 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
307 // the sysprop implementation library.
308 JavaInfo JavaInfo
309}
310
Colin Crossbc7d76c2023-12-12 16:39:03 -0800311var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]()
Colin Cross75ce9ec2021-02-26 16:20:32 -0800312
Paul Duffin44b481b2020-06-17 16:59:43 +0100313// Methods that need to be implemented for a module that is added to apex java_libs property.
314type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700315 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100316 ImplementationAndResourcesJars() android.Paths
317}
318
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100319// Provides build path and install path to DEX jars.
320type UsesLibraryDependency interface {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000321 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100322 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000323 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100324}
325
Jaewoong Jung26342642021-03-17 15:56:23 -0700326// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800327type xref interface {
328 XrefJavaFiles() android.Paths
329}
330
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800331func (j *Module) XrefJavaFiles() android.Paths {
332 return j.kytheFiles
333}
334
Colin Crossbe1da472017-07-07 15:59:46 -0700335type dependencyTag struct {
336 blueprint.BaseDependencyTag
337 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000338
339 // True if the dependency is relinked at runtime.
340 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800341
342 // True if the dependency is a toolchain, for example an annotation processor.
343 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700344}
345
Colin Crosse9fe2942020-11-10 18:12:15 -0800346// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
347// dependency to be installed when the parent module is installed.
348type installDependencyTag struct {
349 blueprint.BaseDependencyTag
350 android.InstallAlwaysNeededDependencyTag
351 name string
352}
353
Colin Cross65cb3142021-12-10 23:05:02 +0000354func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
355 if d.runtimeLinked {
356 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800357 } else if d.toolchain {
358 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000359 }
360 return nil
361}
362
363var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
364
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100365type usesLibraryDependencyTag struct {
366 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100367 sdkVersion int // SDK version in which the library appared as a standalone library.
368 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100369}
370
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100371func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100372 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000373 dependencyTag: dependencyTag{
374 name: fmt.Sprintf("uses-library-%d", sdkVersion),
375 runtimeLinked: true,
376 },
377 sdkVersion: sdkVersion,
378 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100379 }
380}
381
Jiyong Park8be103b2019-11-08 15:53:48 +0900382func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700383 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900384}
385
Colin Crossbe1da472017-07-07 15:59:46 -0700386var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800387 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000388 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800389 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000390 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400391 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000392 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800393 pluginTag = dependencyTag{name: "plugin", toolchain: true}
394 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
395 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000396 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
397 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800398 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000399 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
400 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800401 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800402 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
403 certificateTag = dependencyTag{name: "certificate"}
404 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800405 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000406 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500407 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800408 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000409 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
410 depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
Jihoon Kang84b25892023-12-01 22:01:06 +0000411 aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800412 jniInstallTag = installDependencyTag{name: "jni install"}
413 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100414 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
415 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
416 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
417 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
418 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700419)
Colin Cross2fe66872015-03-30 17:20:39 -0700420
Jiyong Park83dc74b2020-01-14 18:38:44 +0900421func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400422 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900423}
424
425func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
426 return depTag == staticLibTag
427}
428
Colin Crossfc3674a2017-09-18 17:41:52 -0700429type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100430 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700431
Colin Cross6cef4812019-10-17 14:23:50 -0700432 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
433 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100434
435 // The default system modules to use. Will be an empty string if no system
436 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700437 systemModules string
438
Pete Gilline3d44b22020-06-29 11:28:51 +0100439 // The modules that will be added to the classpath regardless of the Java language level targeted
440 classpath []string
441
Colin Cross6cef4812019-10-17 14:23:50 -0700442 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100443 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700444 java9Classpath []string
445
Colin Crossa97c5d32018-03-28 14:58:31 -0700446 frameworkResModule string
447
Colin Cross86a60ae2018-05-29 14:44:55 -0700448 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700449 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100450
451 noStandardLibs, noFrameworksLibs bool
452}
453
454func (s sdkDep) hasStandardLibs() bool {
455 return !s.noStandardLibs
456}
457
458func (s sdkDep) hasFrameworkLibs() bool {
459 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700460}
461
Colin Crossa4f08812018-10-02 22:03:40 -0700462type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700463 name string
464 path android.Path
465 target android.Target
466 coverageFile android.OptionalPath
467 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000468 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700469}
470
Jiyong Parkf1691d22021-03-29 20:11:58 +0900471func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700472 sdkDep := decodeSdkDep(ctx, sdkContext)
473 if sdkDep.useModule {
474 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
475 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400476 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700477 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000478 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000479 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000480 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700481 }
482 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
483 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
484 }
485 }
486 if sdkDep.systemModules != "" {
487 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
488 }
489}
490
Colin Cross32f676a2017-09-06 13:41:06 -0700491type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700492 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
493 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
494 // systemModules and java9Classpath instead.
495 bootClasspath classpath
496
497 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
498 // contains header jars for all static and non-static dependencies.
499 classpath classpath
500
501 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
502 // header jars for all non-static dependencies. Static dependencies have already been
503 // combined into the program jar.
504 dexClasspath classpath
505
506 // java9Classpath is the list of jars that will be added to the classpath when targeting
507 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
508 // are provided by systemModules.
509 java9Classpath classpath
510
Colin Cross748b2d82020-11-19 13:52:06 -0800511 processorPath classpath
512 errorProneProcessorPath classpath
513 processorClasses []string
514 staticJars android.Paths
515 staticHeaderJars android.Paths
516 staticResourceJars android.Paths
517 aidlIncludeDirs android.Paths
518 srcs android.Paths
519 srcJars android.Paths
520 systemModules *systemModules
521 aidlPreprocess android.OptionalPath
522 kotlinStdlib android.Paths
523 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700524 kotlinPlugins android.Paths
Jihoon Kang6592e872023-12-19 01:13:16 +0000525 aconfigProtoFiles android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800526
527 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700528}
Colin Cross2fe66872015-03-30 17:20:39 -0700529
Colin Cross54250902017-12-05 09:28:08 -0800530func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
531 for _, f := range dep.Srcs() {
532 if f.Ext() != ".jar" {
533 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
534 ctx.OtherModuleName(dep.(blueprint.Module)))
535 }
536 }
537}
538
Jiyong Parkf1691d22021-03-29 20:11:58 +0900539func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700540 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700541 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700542 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900543 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca384250c2023-02-02 17:56:19 +0000544 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000545 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700546 }
Nan Zhang357466b2018-04-17 17:38:36 -0700547}
548
Jihoon Kangff878bf2022-12-22 21:26:06 +0000549// Java version for stubs generation
550func getStubsJavaVersion() javaVersion {
551 return JAVA_VERSION_8
552}
553
Colin Cross1e743852019-10-28 11:37:20 -0700554type javaVersion int
555
556const (
557 JAVA_VERSION_UNSUPPORTED = 0
558 JAVA_VERSION_6 = 6
559 JAVA_VERSION_7 = 7
560 JAVA_VERSION_8 = 8
561 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000562 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100563 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700564)
565
566func (v javaVersion) String() string {
567 switch v {
568 case JAVA_VERSION_6:
Sorin Bascad567a512024-01-15 16:38:46 +0000569 // Java version 1.6 no longer supported, bumping to 1.8
570 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700571 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000572 // Java version 1.7 no longer supported, bumping to 1.8
573 return "1.8"
Colin Cross1e743852019-10-28 11:37:20 -0700574 case JAVA_VERSION_8:
575 return "1.8"
576 case JAVA_VERSION_9:
577 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000578 case JAVA_VERSION_11:
579 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100580 case JAVA_VERSION_17:
581 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700582 default:
583 return "unsupported"
584 }
585}
586
Cole Faustd96eebf2022-06-28 14:41:27 -0700587func (v javaVersion) StringForKotlinc() string {
588 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
589 // error: unknown JVM target version: foo
Sorin Bascad567a512024-01-15 16:38:46 +0000590 // Supported versions: 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
Cole Faustd96eebf2022-06-28 14:41:27 -0700591 switch v {
Sorin Bascad567a512024-01-15 16:38:46 +0000592 case JAVA_VERSION_6:
593 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700594 case JAVA_VERSION_7:
Sorin Bascad567a512024-01-15 16:38:46 +0000595 return "1.8"
Cole Faustd96eebf2022-06-28 14:41:27 -0700596 case JAVA_VERSION_9:
597 return "9"
598 default:
599 return v.String()
600 }
601}
602
Colin Cross1e743852019-10-28 11:37:20 -0700603// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
604func (v javaVersion) usesJavaModules() bool {
605 return v >= 9
606}
607
608func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100609 switch javaVersion {
610 case "1.6", "6":
Sorin Bascad567a512024-01-15 16:38:46 +0000611 // Java version 1.6 no longer supported, bumping to 1.8
612 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100613 case "1.7", "7":
Sorin Bascad567a512024-01-15 16:38:46 +0000614 // Java version 1.7 no longer supported, bumping to 1.8
615 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100616 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700617 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100618 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700619 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000620 case "11":
621 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100622 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100623 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100624 case "10", "12", "13", "14", "15", "16":
625 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700626 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100627 default:
628 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700629 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100630 }
631}
632
Colin Cross2fe66872015-03-30 17:20:39 -0700633//
634// Java libraries (.jar file)
635//
636
Colin Crossf506d872017-07-19 15:53:04 -0700637type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700638 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700639
Colin Cross312634e2023-11-21 15:13:56 -0800640 combinedExportedProguardFlagsFile android.Path
Jared Duke5979b302022-12-19 21:08:39 +0000641
Colin Cross09ad3a62023-11-15 12:29:33 -0800642 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Colin Cross2fe66872015-03-30 17:20:39 -0700643}
644
Jiyong Park45bf82e2020-12-15 22:29:02 +0900645var _ android.ApexModule = (*Library)(nil)
646
satayevd604b212021-07-21 14:23:52 +0100647// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100648type PermittedPackagesForUpdatableBootJars interface {
649 PermittedPackagesForUpdatableBootJars() []string
650}
651
652var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
653
654func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
655 return j.properties.Permitted_packages
656}
657
Spandan Dase21a8d42024-01-23 23:56:29 +0000658func shouldUncompressDex(ctx android.ModuleContext, libName string, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000659 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Crossff694a82023-12-13 15:54:49 -0800660 if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000661 return true
662 }
663
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000664 // Store uncompressed (and do not strip) dex files from boot class path jars.
665 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
666 return true
667 }
668
669 // Store uncompressed dex files that are preopted on /system.
Spandan Dase21a8d42024-01-23 23:56:29 +0000670 if !dexpreopter.dexpreoptDisabled(ctx, libName) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, libName, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000671 return true
672 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800673 if ctx.Config().UncompressPrivAppDex() &&
674 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
675 return true
676 }
677
Colin Cross2fc72f62018-12-21 12:59:54 -0800678 return false
679}
680
Jiakai Zhang22450f22021-10-11 03:05:20 +0000681// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
682func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
683 if dexer.dexProperties.Uncompress_dex == nil {
684 // If the value was not force-set by the user, use reasonable default based on the module.
Spandan Dase21a8d42024-01-23 23:56:29 +0000685 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexpreopter))
Jiakai Zhang22450f22021-10-11 03:05:20 +0000686 }
687}
688
Colin Crossf506d872017-07-19 15:53:04 -0700689func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000690
691 j.provideHiddenAPIPropertyInfo(ctx)
692
Jiyong Park92315372021-04-02 08:45:46 +0900693 j.sdkVersion = j.SdkVersion(ctx)
694 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000695 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900696
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000697 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
698
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000699 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
Colin Cross40213022023-12-13 15:19:49 -0800700 android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo)
Colin Cross312634e2023-11-21 15:13:56 -0800701 exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList()
702 j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...)
703
704 combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags")
705 writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles)
706 j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000707
Colin Crossff694a82023-12-13 15:54:49 -0800708 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -0700709 if !apexInfo.IsForPlatform() {
710 j.hideApexVariantFromMake = true
711 }
712
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100713 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +0000714 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800715 if ctx.Device() {
716 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +0000717 ctx, j.Name(), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross61df14a2021-12-01 13:04:46 -0800718 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
719 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
720 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
721 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
Spandan Das0727ba72024-02-13 16:37:43 +0000722 if j.usesLibrary.shouldDisableDexpreopt {
723 j.dexpreopter.disableDexpreopt()
724 }
Colin Cross61df14a2021-12-01 13:04:46 -0800725 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700726 j.compile(ctx, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700727
Colin Cross56a83212020-09-15 18:30:11 -0700728 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900729 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Cross09ad3a62023-11-15 12:29:33 -0800730 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700731 if j.InstallMixin != nil {
732 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
733 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700734 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
735 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800736 j.hostdexInstallFile = ctx.InstallFile(
737 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700738 j.Stem()+"-hostdex.jar", j.outputFile)
739 }
740 var installDir android.InstallPath
741 if ctx.InstallInTestcases() {
742 var archDir string
743 if !ctx.Host() {
744 archDir = ctx.DeviceConfig().DeviceArch()
745 }
746 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
747 } else {
748 installDir = android.PathForModuleInstall(ctx, "framework")
749 }
750 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700751 }
Colin Crossb7a63242015-04-16 14:09:14 -0700752}
753
Colin Crossf506d872017-07-19 15:53:04 -0700754func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700755 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100756 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700757}
758
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000759const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000760 aidlIncludeDir = "aidl"
761 javaDir = "java"
762 jarFileSuffix = ".jar"
763 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000764)
765
Paul Duffina0dbf432019-12-05 11:25:53 +0000766// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000767func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000768 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000769}
770
Paul Duffina04c1072020-03-02 10:16:35 +0000771func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
772 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000773}
774
Paul Duffin13879572019-11-28 14:31:38 +0000775type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000776 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000777
778 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000779 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000780 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
781
782 // Function to compute the snapshot relative path to which the named library's
783 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000784 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000785
786 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
787 // files like aidl files should also be copied.
788 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000789}
790
Paul Duffindb170e42020-12-08 17:48:25 +0000791const (
792 onlyCopyJarToSnapshot = true
793 copyEverythingToSnapshot = false
794)
795
Paul Duffin296701e2021-07-14 10:29:36 +0100796func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
797 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000798}
799
800func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
801 _, ok := module.(*Library)
802 return ok
803}
804
Paul Duffin3a4eb502020-03-19 16:11:18 +0000805func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
806 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000807}
Paul Duffina0dbf432019-12-05 11:25:53 +0000808
Paul Duffin14eb4672020-03-02 11:33:02 +0000809func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000810 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000811}
812
813type librarySdkMemberProperties struct {
814 android.SdkMemberPropertiesBase
815
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000816 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000817 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100818
819 // The list of permitted packages that need to be passed to the prebuilts as they are used to
820 // create the updatable-bcp-packages.txt file.
821 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +0000822
823 // The value of the min_sdk_version property, translated into a number where possible.
824 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800825
826 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +0000827}
828
Paul Duffin3a4eb502020-03-19 16:11:18 +0000829func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000830 j := variant.(*Library)
831
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000832 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +0000833
Paul Duffina551a1c2020-03-17 21:04:24 +0000834 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100835
836 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +0000837
838 // If the min_sdk_version was set then add the canonical representation of the API level to the
839 // snapshot.
840 if j.deviceProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -0700841 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
842 if err != nil {
843 ctx.ModuleErrorf("%s", err)
844 }
Paul Duffinbb638eb2022-11-26 13:36:38 +0000845 p.MinSdkVersion = proptools.StringPtr(canonical)
846 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800847
848 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
849 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
850 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000851}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000852
Paul Duffin3a4eb502020-03-19 16:11:18 +0000853func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000854 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000855
Paul Duffindb170e42020-12-08 17:48:25 +0000856 memberType := ctx.MemberType().(*librarySdkMemberType)
857
Paul Duffina551a1c2020-03-17 21:04:24 +0000858 exportedJar := p.JarToExport
859 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000860 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000861 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000862
863 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000864 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
865
Paul Duffina551a1c2020-03-17 21:04:24 +0000866 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
867 }
868
Paul Duffinbb638eb2022-11-26 13:36:38 +0000869 if p.MinSdkVersion != nil {
870 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
871 }
872
Paul Duffin869de142021-07-15 14:14:41 +0100873 if len(p.PermittedPackages) > 0 {
874 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
875 }
876
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800877 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
878 if p.DexPreoptProfileGuided != nil {
879 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
880 }
881
Paul Duffindb170e42020-12-08 17:48:25 +0000882 // Do not copy anything else to the snapshot.
883 if memberType.onlyCopyJarToSnapshot {
884 return
885 }
886
Paul Duffina551a1c2020-03-17 21:04:24 +0000887 aidlIncludeDirs := p.AidlIncludeDirs
888 if len(aidlIncludeDirs) != 0 {
889 sdkModuleContext := ctx.SdkModuleContext()
890 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000891 // TODO(jiyong): copy parcelable declarations only
892 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
893 for _, file := range aidlFiles {
894 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
895 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000896 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000897
Paul Duffina551a1c2020-03-17 21:04:24 +0000898 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000899 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000900}
901
Colin Cross1b16b0e2019-02-12 14:41:32 -0800902// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
903//
904// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
905// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
906// as a `static_libs` dependency of another module.
907//
908// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
909// a device.
910//
911// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
912// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700913func LibraryFactory() android.Module {
914 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700915
Colin Crossce6734e2020-06-15 16:09:53 -0700916 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700917
Paul Duffin71b33cc2021-06-23 11:39:47 +0100918 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100919
Jiyong Park7f7766d2019-07-25 22:02:35 +0900920 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900921 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700922 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700923}
924
Colin Cross1b16b0e2019-02-12 14:41:32 -0800925// java_library_static is an obsolete alias for java_library.
926func LibraryStaticFactory() android.Module {
927 return LibraryFactory()
928}
929
930// java_library_host builds and links sources into a `.jar` file for the host.
931//
932// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
933// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700934func LibraryHostFactory() android.Module {
935 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700936
Colin Crossce6734e2020-06-15 16:09:53 -0700937 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700938
Colin Cross9ae1b922018-06-26 17:59:05 -0700939 module.Module.properties.Installable = proptools.BoolPtr(true)
940
Jiyong Park7f7766d2019-07-25 22:02:35 +0900941 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900942 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700943 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700944}
945
946//
Colin Crossb628ea52018-08-14 16:42:33 -0700947// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700948//
949
Dan Shi95d19422020-08-15 12:24:26 -0700950// Test option struct.
951type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800952 android.CommonTestOptions
953
Dan Shi95d19422020-08-15 12:24:26 -0700954 // a list of extra test configuration files that should be installed with the module.
955 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -0800956
957 // Extra <option> tags to add to the auto generated test xml file. The "key"
958 // is optional in each of these.
959 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +0000960
961 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
962 // The "key" is optional in each of these.
963 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -0700964}
965
Colin Cross05638fc2018-04-09 18:40:24 -0700966type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700967 // list of compatibility suites (for example "cts", "vts") that the module should be
968 // installed into.
969 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700970
971 // the name of the test configuration (for example "AndroidTest.xml") that should be
972 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800973 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700974
Jack He33338892018-09-19 02:21:28 -0700975 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
976 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800977 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700978
Colin Crossd96ca352018-08-10 16:06:24 -0700979 // list of files or filegroup modules that provide data that should be installed alongside
980 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900981 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700982
983 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
984 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
985 // explicitly.
986 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800987
988 // Add parameterized mainline modules to auto generated test config. The options will be
989 // handled by TradeFed to do downloading and installing the specified modules on the device.
990 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700991
992 // Test options.
993 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800994
995 // Names of modules containing JNI libraries that should be installed alongside the test.
996 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700997
998 // Install the test into a folder named for the module in all test suites.
999 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -07001000}
1001
Liz Kammerdd849a82020-06-12 16:38:45 -07001002type hostTestProperties struct {
1003 // list of native binary modules that should be installed alongside the test
1004 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +00001005
1006 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +00001007 // This property only adds the first variant of the dependency
1008 Data_device_bins_first []string `android:"arch_variant"`
1009
1010 // list of device binary modules that should be installed alongside the test
1011 // This property adds 64bit AND 32bit variants of the dependency
1012 Data_device_bins_both []string `android:"arch_variant"`
1013
1014 // list of device binary modules that should be installed alongside the test
1015 // This property only adds 64bit variants of the dependency
1016 Data_device_bins_64 []string `android:"arch_variant"`
1017
1018 // list of device binary modules that should be installed alongside the test
1019 // This property adds 32bit variants of the dependency if available, or else
1020 // defaults to the 64bit variant
1021 Data_device_bins_prefer32 []string `android:"arch_variant"`
1022
1023 // list of device binary modules that should be installed alongside the test
1024 // This property only adds 32bit variants of the dependency
1025 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001026}
1027
Paul Duffin42df1442019-03-20 12:45:53 +00001028type testHelperLibraryProperties struct {
1029 // list of compatibility suites (for example "cts", "vts") that the module should be
1030 // installed into.
1031 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001032
1033 // Install the test into a folder named for the module in all test suites.
1034 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001035}
1036
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001037type prebuiltTestProperties struct {
1038 // list of compatibility suites (for example "cts", "vts") that the module should be
1039 // installed into.
1040 Test_suites []string `android:"arch_variant"`
1041
1042 // the name of the test configuration (for example "AndroidTest.xml") that should be
1043 // installed with the module.
1044 Test_config *string `android:"path,arch_variant"`
1045}
1046
Colin Cross05638fc2018-04-09 18:40:24 -07001047type Test struct {
1048 Library
1049
1050 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001051
Dan Shi95d19422020-08-15 12:24:26 -07001052 testConfig android.Path
1053 extraTestConfigs android.Paths
1054 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001055}
1056
Liz Kammerdd849a82020-06-12 16:38:45 -07001057type TestHost struct {
1058 Test
1059
1060 testHostProperties hostTestProperties
1061}
1062
Paul Duffin42df1442019-03-20 12:45:53 +00001063type TestHelperLibrary struct {
1064 Library
1065
1066 testHelperLibraryProperties testHelperLibraryProperties
1067}
1068
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001069type JavaTestImport struct {
1070 Import
1071
1072 prebuiltTestProperties prebuiltTestProperties
1073
1074 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001075 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001076}
1077
Colin Cross24cc4be62021-11-03 14:09:41 -07001078func (j *Test) InstallInTestcases() bool {
1079 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1080 // testcases by base_rules.mk.
1081 return !j.Host()
1082}
1083
1084func (j *TestHelperLibrary) InstallInTestcases() bool {
1085 return true
1086}
1087
1088func (j *JavaTestImport) InstallInTestcases() bool {
1089 return true
1090}
1091
Colin Crossf5f4ad32024-01-19 15:41:48 -08001092func (j *TestHost) IsNativeCoverageNeeded(ctx android.IncomingTransitionContext) bool {
Yu Liud8aa2002023-10-05 11:40:06 -07001093 return ctx.DeviceConfig().NativeCoverageEnabled()
1094}
1095
Sam Delmericocc271e22022-06-01 15:45:02 +00001096func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1097 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1098 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1099 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1100 }
1101
1102 var maybeAndroid32Target *android.Target
1103 var maybeAndroid64Target *android.Target
1104 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1105 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1106 if len(android32TargetList) > 0 {
1107 maybeAndroid32Target = &android32TargetList[0]
1108 }
1109 if len(android64TargetList) > 0 {
1110 maybeAndroid64Target = &android64TargetList[0]
1111 }
1112
1113 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1114 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1115 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1116 return
1117 }
1118 if maybeAndroid32Target != nil {
1119 ctx.AddFarVariationDependencies(
1120 maybeAndroid32Target.Variations(),
1121 dataDeviceBinsTag,
1122 j.testHostProperties.Data_device_bins_both...,
1123 )
1124 }
1125 if maybeAndroid64Target != nil {
1126 ctx.AddFarVariationDependencies(
1127 maybeAndroid64Target.Variations(),
1128 dataDeviceBinsTag,
1129 j.testHostProperties.Data_device_bins_both...,
1130 )
1131 }
1132 }
1133
1134 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1135 if maybeAndroid32Target != nil {
1136 ctx.AddFarVariationDependencies(
1137 maybeAndroid32Target.Variations(),
1138 dataDeviceBinsTag,
1139 j.testHostProperties.Data_device_bins_prefer32...,
1140 )
1141 } else {
1142 if maybeAndroid64Target == nil {
1143 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1144 return
1145 }
1146 ctx.AddFarVariationDependencies(
1147 maybeAndroid64Target.Variations(),
1148 dataDeviceBinsTag,
1149 j.testHostProperties.Data_device_bins_prefer32...,
1150 )
1151 }
1152 }
1153
1154 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1155 if maybeAndroid32Target == nil {
1156 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1157 return
1158 }
1159 deviceVariations := maybeAndroid32Target.Variations()
1160 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1161 }
1162
1163 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1164 if maybeAndroid64Target == nil {
1165 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1166 return
1167 }
1168 deviceVariations := maybeAndroid64Target.Variations()
1169 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1170 }
1171}
1172
Liz Kammerdd849a82020-06-12 16:38:45 -07001173func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1174 if len(j.testHostProperties.Data_native_bins) > 0 {
1175 for _, target := range ctx.MultiTargets() {
1176 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1177 }
1178 }
1179
Colin Crossf8d9c492021-01-26 11:01:43 -08001180 if len(j.testProperties.Jni_libs) > 0 {
1181 for _, target := range ctx.MultiTargets() {
1182 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1183 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1184 }
1185 }
1186
Sam Delmericocc271e22022-06-01 15:45:02 +00001187 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001188 j.deps(ctx)
1189}
1190
Yuexi Ma627263f2021-03-04 13:47:56 -08001191func (j *TestHost) AddExtraResource(p android.Path) {
1192 j.extraResources = append(j.extraResources, p)
1193}
1194
Sam Delmericocc271e22022-06-01 15:45:02 +00001195func (j *TestHost) dataDeviceBins() []string {
1196 ret := make([]string, 0,
1197 len(j.testHostProperties.Data_device_bins_first)+
1198 len(j.testHostProperties.Data_device_bins_both)+
1199 len(j.testHostProperties.Data_device_bins_prefer32)+
1200 len(j.testHostProperties.Data_device_bins_32)+
1201 len(j.testHostProperties.Data_device_bins_64),
1202 )
1203
1204 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1205 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1206 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1207 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1208 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1209
1210 return ret
1211}
1212
Sam Delmericob3342ce2022-01-20 21:10:28 +00001213func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1214 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001215 dataDeviceBins := j.dataDeviceBins()
1216 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001217 // add Tradefed configuration to push device bins to device for testing
1218 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1219 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001220 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001221 fullPath := filepath.Join(remoteDir, bin)
1222 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1223 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001224 configs = append(configs, tradefed.Object{
1225 Type: "target_preparer",
1226 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1227 Options: options,
1228 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001229 }
1230
1231 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Colin Cross40213022023-12-13 15:19:49 -08001232 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001233}
1234
Colin Cross303e21f2018-08-07 16:49:25 -07001235func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001236 j.generateAndroidBuildActionsWithConfig(ctx, nil)
Colin Cross40213022023-12-13 15:19:49 -08001237 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001238}
1239
1240func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001241 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1242 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001243 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001244 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1245 }
Cole Faust21680542022-12-07 18:18:37 -08001246 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1247 TestConfigProp: j.testProperties.Test_config,
1248 TestConfigTemplateProp: j.testProperties.Test_config_template,
1249 TestSuites: j.testProperties.Test_suites,
1250 Config: configs,
1251 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001252 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001253 AutoGenConfig: j.testProperties.Auto_gen_config,
1254 UnitTest: j.testProperties.Test_options.Unit_test,
1255 DeviceTemplate: "${JavaTestConfigTemplate}",
1256 HostTemplate: "${JavaHostTestConfigTemplate}",
1257 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1258 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001259
Colin Cross8a497952019-03-05 22:25:09 -08001260 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001261
Dan Shi95d19422020-08-15 12:24:26 -07001262 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1263
Liz Kammerdd849a82020-06-12 16:38:45 -07001264 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1265 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1266 })
1267
Sam Delmericob3342ce2022-01-20 21:10:28 +00001268 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1269 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1270 })
1271
Colin Crossf8d9c492021-01-26 11:01:43 -08001272 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001273 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
Colin Crossf8d9c492021-01-26 11:01:43 -08001274 if sharedLibInfo.SharedLibrary != nil {
1275 // Copy to an intermediate output directory to append "lib[64]" to the path,
1276 // so that it's compatible with the default rpath values.
1277 var relPath string
1278 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1279 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1280 } else {
1281 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1282 }
1283 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1284 ctx.Build(pctx, android.BuildParams{
1285 Rule: android.Cp,
1286 Input: sharedLibInfo.SharedLibrary,
1287 Output: relocatedLib,
1288 })
1289 j.data = append(j.data, relocatedLib)
1290 } else {
1291 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1292 }
1293 })
1294
Colin Cross303e21f2018-08-07 16:49:25 -07001295 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001296}
1297
Paul Duffin42df1442019-03-20 12:45:53 +00001298func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1299 j.Library.GenerateAndroidBuildActions(ctx)
1300}
1301
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001302func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001303 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1304 TestConfigProp: j.prebuiltTestProperties.Test_config,
1305 TestSuites: j.prebuiltTestProperties.Test_suites,
1306 DeviceTemplate: "${JavaTestConfigTemplate}",
1307 HostTemplate: "${JavaHostTestConfigTemplate}",
1308 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1309 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001310
1311 j.Import.GenerateAndroidBuildActions(ctx)
1312}
1313
1314type testSdkMemberType struct {
1315 android.SdkMemberTypeBase
1316}
1317
Paul Duffin296701e2021-07-14 10:29:36 +01001318func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1319 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001320}
1321
1322func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1323 _, ok := module.(*Test)
1324 return ok
1325}
1326
Paul Duffin3a4eb502020-03-19 16:11:18 +00001327func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1328 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001329}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001330
Paul Duffin14eb4672020-03-02 11:33:02 +00001331func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1332 return &testSdkMemberProperties{}
1333}
1334
1335type testSdkMemberProperties struct {
1336 android.SdkMemberPropertiesBase
1337
Paul Duffina551a1c2020-03-17 21:04:24 +00001338 JarToExport android.Path
1339 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001340}
1341
Paul Duffin3a4eb502020-03-19 16:11:18 +00001342func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001343 test := variant.(*Test)
1344
1345 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001346 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001347 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001348 }
1349
Paul Duffina551a1c2020-03-17 21:04:24 +00001350 p.JarToExport = implementationJars[0]
1351 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001352}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001353
Paul Duffin3a4eb502020-03-19 16:11:18 +00001354func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001355 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001356
Paul Duffina551a1c2020-03-17 21:04:24 +00001357 exportedJar := p.JarToExport
1358 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001359 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001360 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001361
1362 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001363 }
1364
1365 testConfig := p.TestConfig
1366 if testConfig != nil {
1367 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1368 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001369 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1370 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001371}
1372
Colin Cross1b16b0e2019-02-12 14:41:32 -08001373// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1374// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1375//
1376// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1377// compiled against the device bootclasspath.
1378//
1379// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1380// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001381func TestFactory() android.Module {
1382 module := &Test{}
1383
Colin Crossce6734e2020-06-15 16:09:53 -07001384 module.addHostAndDeviceProperties()
1385 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001386
Colin Cross9ae1b922018-06-26 17:59:05 -07001387 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001388 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001389 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001390
Colin Cross05638fc2018-04-09 18:40:24 -07001391 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001392 return module
1393}
1394
Paul Duffin42df1442019-03-20 12:45:53 +00001395// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1396func TestHelperLibraryFactory() android.Module {
1397 module := &TestHelperLibrary{}
1398
Colin Crossce6734e2020-06-15 16:09:53 -07001399 module.addHostAndDeviceProperties()
1400 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001401
Colin Cross9a4abed2019-04-24 13:19:28 -07001402 module.Module.properties.Installable = proptools.BoolPtr(true)
1403 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001404 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001405
Paul Duffin42df1442019-03-20 12:45:53 +00001406 InitJavaModule(module, android.HostAndDeviceSupported)
1407 return module
1408}
1409
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001410// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1411// and makes sure that it is added to the appropriate test suite.
1412//
1413// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1414// compiled against an Android classpath.
1415//
1416// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1417// for host modules.
1418func JavaTestImportFactory() android.Module {
1419 module := &JavaTestImport{}
1420
1421 module.AddProperties(
1422 &module.Import.properties,
1423 &module.prebuiltTestProperties)
1424
1425 module.Import.properties.Installable = proptools.BoolPtr(true)
1426
1427 android.InitPrebuiltModule(module, &module.properties.Jars)
1428 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001429 InitJavaModule(module, android.HostAndDeviceSupported)
1430 return module
1431}
1432
Colin Cross1b16b0e2019-02-12 14:41:32 -08001433// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1434// allow running the test with `atest` or a `TEST_MAPPING` file.
1435//
1436// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1437// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001438func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001439 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001440
Colin Crossce6734e2020-06-15 16:09:53 -07001441 module.addHostProperties()
1442 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001443 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001444
Yuexi Ma627263f2021-03-04 13:47:56 -08001445 InitTestHost(
1446 module,
1447 proptools.BoolPtr(true),
1448 nil,
1449 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001450
Liz Kammerdd849a82020-06-12 16:38:45 -07001451 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001452
Colin Cross05638fc2018-04-09 18:40:24 -07001453 return module
1454}
1455
Yuexi Ma627263f2021-03-04 13:47:56 -08001456func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1457 th.properties.Installable = installable
1458 th.testProperties.Auto_gen_config = autoGenConfig
1459 th.testProperties.Test_suites = testSuites
1460}
1461
Colin Cross05638fc2018-04-09 18:40:24 -07001462//
Colin Cross2fe66872015-03-30 17:20:39 -07001463// Java Binaries (.jar file plus wrapper script)
1464//
1465
Colin Crossf506d872017-07-19 15:53:04 -07001466type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001467 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001468 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001469
1470 // Name of the class containing main to be inserted into the manifest as Main-Class.
1471 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001472
1473 // Names of modules containing JNI libraries that should be installed alongside the host
1474 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001475 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001476}
1477
Colin Crossf506d872017-07-19 15:53:04 -07001478type Binary struct {
1479 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001480
Colin Crossf506d872017-07-19 15:53:04 -07001481 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001482
Colin Cross6b4a32d2017-12-05 13:42:45 -08001483 isWrapperVariant bool
1484
Colin Crossc3315992017-12-08 19:12:36 -08001485 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001486 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001487}
1488
Alex Light24237172017-10-26 09:46:21 -07001489func (j *Binary) HostToolPath() android.OptionalPath {
1490 return android.OptionalPathForPath(j.binaryFile)
1491}
1492
Colin Crossf506d872017-07-19 15:53:04 -07001493func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001494 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
1495
Colin Cross6b4a32d2017-12-05 13:42:45 -08001496 if ctx.Arch().ArchType == android.Common {
1497 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001498 if j.binaryProperties.Main_class != nil {
1499 if j.properties.Manifest != nil {
1500 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1501 }
1502 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1503 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1504 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1505 }
1506
Colin Cross6b4a32d2017-12-05 13:42:45 -08001507 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001508 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001509 // Handle the binary wrapper
1510 j.isWrapperVariant = true
1511
Colin Cross366938f2017-12-11 16:29:02 -08001512 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001513 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001514 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001515 if ctx.Windows() {
1516 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1517 }
1518
Zi Wangca65b402022-10-10 13:45:06 -07001519 if ctx.Device() {
1520 // device binary should have a main_class property if it does not
1521 // have a specific wrapper, so that a default wrapper can
1522 // be generated for it.
1523 if j.binaryProperties.Main_class == nil {
1524 ctx.PropertyErrorf("main_class", "main_class property "+
1525 "is required for device binary if no default wrapper is assigned")
1526 } else {
1527 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1528 jarName := j.Stem() + ".jar"
1529 partition := j.PartitionTag(ctx.DeviceConfig())
1530 ctx.Build(pctx, android.BuildParams{
1531 Rule: deviceBinaryWrapper,
1532 Output: wrapper,
1533 Args: map[string]string{
1534 "jar_name": jarName,
1535 "partition": partition,
1536 "main_class": String(j.binaryProperties.Main_class),
1537 },
1538 })
1539 j.wrapperFile = wrapper
1540 }
1541 } else {
1542 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1543 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001544 }
1545
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001546 ext := ""
1547 if ctx.Windows() {
1548 ext = ".bat"
1549 }
1550
Colin Crossc179ea62020-10-09 10:54:15 -07001551 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001552 // of the wrapper variant, which will include the common variant's jar file and any JNI
1553 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001554 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001555 ctx.ModuleName()+ext, j.wrapperFile)
1556 }
Colin Cross2fe66872015-03-30 17:20:39 -07001557}
1558
Colin Crossf506d872017-07-19 15:53:04 -07001559func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001560 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001561 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001562 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001563 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001564 // These dependencies ensure the host installation rules will install the jar file and
1565 // the jni libraries when the wrapper is installed.
1566 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1567 ctx.AddVariationDependencies(
1568 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1569 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001570 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001571}
1572
Colin Cross1b16b0e2019-02-12 14:41:32 -08001573// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1574// as well.
1575//
1576// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1577// compiled against the device bootclasspath.
1578//
1579// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1580// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001581func BinaryFactory() android.Module {
1582 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001583
Colin Crossce6734e2020-06-15 16:09:53 -07001584 module.addHostAndDeviceProperties()
1585 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001586
Colin Cross9ae1b922018-06-26 17:59:05 -07001587 module.Module.properties.Installable = proptools.BoolPtr(true)
1588
Colin Cross6b4a32d2017-12-05 13:42:45 -08001589 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1590 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001591
Colin Cross36242852017-06-23 15:06:31 -07001592 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001593}
1594
Colin Cross1b16b0e2019-02-12 14:41:32 -08001595// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1596//
1597// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1598// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001599func BinaryHostFactory() android.Module {
1600 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001601
Colin Crossce6734e2020-06-15 16:09:53 -07001602 module.addHostProperties()
1603 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001604
Colin Cross9ae1b922018-06-26 17:59:05 -07001605 module.Module.properties.Installable = proptools.BoolPtr(true)
1606
Colin Cross6b4a32d2017-12-05 13:42:45 -08001607 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1608 android.InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001609 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001610}
1611
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001612type JavaApiContribution struct {
1613 android.ModuleBase
1614 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00001615 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001616
1617 properties struct {
1618 // name of the API surface
1619 Api_surface *string
1620
1621 // relative path to the API signature text file
1622 Api_file *string `android:"path"`
1623 }
1624}
1625
1626func ApiContributionFactory() android.Module {
1627 module := &JavaApiContribution{}
1628 android.InitAndroidModule(module)
1629 android.InitDefaultableModule(module)
1630 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001631 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001632 return module
1633}
1634
1635type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00001636 ApiFile android.Path
1637 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001638}
1639
Colin Crossbc7d76c2023-12-12 16:39:03 -08001640var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]()
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001641
1642func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001643 var apiFile android.Path = nil
1644 if apiFileString := ap.properties.Api_file; apiFileString != nil {
1645 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
1646 }
1647
Colin Cross40213022023-12-13 15:19:49 -08001648 android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00001649 ApiFile: apiFile,
1650 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001651 })
1652}
1653
1654type ApiLibrary struct {
1655 android.ModuleBase
1656 android.DefaultableModuleBase
1657
Spandan Dascb368ea2023-03-22 04:27:05 +00001658 hiddenAPI
1659 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00001660 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00001661
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001662 properties JavaApiLibraryProperties
1663
Jihoon Kang01e522c2023-03-14 01:09:34 +00001664 stubsSrcJar android.WritablePath
1665 stubsJar android.WritablePath
1666 stubsJarWithoutStaticLibs android.WritablePath
1667 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00001668 // .dex of stubs, used for hiddenapi processing
1669 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00001670
1671 validationPaths android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001672}
1673
1674type JavaApiLibraryProperties struct {
1675 // name of the API surface
1676 Api_surface *string
1677
Jihoon Kang60d4a092022-11-17 23:47:43 +00001678 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00001679 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00001680 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001681
1682 // List of flags to be passed to the javac compiler to generate jar file
1683 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001684
1685 // List of shared java libs that this module has dependencies to and
1686 // should be passed as classpath in javac invocation
1687 Libs []string
Jihoon Kange30fff02023-02-14 20:18:20 +00001688
1689 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00001690 // merge zipped after metalava invocation
Jihoon Kange30fff02023-02-14 20:18:20 +00001691 Static_libs []string
Jihoon Kang01e522c2023-03-14 01:09:34 +00001692
Jihoon Kangca198c22023-06-22 23:13:51 +00001693 // Java Api library to provide the full API surface stub jar file.
1694 // If this property is set, the stub jar of this module is created by
1695 // extracting the compiled class files provided by the
1696 // full_api_surface_stub module.
1697 Full_api_surface_stub *string
Jihoon Kang862da6f2023-08-01 06:28:51 +00001698
1699 // Version of previously released API file for compatibility check.
1700 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00001701
1702 // java_system_modules module providing the jar to be added to the
1703 // bootclasspath when compiling the stubs.
1704 // The jar will also be passed to metalava as a classpath to
1705 // generate compilable stubs.
1706 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00001707
1708 // If true, the module runs validation on the API signature files provided
1709 // by the modules passed via api_contributions by checking if the files are
1710 // in sync with the source Java files. However, the environment variable
1711 // DISABLE_STUB_VALIDATION has precedence over this property.
1712 Enable_validation *bool
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001713}
1714
1715func ApiLibraryFactory() android.Module {
1716 module := &ApiLibrary{}
1717 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001718 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001719 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00001720 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001721 return module
1722}
1723
1724func (al *ApiLibrary) ApiSurface() *string {
1725 return al.properties.Api_surface
1726}
1727
1728func (al *ApiLibrary) StubsJar() android.Path {
1729 return al.stubsJar
1730}
1731
1732func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00001733 srcs android.Paths, homeDir android.WritablePath,
1734 classpath android.Paths) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001735 rule.Command().Text("rm -rf").Flag(homeDir.String())
1736 rule.Command().Text("mkdir -p").Flag(homeDir.String())
1737
1738 cmd := rule.Command()
1739 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
1740
1741 if metalavaUseRbe(ctx) {
1742 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
1743 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
1744 labels := map[string]string{"type": "tool", "name": "metalava"}
1745
1746 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
1747 rule.Rewrapper(&remoteexec.REParams{
1748 Labels: labels,
1749 ExecStrategy: execStrategy,
1750 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
1751 Platform: map[string]string{remoteexec.PoolKey: pool},
1752 })
1753 }
1754
1755 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
1756 Flag(config.JavacVmFlags).
1757 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001758 FlagWithInputList("--source-files ", srcs, " ")
1759
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02001760 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001761 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00001762 Flag("--include-annotations").
1763 // The flag makes nullability issues as warnings rather than errors by replacing
1764 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
1765 // and these packages are meant to have everything annotated
1766 // @RecentlyNullable/@RecentlyNonNull.
1767 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001768 FlagWithArg("--repeat-errors-max ", "10").
1769 FlagWithArg("--hide ", "UnresolvedImport").
1770 FlagWithArg("--hide ", "InvalidNullabilityOverride").
1771 FlagWithArg("--hide ", "ChangedDefault")
1772
Jihoon Kang4ec24872023-10-05 17:26:09 +00001773 if len(classpath) == 0 {
1774 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
1775 // classes on the classpath when an API file contains missing classes. However, as this command
1776 // does not specify `--classpath` this is not needed for that. However, this is also used as a
1777 // signal to the special metalava code for generating stubs from text files that it needs to add
1778 // some additional items into the API (e.g. default constructors).
1779 cmd.FlagWithArg("--api-class-resolution ", "api")
1780 } else {
1781 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
1782 cmd.FlagWithInputList("--classpath ", classpath, ":")
1783 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01001784
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001785 return cmd
1786}
1787
Jihoon Kang1bff0342023-01-17 20:40:22 +00001788func (al *ApiLibrary) HeaderJars() android.Paths {
1789 return android.Paths{al.stubsJar}
1790}
1791
1792func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
1793 return nil, nil
1794}
1795
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001796func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
1797 if stubsDir.Valid() {
1798 cmd.FlagWithArg("--stubs ", stubsDir.String())
1799 }
1800}
1801
Jihoon Kang063ec002023-06-28 01:16:23 +00001802func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
1803 for _, validationPath := range validationPaths {
1804 cmd.Validation(validationPath)
1805 }
1806}
1807
Jihoon Kangca198c22023-06-22 23:13:51 +00001808// This method extracts the stub class files from the stub jar file provided
1809// from full_api_surface_stub module instead of compiling the srcjar generated from invoking metalava.
Jihoon Kang01e522c2023-03-14 01:09:34 +00001810// This method is used because metalava can generate compilable from-text stubs only when
Jihoon Kangca198c22023-06-22 23:13:51 +00001811// the codebase encompasses all classes listed in the input API text file, and a class can extend
Jihoon Kang01e522c2023-03-14 01:09:34 +00001812// a class that is not within the same API domain.
Jihoon Kangca198c22023-06-22 23:13:51 +00001813func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, fullApiSurfaceStubJar android.Path) {
1814 classFilesList := android.PathForModuleOut(ctx, "metalava", "classes.txt")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001815 unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
1816
1817 rule.Command().
1818 BuiltTool("list_files").
1819 Text(stubsDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001820 FlagWithOutput("--out ", classFilesList).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001821 FlagWithArg("--extensions ", ".java").
Jihoon Kangca198c22023-06-22 23:13:51 +00001822 FlagWithArg("--root ", unzippedSrcJarDir.String()).
1823 Flag("--classes")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001824
1825 rule.Command().
1826 Text("unzip").
1827 Flag("-q").
Jihoon Kangca198c22023-06-22 23:13:51 +00001828 Input(fullApiSurfaceStubJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001829 FlagWithArg("-d ", unzippedSrcJarDir.String())
1830
1831 rule.Command().
1832 BuiltTool("soong_zip").
Jihoon Kangca198c22023-06-22 23:13:51 +00001833 Flag("-jar").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001834 Flag("-write_if_changed").
Jihoon Kangca198c22023-06-22 23:13:51 +00001835 Flag("-ignore_missing_files").
Jihoon Kangd02a4362023-09-12 23:54:43 +00001836 Flag("-quiet").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001837 FlagWithArg("-C ", unzippedSrcJarDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001838 FlagWithInput("-l ", classFilesList).
1839 FlagWithOutput("-o ", al.stubsJarWithoutStaticLibs)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001840}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001841
1842func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00001843 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00001844 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
Jihoon Kang4f04df92024-01-30 02:30:06 +00001845 !ctx.Config().IsEnvTrue("WITHOUT_CHECK_API") &&
Jihoon Kang063ec002023-06-28 01:16:23 +00001846 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00001847 for _, apiContributionName := range apiContributions {
1848 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00001849
1850 // Add the java_api_contribution module generating droidstubs module
1851 // as dependency when validation adding conditions are met and
1852 // the java_api_contribution module name has ".api.contribution" suffix.
1853 // All droidstubs-generated modules possess the suffix in the name,
1854 // but there is no such guarantee for tests.
1855 if addValidations {
1856 if strings.HasSuffix(apiContributionName, ".api.contribution") {
1857 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
1858 } else {
1859 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
1860 "current timestamp provider is not found for the api "+
1861 "contribution %s",
1862 ctx.ModuleName(),
1863 apiContributionName,
1864 )
1865 }
1866 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001867 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001868 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001869 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
Jihoon Kangca198c22023-06-22 23:13:51 +00001870 if al.properties.Full_api_surface_stub != nil {
1871 ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Full_api_surface_stub))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001872 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00001873 if al.properties.System_modules != nil {
1874 ctx.AddVariationDependencies(nil, systemModulesTag, String(al.properties.System_modules))
1875 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001876}
1877
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001878// Map where key is the api scope name and value is the int value
1879// representing the order of the api scope, narrowest to the widest
1880var scopeOrderMap = allApiScopes.MapToIndex(
1881 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00001882
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001883func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
1884 for _, srcFileInfo := range srcFilesInfo {
1885 if srcFileInfo.ApiSurface == "" {
1886 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00001887 }
1888 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001889 sort.Slice(srcFilesInfo, func(i, j int) bool {
1890 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
1891 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00001892
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001893 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00001894}
1895
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001896func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1897
1898 rule := android.NewRuleBuilder(pctx, ctx)
1899
1900 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
1901 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
1902 SandboxInputs()
1903
Jihoon Kang063ec002023-06-28 01:16:23 +00001904 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001905 rule.Command().Text("rm -rf").Text(stubsDir.String())
1906 rule.Command().Text("mkdir -p").Text(stubsDir.String())
1907
1908 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
1909
Jihoon Kang8fe19822023-09-14 06:27:36 +00001910 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001911 var classPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00001912 var staticLibs android.Paths
Jihoon Kangca198c22023-06-22 23:13:51 +00001913 var depApiSrcsStubsJar android.Path
Jihoon Kang4ec24872023-10-05 17:26:09 +00001914 var systemModulesPaths android.Paths
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001915 ctx.VisitDirectDeps(func(dep android.Module) {
1916 tag := ctx.OtherModuleDependencyTag(dep)
1917 switch tag {
1918 case javaApiContributionTag:
Colin Cross313aa542023-12-13 13:47:44 -08001919 provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider)
Jihoon Kang8fe19822023-09-14 06:27:36 +00001920 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001921 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
1922 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00001923 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001924 case libTag:
Colin Cross313aa542023-12-13 13:47:44 -08001925 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001926 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001927 case staticLibTag:
Colin Cross313aa542023-12-13 13:47:44 -08001928 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kange30fff02023-02-14 20:18:20 +00001929 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001930 case depApiSrcsTag:
Colin Cross313aa542023-12-13 13:47:44 -08001931 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kangca198c22023-06-22 23:13:51 +00001932 depApiSrcsStubsJar = provider.HeaderJars[0]
Jihoon Kang4ec24872023-10-05 17:26:09 +00001933 case systemModulesTag:
1934 module := dep.(SystemModulesProvider)
1935 systemModulesPaths = append(systemModulesPaths, module.HeaderJars()...)
Jihoon Kang063ec002023-06-28 01:16:23 +00001936 case metalavaCurrentApiTimestampTag:
1937 if currentApiTimestampProvider, ok := dep.(currentApiTimestampProvider); ok {
1938 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp())
1939 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001940 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00001941 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001942
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001943 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
1944 var srcFiles android.Paths
1945 for _, srcFileInfo := range srcFilesInfo {
1946 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00001947 }
1948
Jihoon Kang160634c2023-05-25 05:28:29 +00001949 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00001950 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
1951 }
1952
Jihoon Kang4ec24872023-10-05 17:26:09 +00001953 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001954
1955 al.stubsFlags(ctx, cmd, stubsDir)
1956
Jihoon Kang862da6f2023-08-01 06:28:51 +00001957 migratingNullability := String(al.properties.Previous_api) != ""
1958 if migratingNullability {
1959 previousApi := android.PathForModuleSrc(ctx, String(al.properties.Previous_api))
1960 cmd.FlagWithInput("--migrate-nullness ", previousApi)
1961 }
1962
Jihoon Kang063ec002023-06-28 01:16:23 +00001963 al.addValidation(ctx, cmd, al.validationPaths)
1964
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001965 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00001966 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
1967 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001968
Jihoon Kangca198c22023-06-22 23:13:51 +00001969 if depApiSrcsStubsJar != nil {
1970 al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsJar)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001971 }
Jihoon Kangca198c22023-06-22 23:13:51 +00001972 rule.Command().
1973 BuiltTool("soong_zip").
1974 Flag("-write_if_changed").
1975 Flag("-jar").
1976 FlagWithOutput("-o ", al.stubsSrcJar).
1977 FlagWithArg("-C ", stubsDir.String()).
1978 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001979
Paul Duffin336b16a2023-08-15 23:10:13 +01001980 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001981
Jihoon Kangca198c22023-06-22 23:13:51 +00001982 if depApiSrcsStubsJar == nil {
1983 var flags javaBuilderFlags
1984 flags.javaVersion = getStubsJavaVersion()
1985 flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
1986 flags.classpath = classpath(classPaths)
Jihoon Kang4ec24872023-10-05 17:26:09 +00001987 flags.bootClasspath = classpath(systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001988
Vadim Spivak3c496f02023-06-08 06:14:59 +00001989 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
1990
Jihoon Kangca198c22023-06-22 23:13:51 +00001991 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
Vadim Spivak3c496f02023-06-08 06:14:59 +00001992 android.Paths{al.stubsSrcJar}, annoSrcJar, flags, android.Paths{})
Jihoon Kangca198c22023-06-22 23:13:51 +00001993 }
Jihoon Kang423d2292022-11-29 23:10:10 +00001994
Jihoon Kange30fff02023-02-14 20:18:20 +00001995 builder := android.NewRuleBuilder(pctx, ctx)
1996 builder.Command().
1997 BuiltTool("merge_zips").
1998 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001999 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00002000 Inputs(staticLibs)
2001 builder.Build("merge_zips", "merge jar files")
2002
Spandan Dascb368ea2023-03-22 04:27:05 +00002003 // compile stubs to .dex for hiddenapi processing
2004 dexParams := &compileDexParams{
2005 flags: javaBuilderFlags{},
2006 sdkVersion: al.SdkVersion(ctx),
2007 minSdkVersion: al.MinSdkVersion(ctx),
2008 classesJar: al.stubsJar,
2009 jarName: ctx.ModuleName() + ".jar",
2010 }
2011 dexOutputFile := al.dexer.compileDex(ctx, dexParams)
2012 uncompressed := true
2013 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2014 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2015 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2016
Jihoon Kang423d2292022-11-29 23:10:10 +00002017 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002018
Colin Cross40213022023-12-13 15:19:49 -08002019 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jihoon Kang1bff0342023-01-17 20:40:22 +00002020 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2021 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2022 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2023 AidlIncludeDirs: android.Paths{},
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002024 // No aconfig libraries on api libraries
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002025 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002026}
2027
Spandan Das59a4a2b2024-01-09 21:35:56 +00002028func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dascb368ea2023-03-22 04:27:05 +00002029 return al.dexJarFile
2030}
2031
2032func (al *ApiLibrary) DexJarInstallPath() android.Path {
2033 return al.dexJarFile.Path()
2034}
2035
2036func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2037 return nil
2038}
2039
2040// java_api_library constitutes the sdk, and does not build against one
2041func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2042 return android.SdkSpecNone
2043}
2044
2045// java_api_library is always at "current". Return FutureApiLevel
2046func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2047 return android.FutureApiLevel
2048}
2049
2050// implement the following interfaces for hiddenapi processing
2051var _ hiddenAPIModule = (*ApiLibrary)(nil)
2052var _ UsesLibraryDependency = (*ApiLibrary)(nil)
2053
Colin Cross2fe66872015-03-30 17:20:39 -07002054//
2055// Java prebuilts
2056//
2057
Colin Cross74d73e22017-08-02 11:05:49 -07002058type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002059 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002060
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002061 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2062 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002063 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002064
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002065 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2066 // specified.
2067 Min_sdk_version *string
2068
William Loh5a082f92022-05-17 20:21:50 +00002069 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2070 // and uses-permission tags in manifest_fixer.
2071 Replace_max_sdk_version_placeholder *string
2072
Colin Cross535e2cf2017-10-20 17:57:49 -07002073 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002074
Paul Duffin869de142021-07-15 14:14:41 +01002075 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002076 Permitted_packages []string
2077
Jiyong Park1be96912018-05-28 18:02:19 +09002078 // List of shared java libs that this module has dependencies to
2079 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002080
2081 // List of files to remove from the jar file(s)
2082 Exclude_files []string
2083
2084 // List of directories to remove from the jar file(s)
2085 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002086
2087 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002088 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002089
2090 // set the name of the output
2091 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002092
2093 Aidl struct {
2094 // directories that should be added as include directories for any aidl sources of modules
2095 // that depend on this module, as well as to aidl for this module.
2096 Export_include_dirs []string
2097 }
Spandan Das3cf04632024-01-19 00:22:22 +00002098
2099 // Name of the source soong module that gets shadowed by this prebuilt
2100 // If unspecified, follows the naming convention that the source module of
2101 // the prebuilt is Name() without "prebuilt_" prefix
2102 Source_module_name *string
Spandan Das23956d12024-01-19 00:22:22 +00002103
2104 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2105 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2106 // (without any prebuilt_ prefix)
2107 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Colin Cross74d73e22017-08-02 11:05:49 -07002108}
2109
2110type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002111 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002112 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002113 android.ApexModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002114 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002115
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002116 // Functionality common to Module and Import.
2117 embeddableInModuleAndImport
2118
Liz Kammerd6c31d22020-08-05 15:40:41 -07002119 hiddenAPI
2120 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002121 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002122
Colin Cross74d73e22017-08-02 11:05:49 -07002123 properties ImportProperties
2124
Liz Kammerd6c31d22020-08-05 15:40:41 -07002125 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002126 dexJarFile OptionalDexJarPath
Spandan Dasfae468e2023-12-12 23:23:53 +00002127 dexJarFileErr error
Jeongik Chad5fe8782021-07-08 01:13:11 +09002128 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002129
Colin Cross0a6e0072017-08-30 14:24:55 -07002130 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002131 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09002132 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002133
2134 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002135
2136 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002137 minSdkVersion android.ApiLevel
Colin Cross2fe66872015-03-30 17:20:39 -07002138}
2139
Paul Duffin630b11e2021-07-15 13:35:26 +01002140var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2141
2142func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2143 return j.properties.Permitted_packages
2144}
2145
Jiyong Park92315372021-04-02 08:45:46 +09002146func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2147 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002148}
2149
Jiyong Parkf1691d22021-03-29 20:11:58 +09002150func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002151 return "none"
2152}
2153
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002154func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002155 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002156 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002157 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002158 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002159}
2160
Spandan Dasa26eda72023-03-02 00:56:06 +00002161func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002162 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002163 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002164 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002165 // Default is PrivateApiLevel
2166 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002167}
2168
Spandan Dasca70fc42023-03-01 23:38:49 +00002169func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2170 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002171}
2172
Colin Cross74d73e22017-08-02 11:05:49 -07002173func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002174 return &j.prebuilt
2175}
2176
Colin Cross74d73e22017-08-02 11:05:49 -07002177func (j *Import) PrebuiltSrcs() []string {
2178 return j.properties.Jars
2179}
2180
Spandan Das3cf04632024-01-19 00:22:22 +00002181func (j *Import) BaseModuleName() string {
2182 return proptools.StringDefault(j.properties.Source_module_name, j.ModuleBase.Name())
2183}
2184
Colin Cross74d73e22017-08-02 11:05:49 -07002185func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002186 return j.prebuilt.Name(j.ModuleBase.Name())
2187}
2188
Jiyong Park0b238752019-10-29 11:23:10 +09002189func (j *Import) Stem() string {
Spandan Das3cf04632024-01-19 00:22:22 +00002190 return proptools.StringDefault(j.properties.Stem, j.BaseModuleName())
Jiyong Park0b238752019-10-29 11:23:10 +09002191}
2192
Spandan Das23956d12024-01-19 00:22:22 +00002193func (j *Import) CreatedByJavaSdkLibraryName() *string {
2194 return j.properties.Created_by_java_sdk_library_name
2195}
2196
Jiyong Park618922e2020-01-08 13:35:43 +09002197func (a *Import) JacocoReportClassesFile() android.Path {
2198 return nil
2199}
2200
Bill Peckhama41a6962021-01-11 10:58:54 -08002201func (j *Import) LintDepSets() LintDepSets {
2202 return LintDepSets{}
2203}
2204
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002205func (j *Import) getStrictUpdatabilityLinting() bool {
2206 return false
2207}
2208
2209func (j *Import) setStrictUpdatabilityLinting(bool) {
2210}
2211
Colin Cross74d73e22017-08-02 11:05:49 -07002212func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002213 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002214
2215 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002216 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002217 }
Colin Cross1e676be2016-10-12 14:38:15 -07002218}
2219
Sam Delmerico277795c2022-02-25 17:04:37 +00002220func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09002221 j.sdkVersion = j.SdkVersion(ctx)
2222 j.minSdkVersion = j.MinSdkVersion(ctx)
2223
Colin Crossff694a82023-12-13 15:54:49 -08002224 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
2225 if !apexInfo.IsForPlatform() {
Colin Cross56a83212020-09-15 18:30:11 -07002226 j.hideApexVariantFromMake = true
2227 }
2228
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002229 if ctx.Windows() {
2230 j.HideFromMake()
2231 }
Sam Delmerico277795c2022-02-25 17:04:37 +00002232}
2233
2234func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2235 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002236
Colin Cross8a497952019-03-05 22:25:09 -08002237 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07002238
Jiyong Park0b238752019-10-29 11:23:10 +09002239 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07002240 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07002241 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
2242 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07002243 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07002244 inputFile := outputFile
2245 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
2246 TransformJetifier(ctx, outputFile, inputFile)
2247 }
Colin Crosse9a275b2017-10-16 17:09:48 -07002248 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002249 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01002250
Liz Kammerd6c31d22020-08-05 15:40:41 -07002251 var flags javaBuilderFlags
2252
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002253 j.collectTransitiveHeaderJars(ctx)
Jiyong Park1be96912018-05-28 18:02:19 +09002254 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09002255 tag := ctx.OtherModuleDependencyTag(module)
Colin Cross313aa542023-12-13 13:47:44 -08002256 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002257 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002258 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002259 flags.classpath = append(flags.classpath, dep.HeaderJars...)
2260 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
2261 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002262 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002263 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002264 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09002265 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002266 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002267 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002268 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09002269 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09002270 }
2271 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002272
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002273 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09002274 })
2275
Sam Delmerico277795c2022-02-25 17:04:37 +00002276 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09002277
2278 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002279
Paul Duffin064b70c2020-11-02 17:32:38 +00002280 if ctx.Device() {
2281 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
2282 // obtained from the associated deapexer module.
Colin Crossff694a82023-12-13 15:54:49 -08002283 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Paul Duffin064b70c2020-11-02 17:32:38 +00002284 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00002285 // Get the path of the dex implementation jar from the `deapexer` module.
Spandan Dasfae468e2023-12-12 23:23:53 +00002286 di, err := android.FindDeapexerProviderForModule(ctx)
2287 if err != nil {
2288 // An error was found, possibly due to multiple apexes in the tree that export this library
2289 // Defer the error till a client tries to call DexJarBuildPath
2290 j.dexJarFileErr = err
Spandan Das3a392012024-01-17 18:26:27 +00002291 j.initHiddenAPIError(err)
Spandan Dasfae468e2023-12-12 23:23:53 +00002292 return
Martin Stjernholm44825602021-09-17 01:44:12 +01002293 }
Spandan Das5be63332023-12-13 00:06:32 +00002294 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(j.BaseModuleName())
Jiakai Zhang81e46812023-02-08 21:56:07 +08002295 if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002296 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
2297 j.dexJarFile = dexJarFile
Spandan Das5be63332023-12-13 00:06:32 +00002298 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, ApexRootRelativePathToJavaLib(j.BaseModuleName()))
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002299 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01002300
Spandan Dase21a8d42024-01-23 23:56:29 +00002301 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002302 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002303 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Jiakai Zhang81e46812023-02-08 21:56:07 +08002304
2305 if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
2306 j.dexpreopter.inputProfilePathOnHost = profilePath
2307 }
2308
Jiakai Zhang22450f22021-10-11 03:05:20 +00002309 // Initialize the hiddenapi structure.
2310 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00002311 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00002312 // This should never happen as a variant for a prebuilt_apex is only created if the
2313 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01002314 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00002315 }
2316 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002317 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00002318 if sdkDep.invalidVersion {
2319 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2320 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2321 } else if sdkDep.useFiles {
2322 // sdkDep.jar is actually equivalent to turbine header.jar.
2323 flags.classpath = append(flags.classpath, sdkDep.jars...)
2324 }
2325
2326 // Dex compilation
2327
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002328 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00002329 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00002330 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00002331 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
2332
Paul Duffin612e6102021-02-02 13:38:13 +00002333 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00002334 dexParams := &compileDexParams{
2335 flags: flags,
2336 sdkVersion: j.SdkVersion(ctx),
2337 minSdkVersion: j.MinSdkVersion(ctx),
2338 classesJar: outputFile,
2339 jarName: jarName,
2340 }
2341
2342 dexOutputFile = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00002343 if ctx.Failed() {
2344 return
2345 }
2346
Paul Duffin74d18d12021-05-14 14:18:47 +01002347 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002348 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01002349
2350 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01002351 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002352
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002353 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09002354 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002355 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002356 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002357
Colin Cross40213022023-12-13 15:19:49 -08002358 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Colin Crossdcf71b22021-02-01 13:59:03 -08002359 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002360 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
2361 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08002362 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
2363 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
2364 AidlIncludeDirs: j.exportAidlIncludeDirs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002365 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08002366 })
Colin Cross2fe66872015-03-30 17:20:39 -07002367}
2368
Sam Delmerico277795c2022-02-25 17:04:37 +00002369func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
2370 if !Bool(j.properties.Installable) {
2371 return
2372 }
2373
2374 var installDir android.InstallPath
2375 if ctx.InstallInTestcases() {
2376 var archDir string
2377 if !ctx.Host() {
2378 archDir = ctx.DeviceConfig().DeviceArch()
2379 }
2380 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
2381 } else {
2382 installDir = android.PathForModuleInstall(ctx, "framework")
2383 }
2384 ctx.InstallFile(installDir, jarName, outputFile)
2385}
2386
Paul Duffinaa55f742020-10-06 17:20:13 +01002387func (j *Import) OutputFiles(tag string) (android.Paths, error) {
2388 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00002389 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01002390 return android.Paths{j.combinedClasspathFile}, nil
2391 default:
2392 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
2393 }
2394}
2395
2396var _ android.OutputFileProducer = (*Import)(nil)
2397
Nan Zhanged19fc32017-10-19 13:06:22 -07002398func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002399 if j.combinedClasspathFile == nil {
2400 return nil
2401 }
Colin Cross37f6d792018-07-12 12:28:41 -07002402 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07002403}
2404
Colin Cross331a1212018-08-15 20:40:52 -07002405func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002406 if j.combinedClasspathFile == nil {
2407 return nil
2408 }
Colin Cross331a1212018-08-15 20:40:52 -07002409 return android.Paths{j.combinedClasspathFile}
2410}
2411
Spandan Das59a4a2b2024-01-09 21:35:56 +00002412func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dasfae468e2023-12-12 23:23:53 +00002413 if j.dexJarFileErr != nil {
Spandan Das59a4a2b2024-01-09 21:35:56 +00002414 ctx.ModuleErrorf(j.dexJarFileErr.Error())
Spandan Dasfae468e2023-12-12 23:23:53 +00002415 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002416 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08002417}
2418
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002419func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09002420 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002421}
2422
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002423func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2424 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09002425}
2426
Jiyong Park45bf82e2020-12-15 22:29:02 +09002427var _ android.ApexModule = (*Import)(nil)
2428
2429// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09002430func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002431 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09002432}
2433
Jiyong Park45bf82e2020-12-15 22:29:02 +09002434// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002435func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2436 sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002437 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002438 minSdkVersion := j.MinSdkVersion(ctx)
2439 if !minSdkVersion.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002440 return fmt.Errorf("min_sdk_version is not specified")
2441 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002442 // If the module is compiling against core (via sdk_version), skip comparison check.
2443 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002444 return nil
2445 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002446 if minSdkVersion.GreaterThan(sdkVersion) {
2447 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002448 }
Jooyung Han749dc692020-04-15 11:03:39 +09002449 return nil
2450}
2451
Paul Duffinfef55002021-06-17 14:56:05 +01002452// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
2453// java_sdk_library_import with the specified base module name requires to be exported from a
2454// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002455func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
Spandan Das5be63332023-12-13 00:06:32 +00002456 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002457 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002458 files := []string{
2459 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01002460 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08002461 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
2462 files = append(files, dexJarFileApexRootRelative+".prof")
2463 }
2464 return files
Paul Duffinfef55002021-06-17 14:56:05 +01002465}
2466
Spandan Das5be63332023-12-13 00:06:32 +00002467// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002468// the java library with the specified name.
Spandan Das5be63332023-12-13 00:06:32 +00002469func ApexRootRelativePathToJavaLib(name string) string {
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002470 return filepath.Join("javalib", name+".jar")
2471}
2472
Paul Duffinfef55002021-06-17 14:56:05 +01002473var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
2474
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002475func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01002476 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08002477 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01002478}
2479
Spandan Das2ea84dd2024-01-25 22:12:50 +00002480func (j *Import) UseProfileGuidedDexpreopt() bool {
2481 return proptools.Bool(j.importDexpreoptProperties.Dex_preopt.Profile_guided)
2482}
2483
albaltai36ff7dc2018-12-25 14:35:23 +08002484// Add compile time check for interface implementation
2485var _ android.IDEInfo = (*Import)(nil)
2486var _ android.IDECustomizedModuleName = (*Import)(nil)
2487
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002488// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002489
2490func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
2491 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
2492}
2493
2494func (j *Import) IDECustomizedModuleName() string {
2495 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
2496 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
2497 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01002498 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002499}
2500
Colin Cross74d73e22017-08-02 11:05:49 -07002501var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07002502
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002503func (j *Import) IsInstallable() bool {
2504 return Bool(j.properties.Installable)
2505}
2506
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002507var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002508
Colin Cross1b16b0e2019-02-12 14:41:32 -08002509// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
2510//
2511// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
2512// compiled against an Android classpath.
2513//
2514// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
2515// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07002516func ImportFactory() android.Module {
2517 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07002518
Liz Kammerd6c31d22020-08-05 15:40:41 -07002519 module.AddProperties(
2520 &module.properties,
2521 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08002522 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07002523 )
Colin Cross74d73e22017-08-02 11:05:49 -07002524
Paul Duffin71b33cc2021-06-23 11:39:47 +01002525 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01002526
Liz Kammerd6c31d22020-08-05 15:40:41 -07002527 module.dexProperties.Optimize.EnabledByDefault = false
2528
Colin Cross74d73e22017-08-02 11:05:49 -07002529 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002530 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002531 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07002532 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002533}
2534
Colin Cross1b16b0e2019-02-12 14:41:32 -08002535// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
2536// module.
2537//
2538// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
2539// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07002540func ImportFactoryHost() android.Module {
2541 module := &Import{}
2542
2543 module.AddProperties(&module.properties)
2544
2545 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002546 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002547 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07002548 return module
2549}
2550
Colin Cross42be7612019-02-21 18:12:14 -08002551// dex_import module
2552
2553type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07002554 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09002555
2556 // set the name of the output
2557 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08002558}
2559
2560type DexImport struct {
2561 android.ModuleBase
2562 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002563 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08002564 prebuilt android.Prebuilt
2565
2566 properties DexImportProperties
2567
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002568 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08002569
2570 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07002571
2572 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08002573}
2574
2575func (j *DexImport) Prebuilt() *android.Prebuilt {
2576 return &j.prebuilt
2577}
2578
2579func (j *DexImport) PrebuiltSrcs() []string {
2580 return j.properties.Jars
2581}
2582
2583func (j *DexImport) Name() string {
2584 return j.prebuilt.Name(j.ModuleBase.Name())
2585}
2586
Jiyong Park0b238752019-10-29 11:23:10 +09002587func (j *DexImport) Stem() string {
2588 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2589}
2590
Jiyong Park77acec62020-06-01 21:39:15 +09002591func (a *DexImport) JacocoReportClassesFile() android.Path {
2592 return nil
2593}
2594
Colin Cross08dca382020-07-21 20:31:17 -07002595func (a *DexImport) LintDepSets() LintDepSets {
2596 return LintDepSets{}
2597}
2598
Martin Stjernholm6d415272020-01-31 17:10:36 +00002599func (j *DexImport) IsInstallable() bool {
2600 return true
2601}
2602
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002603func (j *DexImport) getStrictUpdatabilityLinting() bool {
2604 return false
2605}
2606
2607func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2608}
2609
Colin Cross42be7612019-02-21 18:12:14 -08002610func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2611 if len(j.properties.Jars) != 1 {
2612 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2613 }
2614
Colin Crossff694a82023-12-13 15:54:49 -08002615 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07002616 if !apexInfo.IsForPlatform() {
2617 j.hideApexVariantFromMake = true
2618 }
2619
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002620 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
Spandan Dase21a8d42024-01-23 23:56:29 +00002621 ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
2622 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), &j.dexpreopter)
Colin Cross42be7612019-02-21 18:12:14 -08002623
2624 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2625 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2626
2627 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002628 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002629
2630 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2631 rule.Temporary(temporary)
2632
2633 // use zip2zip to uncompress classes*.dex files
2634 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002635 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002636 FlagWithInput("-i ", inputJar).
2637 FlagWithOutput("-o ", temporary).
2638 FlagWithArg("-0 ", "'classes*.dex'")
2639
2640 // use zipalign to align uncompressed classes*.dex files
2641 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002642 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002643 Flag("-f").
2644 Text("4").
2645 Input(temporary).
2646 Output(dexOutputFile)
2647
2648 rule.DeleteTemporaryFiles()
2649
Colin Crossf1a035e2020-11-16 17:32:30 -08002650 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002651 } else {
2652 ctx.Build(pctx, android.BuildParams{
2653 Rule: android.Cp,
2654 Input: inputJar,
2655 Output: dexOutputFile,
2656 })
2657 }
2658
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002659 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002660
Spandan Dase21a8d42024-01-23 23:56:29 +00002661 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002662
Colin Cross56a83212020-09-15 18:30:11 -07002663 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002664 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2665 j.Stem()+".jar", dexOutputFile)
2666 }
Colin Cross42be7612019-02-21 18:12:14 -08002667}
2668
Spandan Das59a4a2b2024-01-09 21:35:56 +00002669func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002670 return j.dexJarFile
2671}
2672
Jiyong Park45bf82e2020-12-15 22:29:02 +09002673var _ android.ApexModule = (*DexImport)(nil)
2674
2675// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002676func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2677 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002678 // we don't check prebuilt modules for sdk_version
2679 return nil
2680}
2681
Colin Cross42be7612019-02-21 18:12:14 -08002682// dex_import imports a `.jar` file containing classes.dex files.
2683//
2684// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2685// to the device.
2686func DexImportFactory() android.Module {
2687 module := &DexImport{}
2688
2689 module.AddProperties(&module.properties)
2690
2691 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002692 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002693 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002694 return module
2695}
2696
Colin Cross89536d42017-07-07 14:35:50 -07002697// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002698type Defaults struct {
2699 android.ModuleBase
2700 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002701 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002702}
2703
Colin Cross1b16b0e2019-02-12 14:41:32 -08002704// java_defaults provides a set of properties that can be inherited by other java or android modules.
2705//
2706// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2707// property in the defaults module that exists in the depending module will be prepended to the depending module's
2708// value for that property.
2709//
2710// Example:
2711//
Sam Delmerico277795c2022-02-25 17:04:37 +00002712// java_defaults {
2713// name: "example_defaults",
2714// srcs: ["common/**/*.java"],
2715// javacflags: ["-Xlint:all"],
2716// aaptflags: ["--auto-add-overlay"],
2717// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002718//
Sam Delmerico277795c2022-02-25 17:04:37 +00002719// java_library {
2720// name: "example",
2721// defaults: ["example_defaults"],
2722// srcs: ["example/**/*.java"],
2723// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002724//
2725// is functionally identical to:
2726//
Sam Delmerico277795c2022-02-25 17:04:37 +00002727// java_library {
2728// name: "example",
2729// srcs: [
2730// "common/**/*.java",
2731// "example/**/*.java",
2732// ],
2733// javacflags: ["-Xlint:all"],
2734// }
Paul Duffin47357662019-12-05 14:07:14 +00002735func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002736 module := &Defaults{}
2737
Colin Cross89536d42017-07-07 14:35:50 -07002738 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002739 &CommonProperties{},
2740 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002741 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002742 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002743 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002744 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002745 &aaptProperties{},
2746 &androidLibraryProperties{},
2747 &appProperties{},
2748 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002749 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00002750 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002751 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002752 &ImportProperties{},
2753 &AARImportProperties{},
2754 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002755 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002756 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002757 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002758 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002759 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002760 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00002761 &JavaApiLibraryProperties{},
Jihoon Kang9272dcc2024-01-12 00:08:30 +00002762 &bootclasspathFragmentProperties{},
2763 &SourceOnlyBootclasspathProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002764 )
2765
2766 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002767 return module
2768}
Nan Zhangea568a42017-11-08 21:20:04 -08002769
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002770func kytheExtractJavaFactory() android.Singleton {
2771 return &kytheExtractJavaSingleton{}
2772}
2773
2774type kytheExtractJavaSingleton struct {
2775}
2776
2777func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2778 var xrefTargets android.Paths
2779 ctx.VisitAllModules(func(module android.Module) {
2780 if javaModule, ok := module.(xref); ok {
2781 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2782 }
2783 })
2784 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2785 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002786 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002787 }
2788}
2789
Nan Zhangea568a42017-11-08 21:20:04 -08002790var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002791var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002792var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04002793var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002794
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002795// Add class loader context (CLC) of a given dependency to the current CLC.
2796func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2797 clcMap dexpreopt.ClassLoaderContextMap) {
2798
2799 dep, ok := depModule.(UsesLibraryDependency)
2800 if !ok {
2801 return
2802 }
2803
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002804 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2805
2806 var sdkLib *string
2807 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2808 // A shared SDK library. This should be added as a top-level CLC element.
2809 sdkLib = &depName
2810 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2811 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2812 // property. This should be handled in the same way as a shared SDK library.
2813 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002814 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002815
2816 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002817 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002818 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002819 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2820 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002821 } else if depTag == staticLibTag {
2822 // Propagate <uses-library> through static library dependencies, unless it is a component
2823 // library (such as stubs). Component libraries have a dependency on their SDK library,
2824 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002825 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002826 return
2827 }
2828 } else {
2829 // Don't propagate <uses-library> for other dependency tags.
2830 return
2831 }
2832
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002833 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2834 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2835 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2836 // from its CLC should be added to the current CLC.
2837 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002838 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Spandan Das59a4a2b2024-01-09 21:35:56 +00002839 dep.DexJarBuildPath(ctx).PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002840 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002841 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2842 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002843}
Wei Libafb6d62021-12-10 03:14:59 -08002844
Jihoon Kangfdf32362023-09-12 00:36:43 +00002845type JavaApiContributionImport struct {
2846 JavaApiContribution
2847
Spandan Das23956d12024-01-19 00:22:22 +00002848 prebuilt android.Prebuilt
2849 prebuiltProperties javaApiContributionImportProperties
2850}
2851
2852type javaApiContributionImportProperties struct {
2853 // Name of the source soong module that gets shadowed by this prebuilt
2854 // If unspecified, follows the naming convention that the source module of
2855 // the prebuilt is Name() without "prebuilt_" prefix
2856 Source_module_name *string
2857
2858 // Non-nil if this java_import module was dynamically created by a java_sdk_library_import
2859 // The name is the undecorated name of the java_sdk_library as it appears in the blueprint file
2860 // (without any prebuilt_ prefix)
2861 Created_by_java_sdk_library_name *string `blueprint:"mutated"`
Jihoon Kangfdf32362023-09-12 00:36:43 +00002862}
2863
2864func ApiContributionImportFactory() android.Module {
2865 module := &JavaApiContributionImport{}
2866 android.InitAndroidModule(module)
2867 android.InitDefaultableModule(module)
2868 android.InitPrebuiltModule(module, &[]string{""})
Spandan Das23956d12024-01-19 00:22:22 +00002869 module.AddProperties(&module.properties, &module.prebuiltProperties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002870 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00002871 return module
2872}
2873
2874func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
2875 return &module.prebuilt
2876}
2877
2878func (module *JavaApiContributionImport) Name() string {
2879 return module.prebuilt.Name(module.ModuleBase.Name())
2880}
2881
Spandan Das23956d12024-01-19 00:22:22 +00002882func (j *JavaApiContributionImport) BaseModuleName() string {
2883 return proptools.StringDefault(j.prebuiltProperties.Source_module_name, j.ModuleBase.Name())
2884}
2885
2886func (j *JavaApiContributionImport) CreatedByJavaSdkLibraryName() *string {
2887 return j.prebuiltProperties.Created_by_java_sdk_library_name
2888}
2889
Jihoon Kangfdf32362023-09-12 00:36:43 +00002890func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2891 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
2892}