blob: 807aea97dbd542a8be4f8abad37d283e8dd516e4 [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
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500251 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700252 TransitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500253
254 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -0700255 TransitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500256
Colin Crossdcf71b22021-02-01 13:59:03 -0800257 // ImplementationAndResourceJars is a list of jars that contain the implementations of classes
258 // in the module as well as any resources included in the module.
259 ImplementationAndResourcesJars android.Paths
260
261 // ImplementationJars is a list of jars that contain the implementations of classes in the
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000262 //module.
Colin Crossdcf71b22021-02-01 13:59:03 -0800263 ImplementationJars android.Paths
264
265 // ResourceJars is a list of jars that contain the resources included in the module.
266 ResourceJars android.Paths
267
268 // AidlIncludeDirs is a list of directories that should be passed to the aidl tool when
269 // depending on this module.
270 AidlIncludeDirs android.Paths
271
272 // SrcJarArgs is a list of arguments to pass to soong_zip to package the sources of this
273 // module.
274 SrcJarArgs []string
275
276 // SrcJarDeps is a list of paths to depend on when packaging the sources of this module.
277 SrcJarDeps android.Paths
278
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000279 // The source files of this module and all its transitive static dependencies.
280 TransitiveSrcFiles *android.DepSet[android.Path]
281
Colin Crossdcf71b22021-02-01 13:59:03 -0800282 // ExportedPlugins is a list of paths that should be used as annotation processors for any
283 // module that depends on this module.
284 ExportedPlugins android.Paths
285
286 // ExportedPluginClasses is a list of classes that should be run as annotation processors for
287 // any module that depends on this module.
288 ExportedPluginClasses []string
289
290 // ExportedPluginDisableTurbine is true if this module's annotation processors generate APIs,
291 // requiring disbling turbine for any modules that depend on it.
292 ExportedPluginDisableTurbine bool
293
294 // JacocoReportClassesFile is the path to a jar containing uninstrumented classes that will be
295 // instrumented by jacoco.
296 JacocoReportClassesFile android.Path
297}
298
Colin Crossbc7d76c2023-12-12 16:39:03 -0800299var JavaInfoProvider = blueprint.NewProvider[JavaInfo]()
Colin Crossdcf71b22021-02-01 13:59:03 -0800300
Colin Cross75ce9ec2021-02-26 16:20:32 -0800301// SyspropPublicStubInfo contains info about the sysprop public stub library that corresponds to
302// the sysprop implementation library.
303type SyspropPublicStubInfo struct {
304 // JavaInfo is the JavaInfoProvider of the sysprop public stub library that corresponds to
305 // the sysprop implementation library.
306 JavaInfo JavaInfo
307}
308
Colin Crossbc7d76c2023-12-12 16:39:03 -0800309var SyspropPublicStubInfoProvider = blueprint.NewProvider[SyspropPublicStubInfo]()
Colin Cross75ce9ec2021-02-26 16:20:32 -0800310
Paul Duffin44b481b2020-06-17 16:59:43 +0100311// Methods that need to be implemented for a module that is added to apex java_libs property.
312type ApexDependency interface {
Nan Zhanged19fc32017-10-19 13:06:22 -0700313 HeaderJars() android.Paths
Paul Duffin44b481b2020-06-17 16:59:43 +0100314 ImplementationAndResourcesJars() android.Paths
315}
316
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100317// Provides build path and install path to DEX jars.
318type UsesLibraryDependency interface {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000319 DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +0100320 DexJarInstallPath() android.Path
Ulya Trafimovichdbf31662020-12-17 12:07:54 +0000321 ClassLoaderContexts() dexpreopt.ClassLoaderContextMap
Ulya Trafimovich31e444e2020-08-14 17:32:16 +0100322}
323
Jaewoong Jung26342642021-03-17 15:56:23 -0700324// TODO(jungjw): Move this to kythe.go once it's created.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800325type xref interface {
326 XrefJavaFiles() android.Paths
327}
328
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800329func (j *Module) XrefJavaFiles() android.Paths {
330 return j.kytheFiles
331}
332
Colin Crossbe1da472017-07-07 15:59:46 -0700333type dependencyTag struct {
334 blueprint.BaseDependencyTag
335 name string
Colin Cross65cb3142021-12-10 23:05:02 +0000336
337 // True if the dependency is relinked at runtime.
338 runtimeLinked bool
Colin Crossce564252022-01-12 11:13:32 -0800339
340 // True if the dependency is a toolchain, for example an annotation processor.
341 toolchain bool
Colin Cross2fe66872015-03-30 17:20:39 -0700342}
343
Colin Crosse9fe2942020-11-10 18:12:15 -0800344// installDependencyTag is a dependency tag that is annotated to cause the installed files of the
345// dependency to be installed when the parent module is installed.
346type installDependencyTag struct {
347 blueprint.BaseDependencyTag
348 android.InstallAlwaysNeededDependencyTag
349 name string
350}
351
Colin Cross65cb3142021-12-10 23:05:02 +0000352func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
353 if d.runtimeLinked {
354 return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
Colin Crossce564252022-01-12 11:13:32 -0800355 } else if d.toolchain {
356 return []android.LicenseAnnotation{android.LicenseAnnotationToolchain}
Colin Cross65cb3142021-12-10 23:05:02 +0000357 }
358 return nil
359}
360
361var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
362
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100363type usesLibraryDependencyTag struct {
364 dependencyTag
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100365 sdkVersion int // SDK version in which the library appared as a standalone library.
366 optional bool // If the dependency is optional or required.
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100367}
368
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100369func makeUsesLibraryDependencyTag(sdkVersion int, optional bool) usesLibraryDependencyTag {
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100370 return usesLibraryDependencyTag{
Colin Cross65cb3142021-12-10 23:05:02 +0000371 dependencyTag: dependencyTag{
372 name: fmt.Sprintf("uses-library-%d", sdkVersion),
373 runtimeLinked: true,
374 },
375 sdkVersion: sdkVersion,
376 optional: optional,
Ulya Trafimovichb5218112020-10-07 15:11:32 +0100377 }
378}
379
Jiyong Park8be103b2019-11-08 15:53:48 +0900380func IsJniDepTag(depTag blueprint.DependencyTag) bool {
Colin Crossde78d132020-10-09 18:59:49 -0700381 return depTag == jniLibTag
Jiyong Park8be103b2019-11-08 15:53:48 +0900382}
383
Colin Crossbe1da472017-07-07 15:59:46 -0700384var (
Colin Cross75ce9ec2021-02-26 16:20:32 -0800385 dataNativeBinsTag = dependencyTag{name: "dataNativeBins"}
Sam Delmericob3342ce2022-01-20 21:10:28 +0000386 dataDeviceBinsTag = dependencyTag{name: "dataDeviceBins"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800387 staticLibTag = dependencyTag{name: "staticlib"}
Colin Cross65cb3142021-12-10 23:05:02 +0000388 libTag = dependencyTag{name: "javalib", runtimeLinked: true}
Liz Kammeref28a4c2022-09-23 16:50:56 -0400389 sdkLibTag = dependencyTag{name: "sdklib", runtimeLinked: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000390 java9LibTag = dependencyTag{name: "java9lib", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800391 pluginTag = dependencyTag{name: "plugin", toolchain: true}
392 errorpronePluginTag = dependencyTag{name: "errorprone-plugin", toolchain: true}
393 exportedPluginTag = dependencyTag{name: "exported-plugin", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000394 bootClasspathTag = dependencyTag{name: "bootclasspath", runtimeLinked: true}
395 systemModulesTag = dependencyTag{name: "system modules", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800396 frameworkResTag = dependencyTag{name: "framework-res"}
Colin Cross65cb3142021-12-10 23:05:02 +0000397 kotlinStdlibTag = dependencyTag{name: "kotlin-stdlib", runtimeLinked: true}
398 kotlinAnnotationsTag = dependencyTag{name: "kotlin-annotations", runtimeLinked: true}
Colin Crossce564252022-01-12 11:13:32 -0800399 kotlinPluginTag = dependencyTag{name: "kotlin-plugin", toolchain: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800400 proguardRaiseTag = dependencyTag{name: "proguard-raise"}
401 certificateTag = dependencyTag{name: "certificate"}
402 instrumentationForTag = dependencyTag{name: "instrumentation_for"}
Colin Crossce564252022-01-12 11:13:32 -0800403 extraLintCheckTag = dependencyTag{name: "extra-lint-check", toolchain: true}
Colin Cross65cb3142021-12-10 23:05:02 +0000404 jniLibTag = dependencyTag{name: "jnilib", runtimeLinked: true}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -0500405 r8LibraryJarTag = dependencyTag{name: "r8-libraryjar", runtimeLinked: true}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800406 syspropPublicStubDepTag = dependencyTag{name: "sysprop public stub"}
Jihoon Kang01e522c2023-03-14 01:09:34 +0000407 javaApiContributionTag = dependencyTag{name: "java-api-contribution"}
408 depApiSrcsTag = dependencyTag{name: "dep-api-srcs"}
Jihoon Kang84b25892023-12-01 22:01:06 +0000409 aconfigDeclarationTag = dependencyTag{name: "aconfig-declaration"}
Colin Cross75ce9ec2021-02-26 16:20:32 -0800410 jniInstallTag = installDependencyTag{name: "jni install"}
411 binaryInstallTag = installDependencyTag{name: "binary install"}
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100412 usesLibReqTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, false)
413 usesLibOptTag = makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, true)
414 usesLibCompat28OptTag = makeUsesLibraryDependencyTag(28, true)
415 usesLibCompat29ReqTag = makeUsesLibraryDependencyTag(29, false)
416 usesLibCompat30OptTag = makeUsesLibraryDependencyTag(30, true)
Colin Crossbe1da472017-07-07 15:59:46 -0700417)
Colin Cross2fe66872015-03-30 17:20:39 -0700418
Jiyong Park83dc74b2020-01-14 18:38:44 +0900419func IsLibDepTag(depTag blueprint.DependencyTag) bool {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400420 return depTag == libTag || depTag == sdkLibTag
Jiyong Park83dc74b2020-01-14 18:38:44 +0900421}
422
423func IsStaticLibDepTag(depTag blueprint.DependencyTag) bool {
424 return depTag == staticLibTag
425}
426
Colin Crossfc3674a2017-09-18 17:41:52 -0700427type sdkDep struct {
Pete Gilline3d44b22020-06-29 11:28:51 +0100428 useModule, useFiles, invalidVersion bool
Colin Cross47ff2522017-10-02 14:22:08 -0700429
Colin Cross6cef4812019-10-17 14:23:50 -0700430 // The modules that will be added to the bootclasspath when targeting 1.8 or lower
431 bootclasspath []string
Paul Duffine25c6442019-10-11 13:50:28 +0100432
433 // The default system modules to use. Will be an empty string if no system
434 // modules are to be used.
Colin Cross1369cdb2017-09-29 17:58:17 -0700435 systemModules string
436
Pete Gilline3d44b22020-06-29 11:28:51 +0100437 // The modules that will be added to the classpath regardless of the Java language level targeted
438 classpath []string
439
Colin Cross6cef4812019-10-17 14:23:50 -0700440 // The modules that will be added ot the classpath when targeting 1.9 or higher
Pete Gilline3d44b22020-06-29 11:28:51 +0100441 // (normally these will be on the bootclasspath when targeting 1.8 or lower)
Colin Cross6cef4812019-10-17 14:23:50 -0700442 java9Classpath []string
443
Colin Crossa97c5d32018-03-28 14:58:31 -0700444 frameworkResModule string
445
Colin Cross86a60ae2018-05-29 14:44:55 -0700446 jars android.Paths
Colin Cross3047fa22019-04-18 10:56:44 -0700447 aidl android.OptionalPath
Paul Duffin250e6192019-06-07 10:44:37 +0100448
449 noStandardLibs, noFrameworksLibs bool
450}
451
452func (s sdkDep) hasStandardLibs() bool {
453 return !s.noStandardLibs
454}
455
456func (s sdkDep) hasFrameworkLibs() bool {
457 return !s.noStandardLibs && !s.noFrameworksLibs
Colin Cross1369cdb2017-09-29 17:58:17 -0700458}
459
Colin Crossa4f08812018-10-02 22:03:40 -0700460type jniLib struct {
Colin Cross403cc152020-07-06 14:15:24 -0700461 name string
462 path android.Path
463 target android.Target
464 coverageFile android.OptionalPath
465 unstrippedFile android.Path
Jihoon Kangf78a8902022-09-01 22:47:07 +0000466 partition string
Colin Crossa4f08812018-10-02 22:03:40 -0700467}
468
Jiyong Parkf1691d22021-03-29 20:11:58 +0900469func sdkDeps(ctx android.BottomUpMutatorContext, sdkContext android.SdkContext, d dexer) {
Liz Kammerd6c31d22020-08-05 15:40:41 -0700470 sdkDep := decodeSdkDep(ctx, sdkContext)
471 if sdkDep.useModule {
472 ctx.AddVariationDependencies(nil, bootClasspathTag, sdkDep.bootclasspath...)
473 ctx.AddVariationDependencies(nil, java9LibTag, sdkDep.java9Classpath...)
Liz Kammeref28a4c2022-09-23 16:50:56 -0400474 ctx.AddVariationDependencies(nil, sdkLibTag, sdkDep.classpath...)
Liz Kammerd6c31d22020-08-05 15:40:41 -0700475 if d.effectiveOptimizeEnabled() && sdkDep.hasStandardLibs() {
Jihoon Kangb5078312023-03-29 23:25:49 +0000476 ctx.AddVariationDependencies(nil, proguardRaiseTag,
Jihoon Kang6c0df882023-06-14 22:43:25 +0000477 config.LegacyCorePlatformBootclasspathLibraries...,
Jihoon Kangb5078312023-03-29 23:25:49 +0000478 )
Liz Kammerd6c31d22020-08-05 15:40:41 -0700479 }
480 if d.effectiveOptimizeEnabled() && sdkDep.hasFrameworkLibs() {
481 ctx.AddVariationDependencies(nil, proguardRaiseTag, config.FrameworkLibraries...)
482 }
483 }
484 if sdkDep.systemModules != "" {
485 ctx.AddVariationDependencies(nil, systemModulesTag, sdkDep.systemModules)
486 }
487}
488
Colin Cross32f676a2017-09-06 13:41:06 -0700489type deps struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700490 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
491 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
492 // systemModules and java9Classpath instead.
493 bootClasspath classpath
494
495 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
496 // contains header jars for all static and non-static dependencies.
497 classpath classpath
498
499 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
500 // header jars for all non-static dependencies. Static dependencies have already been
501 // combined into the program jar.
502 dexClasspath classpath
503
504 // java9Classpath is the list of jars that will be added to the classpath when targeting
505 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
506 // are provided by systemModules.
507 java9Classpath classpath
508
Colin Cross748b2d82020-11-19 13:52:06 -0800509 processorPath classpath
510 errorProneProcessorPath classpath
511 processorClasses []string
512 staticJars android.Paths
513 staticHeaderJars android.Paths
514 staticResourceJars android.Paths
515 aidlIncludeDirs android.Paths
516 srcs android.Paths
517 srcJars android.Paths
518 systemModules *systemModules
519 aidlPreprocess android.OptionalPath
520 kotlinStdlib android.Paths
521 kotlinAnnotations android.Paths
Colin Crossa1ff7c62021-09-17 14:11:52 -0700522 kotlinPlugins android.Paths
Jihoon Kang6592e872023-12-19 01:13:16 +0000523 aconfigProtoFiles android.Paths
Colin Crossbe9cdb82019-01-21 21:37:16 -0800524
525 disableTurbine bool
Colin Cross32f676a2017-09-06 13:41:06 -0700526}
Colin Cross2fe66872015-03-30 17:20:39 -0700527
Colin Cross54250902017-12-05 09:28:08 -0800528func checkProducesJars(ctx android.ModuleContext, dep android.SourceFileProducer) {
529 for _, f := range dep.Srcs() {
530 if f.Ext() != ".jar" {
531 ctx.ModuleErrorf("genrule %q must generate files ending with .jar to be used as a libs or static_libs dependency",
532 ctx.OtherModuleName(dep.(blueprint.Module)))
533 }
534 }
535}
536
Jiyong Parkf1691d22021-03-29 20:11:58 +0900537func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext android.SdkContext) javaVersion {
Nan Zhang357466b2018-04-17 17:38:36 -0700538 if javaVersion != "" {
Colin Cross1e743852019-10-28 11:37:20 -0700539 return normalizeJavaVersion(ctx, javaVersion)
Colin Cross17dec172020-05-14 18:05:32 -0700540 } else if ctx.Device() {
Jiyong Park92315372021-04-02 08:45:46 +0900541 return defaultJavaLanguageVersion(ctx, sdkContext.SdkVersion(ctx))
Sorin Basca384250c2023-02-02 17:56:19 +0000542 } else {
Sorin Bascabe302732023-02-15 17:52:27 +0000543 return JAVA_VERSION_17
Nan Zhang357466b2018-04-17 17:38:36 -0700544 }
Nan Zhang357466b2018-04-17 17:38:36 -0700545}
546
Jihoon Kangff878bf2022-12-22 21:26:06 +0000547// Java version for stubs generation
548func getStubsJavaVersion() javaVersion {
549 return JAVA_VERSION_8
550}
551
Colin Cross1e743852019-10-28 11:37:20 -0700552type javaVersion int
553
554const (
555 JAVA_VERSION_UNSUPPORTED = 0
556 JAVA_VERSION_6 = 6
557 JAVA_VERSION_7 = 7
558 JAVA_VERSION_8 = 8
559 JAVA_VERSION_9 = 9
Sorin Bascac0244da2021-11-26 17:26:33 +0000560 JAVA_VERSION_11 = 11
Sorin Bascace720c32022-05-24 12:13:50 +0100561 JAVA_VERSION_17 = 17
Colin Cross1e743852019-10-28 11:37:20 -0700562)
563
564func (v javaVersion) String() string {
565 switch v {
566 case JAVA_VERSION_6:
567 return "1.6"
568 case JAVA_VERSION_7:
569 return "1.7"
570 case JAVA_VERSION_8:
571 return "1.8"
572 case JAVA_VERSION_9:
573 return "1.9"
Sorin Bascac0244da2021-11-26 17:26:33 +0000574 case JAVA_VERSION_11:
575 return "11"
Sorin Bascace720c32022-05-24 12:13:50 +0100576 case JAVA_VERSION_17:
577 return "17"
Colin Cross1e743852019-10-28 11:37:20 -0700578 default:
579 return "unsupported"
580 }
581}
582
Cole Faustd96eebf2022-06-28 14:41:27 -0700583func (v javaVersion) StringForKotlinc() string {
584 // $ ./external/kotlinc/bin/kotlinc -jvm-target foo
585 // error: unknown JVM target version: foo
586 // Supported versions: 1.6, 1.8, 9, 10, 11, 12, 13, 14, 15, 16, 17
587 switch v {
588 case JAVA_VERSION_7:
589 return "1.6"
590 case JAVA_VERSION_9:
591 return "9"
592 default:
593 return v.String()
594 }
595}
596
Colin Cross1e743852019-10-28 11:37:20 -0700597// Returns true if javac targeting this version uses system modules instead of a bootclasspath.
598func (v javaVersion) usesJavaModules() bool {
599 return v >= 9
600}
601
602func normalizeJavaVersion(ctx android.BaseModuleContext, javaVersion string) javaVersion {
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100603 switch javaVersion {
604 case "1.6", "6":
Colin Cross1e743852019-10-28 11:37:20 -0700605 return JAVA_VERSION_6
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100606 case "1.7", "7":
Colin Cross1e743852019-10-28 11:37:20 -0700607 return JAVA_VERSION_7
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100608 case "1.8", "8":
Colin Cross1e743852019-10-28 11:37:20 -0700609 return JAVA_VERSION_8
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100610 case "1.9", "9":
Colin Cross1e743852019-10-28 11:37:20 -0700611 return JAVA_VERSION_9
Sorin Bascac0244da2021-11-26 17:26:33 +0000612 case "11":
613 return JAVA_VERSION_11
Sorin Bascace720c32022-05-24 12:13:50 +0100614 case "17":
Sorin Basca5938fed2022-06-22 12:53:51 +0100615 return JAVA_VERSION_17
Sorin Bascace720c32022-05-24 12:13:50 +0100616 case "10", "12", "13", "14", "15", "16":
617 ctx.PropertyErrorf("java_version", "Java language level %s is not supported", javaVersion)
Colin Cross1e743852019-10-28 11:37:20 -0700618 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100619 default:
620 ctx.PropertyErrorf("java_version", "Unrecognized Java language level")
Colin Cross1e743852019-10-28 11:37:20 -0700621 return JAVA_VERSION_UNSUPPORTED
Pete Gillin4e8b48a2019-07-12 13:16:17 +0100622 }
623}
624
Colin Cross2fe66872015-03-30 17:20:39 -0700625//
626// Java libraries (.jar file)
627//
628
Colin Crossf506d872017-07-19 15:53:04 -0700629type Library struct {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700630 Module
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700631
Colin Cross312634e2023-11-21 15:13:56 -0800632 combinedExportedProguardFlagsFile android.Path
Jared Duke5979b302022-12-19 21:08:39 +0000633
Colin Cross09ad3a62023-11-15 12:29:33 -0800634 InstallMixin func(ctx android.ModuleContext, installPath android.Path) (extraInstallDeps android.InstallPaths)
Colin Cross2fe66872015-03-30 17:20:39 -0700635}
636
Jiyong Park45bf82e2020-12-15 22:29:02 +0900637var _ android.ApexModule = (*Library)(nil)
638
satayevd604b212021-07-21 14:23:52 +0100639// Provides access to the list of permitted packages from apex boot jars.
Paul Duffine739f1e2020-05-29 11:24:51 +0100640type PermittedPackagesForUpdatableBootJars interface {
641 PermittedPackagesForUpdatableBootJars() []string
642}
643
644var _ PermittedPackagesForUpdatableBootJars = (*Library)(nil)
645
646func (j *Library) PermittedPackagesForUpdatableBootJars() []string {
647 return j.properties.Permitted_packages
648}
649
Colin Cross42be7612019-02-21 18:12:14 -0800650func shouldUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter) bool {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000651 // Store uncompressed (and aligned) any dex files from jars in APEXes.
Colin Crossff694a82023-12-13 15:54:49 -0800652 if apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider); !apexInfo.IsForPlatform() {
Ulya Trafimovichf491dde2020-01-24 12:19:45 +0000653 return true
654 }
655
Nicolas Geoffrayfa6e9ec2019-02-12 13:12:16 +0000656 // Store uncompressed (and do not strip) dex files from boot class path jars.
657 if inList(ctx.ModuleName(), ctx.Config().BootJars()) {
658 return true
659 }
660
661 // Store uncompressed dex files that are preopted on /system.
Jiakai Zhang519c5c82021-09-16 06:15:39 +0000662 if !dexpreopter.dexpreoptDisabled(ctx) && (ctx.Host() || !dexpreopter.odexOnSystemOther(ctx, dexpreopter.installPath)) {
Vladimir Markoe8b00d62018-12-21 15:54:16 +0000663 return true
664 }
Colin Cross083a2aa2019-02-06 16:37:12 -0800665 if ctx.Config().UncompressPrivAppDex() &&
666 inList(ctx.ModuleName(), ctx.Config().ModulesLoadedByPrivilegedModules()) {
667 return true
668 }
669
Colin Cross2fc72f62018-12-21 12:59:54 -0800670 return false
671}
672
Jiakai Zhang22450f22021-10-11 03:05:20 +0000673// Sets `dexer.dexProperties.Uncompress_dex` to the proper value.
674func setUncompressDex(ctx android.ModuleContext, dexpreopter *dexpreopter, dexer *dexer) {
675 if dexer.dexProperties.Uncompress_dex == nil {
676 // If the value was not force-set by the user, use reasonable default based on the module.
677 dexer.dexProperties.Uncompress_dex = proptools.BoolPtr(shouldUncompressDex(ctx, dexpreopter))
678 }
679}
680
Colin Crossf506d872017-07-19 15:53:04 -0700681func (j *Library) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000682
683 j.provideHiddenAPIPropertyInfo(ctx)
684
Jiyong Park92315372021-04-02 08:45:46 +0900685 j.sdkVersion = j.SdkVersion(ctx)
686 j.minSdkVersion = j.MinSdkVersion(ctx)
satayev0a420e72021-11-29 17:25:52 +0000687 j.maxSdkVersion = j.MaxSdkVersion(ctx)
Jiyong Park92315372021-04-02 08:45:46 +0900688
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000689 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
690
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000691 proguardSpecInfo := j.collectProguardSpecInfo(ctx)
Colin Cross40213022023-12-13 15:19:49 -0800692 android.SetProvider(ctx, ProguardSpecInfoProvider, proguardSpecInfo)
Colin Cross312634e2023-11-21 15:13:56 -0800693 exportedProguardFlagsFiles := proguardSpecInfo.ProguardFlagsFiles.ToList()
694 j.extraProguardFlagsFiles = append(j.extraProguardFlagsFiles, exportedProguardFlagsFiles...)
695
696 combinedExportedProguardFlagFile := android.PathForModuleOut(ctx, "export_proguard_flags")
697 writeCombinedProguardFlagsFile(ctx, combinedExportedProguardFlagFile, exportedProguardFlagsFiles)
698 j.combinedExportedProguardFlagsFile = combinedExportedProguardFlagFile
Sam Delmericoc8e040c2023-10-31 17:27:02 +0000699
Colin Crossff694a82023-12-13 15:54:49 -0800700 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -0700701 if !apexInfo.IsForPlatform() {
702 j.hideApexVariantFromMake = true
703 }
704
Artur Satayev2db1c3f2020-04-08 19:09:30 +0100705 j.checkSdkVersions(ctx)
Mark Whitea15790a2023-08-22 21:28:11 +0000706 j.checkHeadersOnly(ctx)
Colin Cross61df14a2021-12-01 13:04:46 -0800707 if ctx.Device() {
708 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
709 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
710 j.dexpreopter.isSDKLibrary = j.deviceProperties.IsSDKLibrary
711 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
712 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
713 j.classLoaderContexts = j.usesLibrary.classLoaderContextForUsesLibDeps(ctx)
714 }
Colin Cross4eae06d2023-06-20 22:40:02 -0700715 j.compile(ctx, nil, nil, nil)
Colin Crossb7a63242015-04-16 14:09:14 -0700716
Colin Cross56a83212020-09-15 18:30:11 -0700717 exclusivelyForApex := !apexInfo.IsForPlatform()
Jiyong Park7f7766d2019-07-25 22:02:35 +0900718 if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
Colin Cross09ad3a62023-11-15 12:29:33 -0800719 var extraInstallDeps android.InstallPaths
Colin Crossf0f2e2c2019-10-15 16:36:40 -0700720 if j.InstallMixin != nil {
721 extraInstallDeps = j.InstallMixin(ctx, j.outputFile)
722 }
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700723 hostDexNeeded := Bool(j.deviceProperties.Hostdex) && !ctx.Host()
724 if hostDexNeeded {
Colin Cross3108ce12021-11-10 14:38:50 -0800725 j.hostdexInstallFile = ctx.InstallFile(
726 android.PathForHostDexInstall(ctx, "framework"),
Colin Cross1d0eb7a2021-11-03 14:08:20 -0700727 j.Stem()+"-hostdex.jar", j.outputFile)
728 }
729 var installDir android.InstallPath
730 if ctx.InstallInTestcases() {
731 var archDir string
732 if !ctx.Host() {
733 archDir = ctx.DeviceConfig().DeviceArch()
734 }
735 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
736 } else {
737 installDir = android.PathForModuleInstall(ctx, "framework")
738 }
739 j.installFile = ctx.InstallFile(installDir, j.Stem()+".jar", j.outputFile, extraInstallDeps...)
Colin Cross2c429dc2017-08-31 16:45:16 -0700740 }
Colin Crossb7a63242015-04-16 14:09:14 -0700741}
742
Colin Crossf506d872017-07-19 15:53:04 -0700743func (j *Library) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross46c9b8b2017-06-22 16:51:17 -0700744 j.deps(ctx)
Ulya Trafimoviche4432872021-08-18 16:57:11 +0100745 j.usesLibrary.deps(ctx, false)
Colin Cross46c9b8b2017-06-22 16:51:17 -0700746}
747
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000748const (
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000749 aidlIncludeDir = "aidl"
750 javaDir = "java"
751 jarFileSuffix = ".jar"
752 testConfigSuffix = "-AndroidTest.xml"
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000753)
754
Paul Duffina0dbf432019-12-05 11:25:53 +0000755// path to the jar file of a java library. Relative to <sdk_root>/<api_dir>
Paul Duffin13648912022-07-15 13:12:35 +0000756func sdkSnapshotFilePathForJar(_ android.SdkMemberContext, osPrefix, name string) string {
Paul Duffina04c1072020-03-02 10:16:35 +0000757 return sdkSnapshotFilePathForMember(osPrefix, name, jarFileSuffix)
Paul Duffin1b82e6a2019-12-03 18:06:47 +0000758}
759
Paul Duffina04c1072020-03-02 10:16:35 +0000760func sdkSnapshotFilePathForMember(osPrefix, name string, suffix string) string {
761 return filepath.Join(javaDir, osPrefix, name+suffix)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000762}
763
Paul Duffin13879572019-11-28 14:31:38 +0000764type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +0000765 android.SdkMemberTypeBase
Paul Duffinf5c0a9c2020-02-28 14:39:53 +0000766
767 // Function to retrieve the appropriate output jar (implementation or header) from
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000768 // the library.
Paul Duffindb170e42020-12-08 17:48:25 +0000769 jarToExportGetter func(ctx android.SdkMemberContext, j *Library) android.Path
770
771 // Function to compute the snapshot relative path to which the named library's
772 // jar should be copied.
Paul Duffin13648912022-07-15 13:12:35 +0000773 snapshotPathGetter func(ctx android.SdkMemberContext, osPrefix, name string) string
Paul Duffindb170e42020-12-08 17:48:25 +0000774
775 // True if only the jar should be copied to the snapshot, false if the jar plus any additional
776 // files like aidl files should also be copied.
777 onlyCopyJarToSnapshot bool
Paul Duffin13879572019-11-28 14:31:38 +0000778}
779
Paul Duffindb170e42020-12-08 17:48:25 +0000780const (
781 onlyCopyJarToSnapshot = true
782 copyEverythingToSnapshot = false
783)
784
Paul Duffin296701e2021-07-14 10:29:36 +0100785func (mt *librarySdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
786 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin13879572019-11-28 14:31:38 +0000787}
788
789func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
790 _, ok := module.(*Library)
791 return ok
792}
793
Paul Duffin3a4eb502020-03-19 16:11:18 +0000794func (mt *librarySdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
795 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_import")
Paul Duffin14eb4672020-03-02 11:33:02 +0000796}
Paul Duffina0dbf432019-12-05 11:25:53 +0000797
Paul Duffin14eb4672020-03-02 11:33:02 +0000798func (mt *librarySdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
Paul Duffina551a1c2020-03-17 21:04:24 +0000799 return &librarySdkMemberProperties{}
Paul Duffin14eb4672020-03-02 11:33:02 +0000800}
801
802type librarySdkMemberProperties struct {
803 android.SdkMemberPropertiesBase
804
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000805 JarToExport android.Path `android:"arch_variant"`
Paul Duffina551a1c2020-03-17 21:04:24 +0000806 AidlIncludeDirs android.Paths
Paul Duffin869de142021-07-15 14:14:41 +0100807
808 // The list of permitted packages that need to be passed to the prebuilts as they are used to
809 // create the updatable-bcp-packages.txt file.
810 PermittedPackages []string
Paul Duffinbb638eb2022-11-26 13:36:38 +0000811
812 // The value of the min_sdk_version property, translated into a number where possible.
813 MinSdkVersion *string `supported_build_releases:"Tiramisu+"`
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800814
815 DexPreoptProfileGuided *bool `supported_build_releases:"UpsideDownCake+"`
Paul Duffin14eb4672020-03-02 11:33:02 +0000816}
817
Paul Duffin3a4eb502020-03-19 16:11:18 +0000818func (p *librarySdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000819 j := variant.(*Library)
820
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000821 p.JarToExport = ctx.MemberType().(*librarySdkMemberType).jarToExportGetter(ctx, j)
Paul Duffindb170e42020-12-08 17:48:25 +0000822
Paul Duffina551a1c2020-03-17 21:04:24 +0000823 p.AidlIncludeDirs = j.AidlIncludeDirs()
Paul Duffin869de142021-07-15 14:14:41 +0100824
825 p.PermittedPackages = j.PermittedPackagesForUpdatableBootJars()
Paul Duffinbb638eb2022-11-26 13:36:38 +0000826
827 // If the min_sdk_version was set then add the canonical representation of the API level to the
828 // snapshot.
829 if j.deviceProperties.Min_sdk_version != nil {
Cole Faust34867402023-04-28 12:32:27 -0700830 canonical, err := android.ReplaceFinalizedCodenames(ctx.SdkModuleContext().Config(), j.minSdkVersion.String())
831 if err != nil {
832 ctx.ModuleErrorf("%s", err)
833 }
Paul Duffinbb638eb2022-11-26 13:36:38 +0000834 p.MinSdkVersion = proptools.StringPtr(canonical)
835 }
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800836
837 if j.dexpreopter.dexpreoptProperties.Dex_preopt_result.Profile_guided {
838 p.DexPreoptProfileGuided = proptools.BoolPtr(true)
839 }
Paul Duffin14eb4672020-03-02 11:33:02 +0000840}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000841
Paul Duffin3a4eb502020-03-19 16:11:18 +0000842func (p *librarySdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +0000843 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +0000844
Paul Duffindb170e42020-12-08 17:48:25 +0000845 memberType := ctx.MemberType().(*librarySdkMemberType)
846
Paul Duffina551a1c2020-03-17 21:04:24 +0000847 exportedJar := p.JarToExport
848 if exportedJar != nil {
Paul Duffindb170e42020-12-08 17:48:25 +0000849 // Delegate the creation of the snapshot relative path to the member type.
Paul Duffin13648912022-07-15 13:12:35 +0000850 snapshotRelativeJavaLibPath := memberType.snapshotPathGetter(ctx, p.OsPrefix(), ctx.Name())
Paul Duffindb170e42020-12-08 17:48:25 +0000851
852 // Copy the exported jar to the snapshot.
Paul Duffin14eb4672020-03-02 11:33:02 +0000853 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
854
Paul Duffina551a1c2020-03-17 21:04:24 +0000855 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
856 }
857
Paul Duffinbb638eb2022-11-26 13:36:38 +0000858 if p.MinSdkVersion != nil {
859 propertySet.AddProperty("min_sdk_version", *p.MinSdkVersion)
860 }
861
Paul Duffin869de142021-07-15 14:14:41 +0100862 if len(p.PermittedPackages) > 0 {
863 propertySet.AddProperty("permitted_packages", p.PermittedPackages)
864 }
865
Jiakai Zhang9c4dc192023-02-09 00:09:24 +0800866 dexPreoptSet := propertySet.AddPropertySet("dex_preopt")
867 if p.DexPreoptProfileGuided != nil {
868 dexPreoptSet.AddProperty("profile_guided", proptools.Bool(p.DexPreoptProfileGuided))
869 }
870
Paul Duffindb170e42020-12-08 17:48:25 +0000871 // Do not copy anything else to the snapshot.
872 if memberType.onlyCopyJarToSnapshot {
873 return
874 }
875
Paul Duffina551a1c2020-03-17 21:04:24 +0000876 aidlIncludeDirs := p.AidlIncludeDirs
877 if len(aidlIncludeDirs) != 0 {
878 sdkModuleContext := ctx.SdkModuleContext()
879 for _, dir := range aidlIncludeDirs {
Paul Duffin14eb4672020-03-02 11:33:02 +0000880 // TODO(jiyong): copy parcelable declarations only
881 aidlFiles, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.aidl", nil)
882 for _, file := range aidlFiles {
883 builder.CopyToSnapshot(android.PathForSource(sdkModuleContext, file), filepath.Join(aidlIncludeDir, file))
884 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000885 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000886
Paul Duffina551a1c2020-03-17 21:04:24 +0000887 // TODO(b/151933053) - add aidl include dirs property
Paul Duffin14eb4672020-03-02 11:33:02 +0000888 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000889}
890
Colin Cross1b16b0e2019-02-12 14:41:32 -0800891// java_library builds and links sources into a `.jar` file for the device, and possibly for the host as well.
892//
893// By default, a java_library has a single variant that produces a `.jar` file containing `.class` files that were
894// compiled against the device bootclasspath. This jar is not suitable for installing on a device, but can be used
895// as a `static_libs` dependency of another module.
896//
897// Specifying `installable: true` will product a `.jar` file containing `classes.dex` files, suitable for installing on
898// a device.
899//
900// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
901// compiled against the host bootclasspath.
Colin Cross9ae1b922018-06-26 17:59:05 -0700902func LibraryFactory() android.Module {
903 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700904
Colin Crossce6734e2020-06-15 16:09:53 -0700905 module.addHostAndDeviceProperties()
Colin Cross2fe66872015-03-30 17:20:39 -0700906
Paul Duffin71b33cc2021-06-23 11:39:47 +0100907 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +0100908
Jiyong Park7f7766d2019-07-25 22:02:35 +0900909 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900910 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross9ae1b922018-06-26 17:59:05 -0700911 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700912}
913
Colin Cross1b16b0e2019-02-12 14:41:32 -0800914// java_library_static is an obsolete alias for java_library.
915func LibraryStaticFactory() android.Module {
916 return LibraryFactory()
917}
918
919// java_library_host builds and links sources into a `.jar` file for the host.
920//
921// A java_library_host has a single variant that produces a `.jar` file containing `.class` files that were
922// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -0700923func LibraryHostFactory() android.Module {
924 module := &Library{}
Colin Cross2fe66872015-03-30 17:20:39 -0700925
Colin Crossce6734e2020-06-15 16:09:53 -0700926 module.addHostProperties()
Colin Cross36242852017-06-23 15:06:31 -0700927
Colin Cross9ae1b922018-06-26 17:59:05 -0700928 module.Module.properties.Installable = proptools.BoolPtr(true)
929
Jiyong Park7f7766d2019-07-25 22:02:35 +0900930 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +0900931 InitJavaModule(module, android.HostSupported)
Colin Cross36242852017-06-23 15:06:31 -0700932 return module
Colin Cross2fe66872015-03-30 17:20:39 -0700933}
934
935//
Colin Crossb628ea52018-08-14 16:42:33 -0700936// Java Tests
Colin Cross05638fc2018-04-09 18:40:24 -0700937//
938
Dan Shi95d19422020-08-15 12:24:26 -0700939// Test option struct.
940type TestOptions struct {
Zhenhuang Wang0ac5a432022-08-12 18:49:20 +0800941 android.CommonTestOptions
942
Dan Shi95d19422020-08-15 12:24:26 -0700943 // a list of extra test configuration files that should be installed with the module.
944 Extra_test_configs []string `android:"path,arch_variant"`
Cole Faust21680542022-12-07 18:18:37 -0800945
946 // Extra <option> tags to add to the auto generated test xml file. The "key"
947 // is optional in each of these.
948 Tradefed_options []tradefed.Option
Dan Shiec731432023-05-26 04:21:44 +0000949
950 // Extra <option> tags to add to the auto generated test xml file under the test runner, e.g., AndroidJunitTest.
951 // The "key" is optional in each of these.
952 Test_runner_options []tradefed.Option
Dan Shi95d19422020-08-15 12:24:26 -0700953}
954
Colin Cross05638fc2018-04-09 18:40:24 -0700955type testProperties struct {
Colin Cross05638fc2018-04-09 18:40:24 -0700956 // list of compatibility suites (for example "cts", "vts") that the module should be
957 // installed into.
958 Test_suites []string `android:"arch_variant"`
Julien Despreze146e392018-08-02 15:00:46 -0700959
960 // the name of the test configuration (for example "AndroidTest.xml") that should be
961 // installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800962 Test_config *string `android:"path,arch_variant"`
Colin Crossd96ca352018-08-10 16:06:24 -0700963
Jack He33338892018-09-19 02:21:28 -0700964 // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
965 // should be installed with the module.
Colin Cross27b922f2019-03-04 22:35:41 -0800966 Test_config_template *string `android:"path,arch_variant"`
Jack He33338892018-09-19 02:21:28 -0700967
Colin Crossd96ca352018-08-10 16:06:24 -0700968 // list of files or filegroup modules that provide data that should be installed alongside
969 // the test
Jiyong Park2b0e4902021-02-16 06:52:39 +0900970 Data []string `android:"path"`
Dan Shi6ffaaa82019-09-26 11:41:36 -0700971
972 // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
973 // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
974 // explicitly.
975 Auto_gen_config *bool
easoncylee5bcff5d2020-04-30 14:57:06 +0800976
977 // Add parameterized mainline modules to auto generated test config. The options will be
978 // handled by TradeFed to do downloading and installing the specified modules on the device.
979 Test_mainline_modules []string
Dan Shi95d19422020-08-15 12:24:26 -0700980
981 // Test options.
982 Test_options TestOptions
Colin Crossf8d9c492021-01-26 11:01:43 -0800983
984 // Names of modules containing JNI libraries that should be installed alongside the test.
985 Jni_libs []string
Colin Crosscfb0f5e2021-09-24 15:47:17 -0700986
987 // Install the test into a folder named for the module in all test suites.
988 Per_testcase_directory *bool
Colin Cross05638fc2018-04-09 18:40:24 -0700989}
990
Liz Kammerdd849a82020-06-12 16:38:45 -0700991type hostTestProperties struct {
992 // list of native binary modules that should be installed alongside the test
993 Data_native_bins []string `android:"arch_variant"`
Sam Delmericob3342ce2022-01-20 21:10:28 +0000994
995 // list of device binary modules that should be installed alongside the test
Sam Delmericocc271e22022-06-01 15:45:02 +0000996 // This property only adds the first variant of the dependency
997 Data_device_bins_first []string `android:"arch_variant"`
998
999 // list of device binary modules that should be installed alongside the test
1000 // This property adds 64bit AND 32bit variants of the dependency
1001 Data_device_bins_both []string `android:"arch_variant"`
1002
1003 // list of device binary modules that should be installed alongside the test
1004 // This property only adds 64bit variants of the dependency
1005 Data_device_bins_64 []string `android:"arch_variant"`
1006
1007 // list of device binary modules that should be installed alongside the test
1008 // This property adds 32bit variants of the dependency if available, or else
1009 // defaults to the 64bit variant
1010 Data_device_bins_prefer32 []string `android:"arch_variant"`
1011
1012 // list of device binary modules that should be installed alongside the test
1013 // This property only adds 32bit variants of the dependency
1014 Data_device_bins_32 []string `android:"arch_variant"`
Liz Kammerdd849a82020-06-12 16:38:45 -07001015}
1016
Paul Duffin42df1442019-03-20 12:45:53 +00001017type testHelperLibraryProperties struct {
1018 // list of compatibility suites (for example "cts", "vts") that the module should be
1019 // installed into.
1020 Test_suites []string `android:"arch_variant"`
Colin Crosscfb0f5e2021-09-24 15:47:17 -07001021
1022 // Install the test into a folder named for the module in all test suites.
1023 Per_testcase_directory *bool
Paul Duffin42df1442019-03-20 12:45:53 +00001024}
1025
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001026type prebuiltTestProperties struct {
1027 // list of compatibility suites (for example "cts", "vts") that the module should be
1028 // installed into.
1029 Test_suites []string `android:"arch_variant"`
1030
1031 // the name of the test configuration (for example "AndroidTest.xml") that should be
1032 // installed with the module.
1033 Test_config *string `android:"path,arch_variant"`
1034}
1035
Colin Cross05638fc2018-04-09 18:40:24 -07001036type Test struct {
1037 Library
1038
1039 testProperties testProperties
Colin Cross303e21f2018-08-07 16:49:25 -07001040
Dan Shi95d19422020-08-15 12:24:26 -07001041 testConfig android.Path
1042 extraTestConfigs android.Paths
1043 data android.Paths
Colin Cross303e21f2018-08-07 16:49:25 -07001044}
1045
Liz Kammerdd849a82020-06-12 16:38:45 -07001046type TestHost struct {
1047 Test
1048
1049 testHostProperties hostTestProperties
1050}
1051
Paul Duffin42df1442019-03-20 12:45:53 +00001052type TestHelperLibrary struct {
1053 Library
1054
1055 testHelperLibraryProperties testHelperLibraryProperties
1056}
1057
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001058type JavaTestImport struct {
1059 Import
1060
1061 prebuiltTestProperties prebuiltTestProperties
1062
1063 testConfig android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07001064 dexJarFile android.Path
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001065}
1066
Colin Cross24cc4be62021-11-03 14:09:41 -07001067func (j *Test) InstallInTestcases() bool {
1068 // Host java tests install into $(HOST_OUT_JAVA_LIBRARIES), and then are copied into
1069 // testcases by base_rules.mk.
1070 return !j.Host()
1071}
1072
1073func (j *TestHelperLibrary) InstallInTestcases() bool {
1074 return true
1075}
1076
1077func (j *JavaTestImport) InstallInTestcases() bool {
1078 return true
1079}
1080
Yu Liud8aa2002023-10-05 11:40:06 -07001081func (j *TestHost) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
1082 return ctx.DeviceConfig().NativeCoverageEnabled()
1083}
1084
Sam Delmericocc271e22022-06-01 15:45:02 +00001085func (j *TestHost) addDataDeviceBinsDeps(ctx android.BottomUpMutatorContext) {
1086 if len(j.testHostProperties.Data_device_bins_first) > 0 {
1087 deviceVariations := ctx.Config().AndroidFirstDeviceTarget.Variations()
1088 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_first...)
1089 }
1090
1091 var maybeAndroid32Target *android.Target
1092 var maybeAndroid64Target *android.Target
1093 android32TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib32")
1094 android64TargetList := android.FirstTarget(ctx.Config().Targets[android.Android], "lib64")
1095 if len(android32TargetList) > 0 {
1096 maybeAndroid32Target = &android32TargetList[0]
1097 }
1098 if len(android64TargetList) > 0 {
1099 maybeAndroid64Target = &android64TargetList[0]
1100 }
1101
1102 if len(j.testHostProperties.Data_device_bins_both) > 0 {
1103 if maybeAndroid32Target == nil && maybeAndroid64Target == nil {
1104 ctx.PropertyErrorf("data_device_bins_both", "no device targets available. Targets: %q", ctx.Config().Targets)
1105 return
1106 }
1107 if maybeAndroid32Target != nil {
1108 ctx.AddFarVariationDependencies(
1109 maybeAndroid32Target.Variations(),
1110 dataDeviceBinsTag,
1111 j.testHostProperties.Data_device_bins_both...,
1112 )
1113 }
1114 if maybeAndroid64Target != nil {
1115 ctx.AddFarVariationDependencies(
1116 maybeAndroid64Target.Variations(),
1117 dataDeviceBinsTag,
1118 j.testHostProperties.Data_device_bins_both...,
1119 )
1120 }
1121 }
1122
1123 if len(j.testHostProperties.Data_device_bins_prefer32) > 0 {
1124 if maybeAndroid32Target != nil {
1125 ctx.AddFarVariationDependencies(
1126 maybeAndroid32Target.Variations(),
1127 dataDeviceBinsTag,
1128 j.testHostProperties.Data_device_bins_prefer32...,
1129 )
1130 } else {
1131 if maybeAndroid64Target == nil {
1132 ctx.PropertyErrorf("data_device_bins_prefer32", "no device targets available. Targets: %q", ctx.Config().Targets)
1133 return
1134 }
1135 ctx.AddFarVariationDependencies(
1136 maybeAndroid64Target.Variations(),
1137 dataDeviceBinsTag,
1138 j.testHostProperties.Data_device_bins_prefer32...,
1139 )
1140 }
1141 }
1142
1143 if len(j.testHostProperties.Data_device_bins_32) > 0 {
1144 if maybeAndroid32Target == nil {
1145 ctx.PropertyErrorf("data_device_bins_32", "cannot find 32bit device target. Targets: %q", ctx.Config().Targets)
1146 return
1147 }
1148 deviceVariations := maybeAndroid32Target.Variations()
1149 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_32...)
1150 }
1151
1152 if len(j.testHostProperties.Data_device_bins_64) > 0 {
1153 if maybeAndroid64Target == nil {
1154 ctx.PropertyErrorf("data_device_bins_64", "cannot find 64bit device target. Targets: %q", ctx.Config().Targets)
1155 return
1156 }
1157 deviceVariations := maybeAndroid64Target.Variations()
1158 ctx.AddFarVariationDependencies(deviceVariations, dataDeviceBinsTag, j.testHostProperties.Data_device_bins_64...)
1159 }
1160}
1161
Liz Kammerdd849a82020-06-12 16:38:45 -07001162func (j *TestHost) DepsMutator(ctx android.BottomUpMutatorContext) {
1163 if len(j.testHostProperties.Data_native_bins) > 0 {
1164 for _, target := range ctx.MultiTargets() {
1165 ctx.AddVariationDependencies(target.Variations(), dataNativeBinsTag, j.testHostProperties.Data_native_bins...)
1166 }
1167 }
1168
Colin Crossf8d9c492021-01-26 11:01:43 -08001169 if len(j.testProperties.Jni_libs) > 0 {
1170 for _, target := range ctx.MultiTargets() {
1171 sharedLibVariations := append(target.Variations(), blueprint.Variation{Mutator: "link", Variation: "shared"})
1172 ctx.AddFarVariationDependencies(sharedLibVariations, jniLibTag, j.testProperties.Jni_libs...)
1173 }
1174 }
1175
Sam Delmericocc271e22022-06-01 15:45:02 +00001176 j.addDataDeviceBinsDeps(ctx)
Liz Kammerdd849a82020-06-12 16:38:45 -07001177 j.deps(ctx)
1178}
1179
Yuexi Ma627263f2021-03-04 13:47:56 -08001180func (j *TestHost) AddExtraResource(p android.Path) {
1181 j.extraResources = append(j.extraResources, p)
1182}
1183
Sam Delmericocc271e22022-06-01 15:45:02 +00001184func (j *TestHost) dataDeviceBins() []string {
1185 ret := make([]string, 0,
1186 len(j.testHostProperties.Data_device_bins_first)+
1187 len(j.testHostProperties.Data_device_bins_both)+
1188 len(j.testHostProperties.Data_device_bins_prefer32)+
1189 len(j.testHostProperties.Data_device_bins_32)+
1190 len(j.testHostProperties.Data_device_bins_64),
1191 )
1192
1193 ret = append(ret, j.testHostProperties.Data_device_bins_first...)
1194 ret = append(ret, j.testHostProperties.Data_device_bins_both...)
1195 ret = append(ret, j.testHostProperties.Data_device_bins_prefer32...)
1196 ret = append(ret, j.testHostProperties.Data_device_bins_32...)
1197 ret = append(ret, j.testHostProperties.Data_device_bins_64...)
1198
1199 return ret
1200}
1201
Sam Delmericob3342ce2022-01-20 21:10:28 +00001202func (j *TestHost) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1203 var configs []tradefed.Config
Sam Delmericocc271e22022-06-01 15:45:02 +00001204 dataDeviceBins := j.dataDeviceBins()
1205 if len(dataDeviceBins) > 0 {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001206 // add Tradefed configuration to push device bins to device for testing
1207 remoteDir := filepath.Join("/data/local/tests/unrestricted/", j.Name())
1208 options := []tradefed.Option{{Name: "cleanup", Value: "true"}}
Sam Delmericocc271e22022-06-01 15:45:02 +00001209 for _, bin := range dataDeviceBins {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001210 fullPath := filepath.Join(remoteDir, bin)
1211 options = append(options, tradefed.Option{Name: "push-file", Key: bin, Value: fullPath})
1212 }
Sam Delmericocc271e22022-06-01 15:45:02 +00001213 configs = append(configs, tradefed.Object{
1214 Type: "target_preparer",
1215 Class: "com.android.tradefed.targetprep.PushFilePreparer",
1216 Options: options,
1217 })
Sam Delmericob3342ce2022-01-20 21:10:28 +00001218 }
1219
1220 j.Test.generateAndroidBuildActionsWithConfig(ctx, configs)
Colin Cross40213022023-12-13 15:19:49 -08001221 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001222}
1223
Colin Cross303e21f2018-08-07 16:49:25 -07001224func (j *Test) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Sam Delmericob3342ce2022-01-20 21:10:28 +00001225 j.generateAndroidBuildActionsWithConfig(ctx, nil)
Colin Cross40213022023-12-13 15:19:49 -08001226 android.SetProvider(ctx, testing.TestModuleProviderKey, testing.TestModuleProviderData{})
Sam Delmericob3342ce2022-01-20 21:10:28 +00001227}
1228
1229func (j *Test) generateAndroidBuildActionsWithConfig(ctx android.ModuleContext, configs []tradefed.Config) {
Julien Desprezb2166612021-03-05 18:08:36 +00001230 if j.testProperties.Test_options.Unit_test == nil && ctx.Host() {
1231 // TODO(b/): Clean temporary heuristic to avoid unexpected onboarding.
Julien Desprezf666b152021-03-15 13:07:53 -07001232 defaultUnitTest := !inList("tradefed", j.properties.Libs) && !inList("cts", j.testProperties.Test_suites)
Julien Desprezb2166612021-03-05 18:08:36 +00001233 j.testProperties.Test_options.Unit_test = proptools.BoolPtr(defaultUnitTest)
1234 }
Cole Faust21680542022-12-07 18:18:37 -08001235 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1236 TestConfigProp: j.testProperties.Test_config,
1237 TestConfigTemplateProp: j.testProperties.Test_config_template,
1238 TestSuites: j.testProperties.Test_suites,
1239 Config: configs,
1240 OptionsForAutogenerated: j.testProperties.Test_options.Tradefed_options,
Dan Shiec731432023-05-26 04:21:44 +00001241 TestRunnerOptions: j.testProperties.Test_options.Test_runner_options,
Cole Faust21680542022-12-07 18:18:37 -08001242 AutoGenConfig: j.testProperties.Auto_gen_config,
1243 UnitTest: j.testProperties.Test_options.Unit_test,
1244 DeviceTemplate: "${JavaTestConfigTemplate}",
1245 HostTemplate: "${JavaHostTestConfigTemplate}",
1246 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1247 })
Liz Kammerdd849a82020-06-12 16:38:45 -07001248
Colin Cross8a497952019-03-05 22:25:09 -08001249 j.data = android.PathsForModuleSrc(ctx, j.testProperties.Data)
Colin Cross303e21f2018-08-07 16:49:25 -07001250
Dan Shi95d19422020-08-15 12:24:26 -07001251 j.extraTestConfigs = android.PathsForModuleSrc(ctx, j.testProperties.Test_options.Extra_test_configs)
1252
Liz Kammerdd849a82020-06-12 16:38:45 -07001253 ctx.VisitDirectDepsWithTag(dataNativeBinsTag, func(dep android.Module) {
1254 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1255 })
1256
Sam Delmericob3342ce2022-01-20 21:10:28 +00001257 ctx.VisitDirectDepsWithTag(dataDeviceBinsTag, func(dep android.Module) {
1258 j.data = append(j.data, android.OutputFileForModule(ctx, dep, ""))
1259 })
1260
Colin Crossf8d9c492021-01-26 11:01:43 -08001261 ctx.VisitDirectDepsWithTag(jniLibTag, func(dep android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001262 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
Colin Crossf8d9c492021-01-26 11:01:43 -08001263 if sharedLibInfo.SharedLibrary != nil {
1264 // Copy to an intermediate output directory to append "lib[64]" to the path,
1265 // so that it's compatible with the default rpath values.
1266 var relPath string
1267 if sharedLibInfo.Target.Arch.ArchType.Multilib == "lib64" {
1268 relPath = filepath.Join("lib64", sharedLibInfo.SharedLibrary.Base())
1269 } else {
1270 relPath = filepath.Join("lib", sharedLibInfo.SharedLibrary.Base())
1271 }
1272 relocatedLib := android.PathForModuleOut(ctx, "relocated").Join(ctx, relPath)
1273 ctx.Build(pctx, android.BuildParams{
1274 Rule: android.Cp,
1275 Input: sharedLibInfo.SharedLibrary,
1276 Output: relocatedLib,
1277 })
1278 j.data = append(j.data, relocatedLib)
1279 } else {
1280 ctx.PropertyErrorf("jni_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
1281 }
1282 })
1283
Colin Cross303e21f2018-08-07 16:49:25 -07001284 j.Library.GenerateAndroidBuildActions(ctx)
Colin Cross05638fc2018-04-09 18:40:24 -07001285}
1286
Paul Duffin42df1442019-03-20 12:45:53 +00001287func (j *TestHelperLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1288 j.Library.GenerateAndroidBuildActions(ctx)
1289}
1290
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001291func (j *JavaTestImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faust21680542022-12-07 18:18:37 -08001292 j.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
1293 TestConfigProp: j.prebuiltTestProperties.Test_config,
1294 TestSuites: j.prebuiltTestProperties.Test_suites,
1295 DeviceTemplate: "${JavaTestConfigTemplate}",
1296 HostTemplate: "${JavaHostTestConfigTemplate}",
1297 HostUnitTestTemplate: "${JavaHostUnitTestConfigTemplate}",
1298 })
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001299
1300 j.Import.GenerateAndroidBuildActions(ctx)
1301}
1302
1303type testSdkMemberType struct {
1304 android.SdkMemberTypeBase
1305}
1306
Paul Duffin296701e2021-07-14 10:29:36 +01001307func (mt *testSdkMemberType) AddDependencies(ctx android.SdkDependencyContext, dependencyTag blueprint.DependencyTag, names []string) {
1308 ctx.AddVariationDependencies(nil, dependencyTag, names...)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001309}
1310
1311func (mt *testSdkMemberType) IsInstance(module android.Module) bool {
1312 _, ok := module.(*Test)
1313 return ok
1314}
1315
Paul Duffin3a4eb502020-03-19 16:11:18 +00001316func (mt *testSdkMemberType) AddPrebuiltModule(ctx android.SdkMemberContext, member android.SdkMember) android.BpModule {
1317 return ctx.SnapshotBuilder().AddPrebuiltModule(member, "java_test_import")
Paul Duffin14eb4672020-03-02 11:33:02 +00001318}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001319
Paul Duffin14eb4672020-03-02 11:33:02 +00001320func (mt *testSdkMemberType) CreateVariantPropertiesStruct() android.SdkMemberProperties {
1321 return &testSdkMemberProperties{}
1322}
1323
1324type testSdkMemberProperties struct {
1325 android.SdkMemberPropertiesBase
1326
Paul Duffina551a1c2020-03-17 21:04:24 +00001327 JarToExport android.Path
1328 TestConfig android.Path
Paul Duffin14eb4672020-03-02 11:33:02 +00001329}
1330
Paul Duffin3a4eb502020-03-19 16:11:18 +00001331func (p *testSdkMemberProperties) PopulateFromVariant(ctx android.SdkMemberContext, variant android.Module) {
Paul Duffin14eb4672020-03-02 11:33:02 +00001332 test := variant.(*Test)
1333
1334 implementationJars := test.ImplementationJars()
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001335 if len(implementationJars) != 1 {
Paul Duffin14eb4672020-03-02 11:33:02 +00001336 panic(fmt.Errorf("there must be only one implementation jar from %q", test.Name()))
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001337 }
1338
Paul Duffina551a1c2020-03-17 21:04:24 +00001339 p.JarToExport = implementationJars[0]
1340 p.TestConfig = test.testConfig
Paul Duffin14eb4672020-03-02 11:33:02 +00001341}
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001342
Paul Duffin3a4eb502020-03-19 16:11:18 +00001343func (p *testSdkMemberProperties) AddToPropertySet(ctx android.SdkMemberContext, propertySet android.BpPropertySet) {
Paul Duffina551a1c2020-03-17 21:04:24 +00001344 builder := ctx.SnapshotBuilder()
Paul Duffin3a4eb502020-03-19 16:11:18 +00001345
Paul Duffina551a1c2020-03-17 21:04:24 +00001346 exportedJar := p.JarToExport
1347 if exportedJar != nil {
Paul Duffin13648912022-07-15 13:12:35 +00001348 snapshotRelativeJavaLibPath := sdkSnapshotFilePathForJar(ctx, p.OsPrefix(), ctx.Name())
Paul Duffina551a1c2020-03-17 21:04:24 +00001349 builder.CopyToSnapshot(exportedJar, snapshotRelativeJavaLibPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001350
1351 propertySet.AddProperty("jars", []string{snapshotRelativeJavaLibPath})
Paul Duffina551a1c2020-03-17 21:04:24 +00001352 }
1353
1354 testConfig := p.TestConfig
1355 if testConfig != nil {
1356 snapshotRelativeTestConfigPath := sdkSnapshotFilePathForMember(p.OsPrefix(), ctx.Name(), testConfigSuffix)
1357 builder.CopyToSnapshot(testConfig, snapshotRelativeTestConfigPath)
Paul Duffin14eb4672020-03-02 11:33:02 +00001358 propertySet.AddProperty("test_config", snapshotRelativeTestConfigPath)
1359 }
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001360}
1361
Colin Cross1b16b0e2019-02-12 14:41:32 -08001362// java_test builds a and links sources into a `.jar` file for the device, and possibly for the host as well, and
1363// creates an `AndroidTest.xml` file to allow running the test with `atest` or a `TEST_MAPPING` file.
1364//
1365// By default, a java_test has a single variant that produces a `.jar` file containing `classes.dex` files that were
1366// compiled against the device bootclasspath.
1367//
1368// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1369// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001370func TestFactory() android.Module {
1371 module := &Test{}
1372
Colin Crossce6734e2020-06-15 16:09:53 -07001373 module.addHostAndDeviceProperties()
1374 module.AddProperties(&module.testProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001375
Colin Cross9ae1b922018-06-26 17:59:05 -07001376 module.Module.properties.Installable = proptools.BoolPtr(true)
Colin Crosse3026872019-01-05 22:30:13 -08001377 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001378 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9ae1b922018-06-26 17:59:05 -07001379
Colin Cross05638fc2018-04-09 18:40:24 -07001380 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross05638fc2018-04-09 18:40:24 -07001381 return module
1382}
1383
Paul Duffin42df1442019-03-20 12:45:53 +00001384// java_test_helper_library creates a java library and makes sure that it is added to the appropriate test suite.
1385func TestHelperLibraryFactory() android.Module {
1386 module := &TestHelperLibrary{}
1387
Colin Crossce6734e2020-06-15 16:09:53 -07001388 module.addHostAndDeviceProperties()
1389 module.AddProperties(&module.testHelperLibraryProperties)
Paul Duffin42df1442019-03-20 12:45:53 +00001390
Colin Cross9a4abed2019-04-24 13:19:28 -07001391 module.Module.properties.Installable = proptools.BoolPtr(true)
1392 module.Module.dexpreopter.isTest = true
Cole Faustd57e8b22022-08-11 11:59:04 -07001393 module.Module.linter.properties.Lint.Test = proptools.BoolPtr(true)
Colin Cross9a4abed2019-04-24 13:19:28 -07001394
Paul Duffin42df1442019-03-20 12:45:53 +00001395 InitJavaModule(module, android.HostAndDeviceSupported)
1396 return module
1397}
1398
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001399// java_test_import imports one or more `.jar` files into the build graph as if they were built by a java_test module
1400// and makes sure that it is added to the appropriate test suite.
1401//
1402// By default, a java_test_import has a single variant that expects a `.jar` file containing `.class` files that were
1403// compiled against an Android classpath.
1404//
1405// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
1406// for host modules.
1407func JavaTestImportFactory() android.Module {
1408 module := &JavaTestImport{}
1409
1410 module.AddProperties(
1411 &module.Import.properties,
1412 &module.prebuiltTestProperties)
1413
1414 module.Import.properties.Installable = proptools.BoolPtr(true)
1415
1416 android.InitPrebuiltModule(module, &module.properties.Jars)
1417 android.InitApexModule(module)
Paul Duffin1b82e6a2019-12-03 18:06:47 +00001418 InitJavaModule(module, android.HostAndDeviceSupported)
1419 return module
1420}
1421
Colin Cross1b16b0e2019-02-12 14:41:32 -08001422// java_test_host builds a and links sources into a `.jar` file for the host, and creates an `AndroidTest.xml` file to
1423// allow running the test with `atest` or a `TEST_MAPPING` file.
1424//
1425// A java_test_host has a single variant that produces a `.jar` file containing `.class` files that were
1426// compiled against the host bootclasspath.
Colin Cross05638fc2018-04-09 18:40:24 -07001427func TestHostFactory() android.Module {
Liz Kammerdd849a82020-06-12 16:38:45 -07001428 module := &TestHost{}
Colin Cross05638fc2018-04-09 18:40:24 -07001429
Colin Crossce6734e2020-06-15 16:09:53 -07001430 module.addHostProperties()
1431 module.AddProperties(&module.testProperties)
Liz Kammerdd849a82020-06-12 16:38:45 -07001432 module.AddProperties(&module.testHostProperties)
Colin Cross05638fc2018-04-09 18:40:24 -07001433
Yuexi Ma627263f2021-03-04 13:47:56 -08001434 InitTestHost(
1435 module,
1436 proptools.BoolPtr(true),
1437 nil,
1438 nil)
Colin Cross9ae1b922018-06-26 17:59:05 -07001439
Liz Kammerdd849a82020-06-12 16:38:45 -07001440 InitJavaModuleMultiTargets(module, android.HostSupported)
Julien Desprezb2166612021-03-05 18:08:36 +00001441
Colin Cross05638fc2018-04-09 18:40:24 -07001442 return module
1443}
1444
Yuexi Ma627263f2021-03-04 13:47:56 -08001445func InitTestHost(th *TestHost, installable *bool, testSuites []string, autoGenConfig *bool) {
1446 th.properties.Installable = installable
1447 th.testProperties.Auto_gen_config = autoGenConfig
1448 th.testProperties.Test_suites = testSuites
1449}
1450
Colin Cross05638fc2018-04-09 18:40:24 -07001451//
Colin Cross2fe66872015-03-30 17:20:39 -07001452// Java Binaries (.jar file plus wrapper script)
1453//
1454
Colin Crossf506d872017-07-19 15:53:04 -07001455type binaryProperties struct {
Colin Cross7d5136f2015-05-11 13:39:40 -07001456 // installable script to execute the resulting jar
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001457 Wrapper *string `android:"path,arch_variant"`
Colin Cross094054a2018-10-17 15:10:48 -07001458
1459 // Name of the class containing main to be inserted into the manifest as Main-Class.
1460 Main_class *string
Colin Cross89226d92020-10-09 19:00:54 -07001461
1462 // Names of modules containing JNI libraries that should be installed alongside the host
1463 // variant of the binary.
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001464 Jni_libs []string `android:"arch_variant"`
Colin Cross7d5136f2015-05-11 13:39:40 -07001465}
1466
Colin Crossf506d872017-07-19 15:53:04 -07001467type Binary struct {
1468 Library
Colin Cross2fe66872015-03-30 17:20:39 -07001469
Colin Crossf506d872017-07-19 15:53:04 -07001470 binaryProperties binaryProperties
Colin Cross10a03492017-08-10 17:09:43 -07001471
Colin Cross6b4a32d2017-12-05 13:42:45 -08001472 isWrapperVariant bool
1473
Colin Crossc3315992017-12-08 19:12:36 -08001474 wrapperFile android.Path
Colin Cross70dda7e2019-10-01 22:05:35 -07001475 binaryFile android.InstallPath
Colin Cross2fe66872015-03-30 17:20:39 -07001476}
1477
Alex Light24237172017-10-26 09:46:21 -07001478func (j *Binary) HostToolPath() android.OptionalPath {
1479 return android.OptionalPathForPath(j.binaryFile)
1480}
1481
Colin Crossf506d872017-07-19 15:53:04 -07001482func (j *Binary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001483 j.stem = proptools.StringDefault(j.overridableDeviceProperties.Stem, ctx.ModuleName())
1484
Colin Cross6b4a32d2017-12-05 13:42:45 -08001485 if ctx.Arch().ArchType == android.Common {
1486 // Compile the jar
Colin Cross094054a2018-10-17 15:10:48 -07001487 if j.binaryProperties.Main_class != nil {
1488 if j.properties.Manifest != nil {
1489 ctx.PropertyErrorf("main_class", "main_class cannot be used when manifest is set")
1490 }
1491 manifestFile := android.PathForModuleOut(ctx, "manifest.txt")
1492 GenerateMainClassManifest(ctx, manifestFile, String(j.binaryProperties.Main_class))
1493 j.overrideManifest = android.OptionalPathForPath(manifestFile)
1494 }
1495
Colin Cross6b4a32d2017-12-05 13:42:45 -08001496 j.Library.GenerateAndroidBuildActions(ctx)
Nan Zhang3c807db2017-11-03 14:53:31 -07001497 } else {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001498 // Handle the binary wrapper
1499 j.isWrapperVariant = true
1500
Colin Cross366938f2017-12-11 16:29:02 -08001501 if j.binaryProperties.Wrapper != nil {
Colin Cross8a497952019-03-05 22:25:09 -08001502 j.wrapperFile = android.PathForModuleSrc(ctx, *j.binaryProperties.Wrapper)
Colin Cross6b4a32d2017-12-05 13:42:45 -08001503 } else {
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001504 if ctx.Windows() {
1505 ctx.PropertyErrorf("wrapper", "wrapper is required for Windows")
1506 }
1507
Zi Wangca65b402022-10-10 13:45:06 -07001508 if ctx.Device() {
1509 // device binary should have a main_class property if it does not
1510 // have a specific wrapper, so that a default wrapper can
1511 // be generated for it.
1512 if j.binaryProperties.Main_class == nil {
1513 ctx.PropertyErrorf("main_class", "main_class property "+
1514 "is required for device binary if no default wrapper is assigned")
1515 } else {
1516 wrapper := android.PathForModuleOut(ctx, ctx.ModuleName()+".sh")
1517 jarName := j.Stem() + ".jar"
1518 partition := j.PartitionTag(ctx.DeviceConfig())
1519 ctx.Build(pctx, android.BuildParams{
1520 Rule: deviceBinaryWrapper,
1521 Output: wrapper,
1522 Args: map[string]string{
1523 "jar_name": jarName,
1524 "partition": partition,
1525 "main_class": String(j.binaryProperties.Main_class),
1526 },
1527 })
1528 j.wrapperFile = wrapper
1529 }
1530 } else {
1531 j.wrapperFile = android.PathForSource(ctx, "build/soong/scripts/jar-wrapper.sh")
1532 }
Colin Cross6b4a32d2017-12-05 13:42:45 -08001533 }
1534
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001535 ext := ""
1536 if ctx.Windows() {
1537 ext = ".bat"
1538 }
1539
Colin Crossc179ea62020-10-09 10:54:15 -07001540 // The host installation rules make the installed wrapper depend on all the dependencies
Colin Cross89226d92020-10-09 19:00:54 -07001541 // of the wrapper variant, which will include the common variant's jar file and any JNI
1542 // libraries. This is verified by TestBinary.
Colin Cross6b4a32d2017-12-05 13:42:45 -08001543 j.binaryFile = ctx.InstallExecutable(android.PathForModuleInstall(ctx, "bin"),
Dan Willemsen8e6b3712021-09-20 23:11:24 -07001544 ctx.ModuleName()+ext, j.wrapperFile)
1545 }
Colin Cross2fe66872015-03-30 17:20:39 -07001546}
1547
Colin Crossf506d872017-07-19 15:53:04 -07001548func (j *Binary) DepsMutator(ctx android.BottomUpMutatorContext) {
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001549 if ctx.Arch().ArchType == android.Common {
Colin Cross6b4a32d2017-12-05 13:42:45 -08001550 j.deps(ctx)
Liz Kammer356f7d42021-01-26 09:18:53 -05001551 }
Liz Kammer3bf97bd2022-04-26 09:38:20 -04001552 if ctx.Arch().ArchType != android.Common {
Colin Crosse9fe2942020-11-10 18:12:15 -08001553 // These dependencies ensure the host installation rules will install the jar file and
1554 // the jni libraries when the wrapper is installed.
1555 ctx.AddVariationDependencies(nil, jniInstallTag, j.binaryProperties.Jni_libs...)
1556 ctx.AddVariationDependencies(
1557 []blueprint.Variation{{Mutator: "arch", Variation: android.CommonArch.String()}},
1558 binaryInstallTag, ctx.ModuleName())
Colin Cross6b4a32d2017-12-05 13:42:45 -08001559 }
Colin Cross46c9b8b2017-06-22 16:51:17 -07001560}
1561
Colin Cross1b16b0e2019-02-12 14:41:32 -08001562// java_binary builds a `.jar` file and a shell script that executes it for the device, and possibly for the host
1563// as well.
1564//
1565// By default, a java_binary has a single variant that produces a `.jar` file containing `classes.dex` files that were
1566// compiled against the device bootclasspath.
1567//
1568// Specifying `host_supported: true` will produce two variants, one compiled against the device bootclasspath and one
1569// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001570func BinaryFactory() android.Module {
1571 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001572
Colin Crossce6734e2020-06-15 16:09:53 -07001573 module.addHostAndDeviceProperties()
1574 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001575
Colin Cross9ae1b922018-06-26 17:59:05 -07001576 module.Module.properties.Installable = proptools.BoolPtr(true)
1577
Colin Cross6b4a32d2017-12-05 13:42:45 -08001578 android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommonFirst)
1579 android.InitDefaultableModule(module)
Wei Libafb6d62021-12-10 03:14:59 -08001580
Colin Cross36242852017-06-23 15:06:31 -07001581 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001582}
1583
Colin Cross1b16b0e2019-02-12 14:41:32 -08001584// java_binary_host builds a `.jar` file and a shell script that executes it for the host.
1585//
1586// A java_binary_host has a single variant that produces a `.jar` file containing `.class` files that were
1587// compiled against the host bootclasspath.
Colin Crossf506d872017-07-19 15:53:04 -07001588func BinaryHostFactory() android.Module {
1589 module := &Binary{}
Colin Cross2fe66872015-03-30 17:20:39 -07001590
Colin Crossce6734e2020-06-15 16:09:53 -07001591 module.addHostProperties()
1592 module.AddProperties(&module.binaryProperties)
Colin Cross36242852017-06-23 15:06:31 -07001593
Colin Cross9ae1b922018-06-26 17:59:05 -07001594 module.Module.properties.Installable = proptools.BoolPtr(true)
1595
Colin Cross6b4a32d2017-12-05 13:42:45 -08001596 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibCommonFirst)
1597 android.InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -07001598 return module
Colin Cross2fe66872015-03-30 17:20:39 -07001599}
1600
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001601type JavaApiContribution struct {
1602 android.ModuleBase
1603 android.DefaultableModuleBase
Spandan Das2cc80ba2023-10-27 17:21:52 +00001604 embeddableInModuleAndImport
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001605
1606 properties struct {
1607 // name of the API surface
1608 Api_surface *string
1609
1610 // relative path to the API signature text file
1611 Api_file *string `android:"path"`
1612 }
1613}
1614
1615func ApiContributionFactory() android.Module {
1616 module := &JavaApiContribution{}
1617 android.InitAndroidModule(module)
1618 android.InitDefaultableModule(module)
1619 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001620 module.initModuleAndImport(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001621 return module
1622}
1623
1624type JavaApiImportInfo struct {
Jihoon Kang8fe19822023-09-14 06:27:36 +00001625 ApiFile android.Path
1626 ApiSurface string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001627}
1628
Colin Crossbc7d76c2023-12-12 16:39:03 -08001629var JavaApiImportProvider = blueprint.NewProvider[JavaApiImportInfo]()
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001630
1631func (ap *JavaApiContribution) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001632 var apiFile android.Path = nil
1633 if apiFileString := ap.properties.Api_file; apiFileString != nil {
1634 apiFile = android.PathForModuleSrc(ctx, String(apiFileString))
1635 }
1636
Colin Cross40213022023-12-13 15:19:49 -08001637 android.SetProvider(ctx, JavaApiImportProvider, JavaApiImportInfo{
Jihoon Kang8fe19822023-09-14 06:27:36 +00001638 ApiFile: apiFile,
1639 ApiSurface: proptools.String(ap.properties.Api_surface),
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001640 })
1641}
1642
1643type ApiLibrary struct {
1644 android.ModuleBase
1645 android.DefaultableModuleBase
1646
Spandan Dascb368ea2023-03-22 04:27:05 +00001647 hiddenAPI
1648 dexer
Spandan Das2cc80ba2023-10-27 17:21:52 +00001649 embeddableInModuleAndImport
Spandan Dascb368ea2023-03-22 04:27:05 +00001650
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001651 properties JavaApiLibraryProperties
1652
Jihoon Kang01e522c2023-03-14 01:09:34 +00001653 stubsSrcJar android.WritablePath
1654 stubsJar android.WritablePath
1655 stubsJarWithoutStaticLibs android.WritablePath
1656 extractedSrcJar android.WritablePath
Spandan Dascb368ea2023-03-22 04:27:05 +00001657 // .dex of stubs, used for hiddenapi processing
1658 dexJarFile OptionalDexJarPath
Jihoon Kang063ec002023-06-28 01:16:23 +00001659
1660 validationPaths android.Paths
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001661}
1662
1663type JavaApiLibraryProperties struct {
1664 // name of the API surface
1665 Api_surface *string
1666
Jihoon Kang60d4a092022-11-17 23:47:43 +00001667 // list of Java API contribution modules that consists this API surface
Spandan Dasc082eb82022-12-01 21:43:06 +00001668 // This is a list of Soong modules
Jihoon Kang60d4a092022-11-17 23:47:43 +00001669 Api_contributions []string
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001670
1671 // List of flags to be passed to the javac compiler to generate jar file
1672 Javacflags []string
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001673
1674 // List of shared java libs that this module has dependencies to and
1675 // should be passed as classpath in javac invocation
1676 Libs []string
Jihoon Kange30fff02023-02-14 20:18:20 +00001677
1678 // List of java libs that this module has static dependencies to and will be
Jihoon Kang01e522c2023-03-14 01:09:34 +00001679 // merge zipped after metalava invocation
Jihoon Kange30fff02023-02-14 20:18:20 +00001680 Static_libs []string
Jihoon Kang01e522c2023-03-14 01:09:34 +00001681
Jihoon Kangca198c22023-06-22 23:13:51 +00001682 // Java Api library to provide the full API surface stub jar file.
1683 // If this property is set, the stub jar of this module is created by
1684 // extracting the compiled class files provided by the
1685 // full_api_surface_stub module.
1686 Full_api_surface_stub *string
Jihoon Kang862da6f2023-08-01 06:28:51 +00001687
1688 // Version of previously released API file for compatibility check.
1689 Previous_api *string `android:"path"`
Jihoon Kang4ec24872023-10-05 17:26:09 +00001690
1691 // java_system_modules module providing the jar to be added to the
1692 // bootclasspath when compiling the stubs.
1693 // The jar will also be passed to metalava as a classpath to
1694 // generate compilable stubs.
1695 System_modules *string
Jihoon Kang063ec002023-06-28 01:16:23 +00001696
1697 // If true, the module runs validation on the API signature files provided
1698 // by the modules passed via api_contributions by checking if the files are
1699 // in sync with the source Java files. However, the environment variable
1700 // DISABLE_STUB_VALIDATION has precedence over this property.
1701 Enable_validation *bool
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001702}
1703
1704func ApiLibraryFactory() android.Module {
1705 module := &ApiLibrary{}
1706 android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibCommon)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001707 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00001708 module.initModuleAndImport(module)
Jihoon Kang1c51f502023-01-09 23:42:40 +00001709 android.InitDefaultableModule(module)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001710 return module
1711}
1712
1713func (al *ApiLibrary) ApiSurface() *string {
1714 return al.properties.Api_surface
1715}
1716
1717func (al *ApiLibrary) StubsJar() android.Path {
1718 return al.stubsJar
1719}
1720
1721func metalavaStubCmd(ctx android.ModuleContext, rule *android.RuleBuilder,
Jihoon Kang4ec24872023-10-05 17:26:09 +00001722 srcs android.Paths, homeDir android.WritablePath,
1723 classpath android.Paths) *android.RuleBuilderCommand {
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001724 rule.Command().Text("rm -rf").Flag(homeDir.String())
1725 rule.Command().Text("mkdir -p").Flag(homeDir.String())
1726
1727 cmd := rule.Command()
1728 cmd.FlagWithArg("ANDROID_PREFS_ROOT=", homeDir.String())
1729
1730 if metalavaUseRbe(ctx) {
1731 rule.Remoteable(android.RemoteRuleSupports{RBE: true})
1732 execStrategy := ctx.Config().GetenvWithDefault("RBE_METALAVA_EXEC_STRATEGY", remoteexec.LocalExecStrategy)
1733 labels := map[string]string{"type": "tool", "name": "metalava"}
1734
1735 pool := ctx.Config().GetenvWithDefault("RBE_METALAVA_POOL", "java16")
1736 rule.Rewrapper(&remoteexec.REParams{
1737 Labels: labels,
1738 ExecStrategy: execStrategy,
1739 ToolchainInputs: []string{config.JavaCmd(ctx).String()},
1740 Platform: map[string]string{remoteexec.PoolKey: pool},
1741 })
1742 }
1743
1744 cmd.BuiltTool("metalava").ImplicitTool(ctx.Config().HostJavaToolPath(ctx, "metalava.jar")).
1745 Flag(config.JavacVmFlags).
1746 Flag("-J--add-opens=java.base/java.util=ALL-UNNAMED").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001747 FlagWithInputList("--source-files ", srcs, " ")
1748
MÃ¥rten Kongstadbd262442023-07-12 14:01:49 +02001749 cmd.Flag("--color").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001750 Flag("--quiet").
Jihoon Kang1bff0342023-01-17 20:40:22 +00001751 Flag("--include-annotations").
1752 // The flag makes nullability issues as warnings rather than errors by replacing
1753 // @Nullable/@NonNull in the listed packages APIs with @RecentlyNullable/@RecentlyNonNull,
1754 // and these packages are meant to have everything annotated
1755 // @RecentlyNullable/@RecentlyNonNull.
1756 FlagWithArg("--force-convert-to-warning-nullability-annotations ", "+*:-android.*:+android.icu.*:-dalvik.*").
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001757 FlagWithArg("--repeat-errors-max ", "10").
1758 FlagWithArg("--hide ", "UnresolvedImport").
1759 FlagWithArg("--hide ", "InvalidNullabilityOverride").
1760 FlagWithArg("--hide ", "ChangedDefault")
1761
Jihoon Kang4ec24872023-10-05 17:26:09 +00001762 if len(classpath) == 0 {
1763 // The main purpose of the `--api-class-resolution api` option is to force metalava to ignore
1764 // classes on the classpath when an API file contains missing classes. However, as this command
1765 // does not specify `--classpath` this is not needed for that. However, this is also used as a
1766 // signal to the special metalava code for generating stubs from text files that it needs to add
1767 // some additional items into the API (e.g. default constructors).
1768 cmd.FlagWithArg("--api-class-resolution ", "api")
1769 } else {
1770 cmd.FlagWithArg("--api-class-resolution ", "api:classpath")
1771 cmd.FlagWithInputList("--classpath ", classpath, ":")
1772 }
Paul Duffin5b7035f2023-05-31 17:51:33 +01001773
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001774 return cmd
1775}
1776
Jihoon Kang1bff0342023-01-17 20:40:22 +00001777func (al *ApiLibrary) HeaderJars() android.Paths {
1778 return android.Paths{al.stubsJar}
1779}
1780
1781func (al *ApiLibrary) OutputDirAndDeps() (android.Path, android.Paths) {
1782 return nil, nil
1783}
1784
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001785func (al *ApiLibrary) stubsFlags(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, stubsDir android.OptionalPath) {
1786 if stubsDir.Valid() {
1787 cmd.FlagWithArg("--stubs ", stubsDir.String())
1788 }
1789}
1790
Jihoon Kang063ec002023-06-28 01:16:23 +00001791func (al *ApiLibrary) addValidation(ctx android.ModuleContext, cmd *android.RuleBuilderCommand, validationPaths android.Paths) {
1792 for _, validationPath := range validationPaths {
1793 cmd.Validation(validationPath)
1794 }
1795}
1796
Jihoon Kangca198c22023-06-22 23:13:51 +00001797// This method extracts the stub class files from the stub jar file provided
1798// from full_api_surface_stub module instead of compiling the srcjar generated from invoking metalava.
Jihoon Kang01e522c2023-03-14 01:09:34 +00001799// This method is used because metalava can generate compilable from-text stubs only when
Jihoon Kangca198c22023-06-22 23:13:51 +00001800// the codebase encompasses all classes listed in the input API text file, and a class can extend
Jihoon Kang01e522c2023-03-14 01:09:34 +00001801// a class that is not within the same API domain.
Jihoon Kangca198c22023-06-22 23:13:51 +00001802func (al *ApiLibrary) extractApiSrcs(ctx android.ModuleContext, rule *android.RuleBuilder, stubsDir android.OptionalPath, fullApiSurfaceStubJar android.Path) {
1803 classFilesList := android.PathForModuleOut(ctx, "metalava", "classes.txt")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001804 unzippedSrcJarDir := android.PathForModuleOut(ctx, "metalava", "unzipDir")
1805
1806 rule.Command().
1807 BuiltTool("list_files").
1808 Text(stubsDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001809 FlagWithOutput("--out ", classFilesList).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001810 FlagWithArg("--extensions ", ".java").
Jihoon Kangca198c22023-06-22 23:13:51 +00001811 FlagWithArg("--root ", unzippedSrcJarDir.String()).
1812 Flag("--classes")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001813
1814 rule.Command().
1815 Text("unzip").
1816 Flag("-q").
Jihoon Kangca198c22023-06-22 23:13:51 +00001817 Input(fullApiSurfaceStubJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001818 FlagWithArg("-d ", unzippedSrcJarDir.String())
1819
1820 rule.Command().
1821 BuiltTool("soong_zip").
Jihoon Kangca198c22023-06-22 23:13:51 +00001822 Flag("-jar").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001823 Flag("-write_if_changed").
Jihoon Kangca198c22023-06-22 23:13:51 +00001824 Flag("-ignore_missing_files").
Jihoon Kangd02a4362023-09-12 23:54:43 +00001825 Flag("-quiet").
Jihoon Kang01e522c2023-03-14 01:09:34 +00001826 FlagWithArg("-C ", unzippedSrcJarDir.String()).
Jihoon Kangca198c22023-06-22 23:13:51 +00001827 FlagWithInput("-l ", classFilesList).
1828 FlagWithOutput("-o ", al.stubsJarWithoutStaticLibs)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001829}
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001830
1831func (al *ApiLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
Jihoon Kang60d4a092022-11-17 23:47:43 +00001832 apiContributions := al.properties.Api_contributions
Jihoon Kang063ec002023-06-28 01:16:23 +00001833 addValidations := !ctx.Config().IsEnvTrue("DISABLE_STUB_VALIDATION") &&
1834 proptools.BoolDefault(al.properties.Enable_validation, true)
Jihoon Kang60d4a092022-11-17 23:47:43 +00001835 for _, apiContributionName := range apiContributions {
1836 ctx.AddDependency(ctx.Module(), javaApiContributionTag, apiContributionName)
Jihoon Kang063ec002023-06-28 01:16:23 +00001837
1838 // Add the java_api_contribution module generating droidstubs module
1839 // as dependency when validation adding conditions are met and
1840 // the java_api_contribution module name has ".api.contribution" suffix.
1841 // All droidstubs-generated modules possess the suffix in the name,
1842 // but there is no such guarantee for tests.
1843 if addValidations {
1844 if strings.HasSuffix(apiContributionName, ".api.contribution") {
1845 ctx.AddDependency(ctx.Module(), metalavaCurrentApiTimestampTag, strings.TrimSuffix(apiContributionName, ".api.contribution"))
1846 } else {
1847 ctx.ModuleErrorf("Validation is enabled for module %s but a "+
1848 "current timestamp provider is not found for the api "+
1849 "contribution %s",
1850 ctx.ModuleName(),
1851 apiContributionName,
1852 )
1853 }
1854 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001855 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001856 ctx.AddVariationDependencies(nil, libTag, al.properties.Libs...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001857 ctx.AddVariationDependencies(nil, staticLibTag, al.properties.Static_libs...)
Jihoon Kangca198c22023-06-22 23:13:51 +00001858 if al.properties.Full_api_surface_stub != nil {
1859 ctx.AddVariationDependencies(nil, depApiSrcsTag, String(al.properties.Full_api_surface_stub))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001860 }
Jihoon Kang4ec24872023-10-05 17:26:09 +00001861 if al.properties.System_modules != nil {
1862 ctx.AddVariationDependencies(nil, systemModulesTag, String(al.properties.System_modules))
1863 }
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001864}
1865
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001866// Map where key is the api scope name and value is the int value
1867// representing the order of the api scope, narrowest to the widest
1868var scopeOrderMap = allApiScopes.MapToIndex(
1869 func(s *apiScope) string { return s.name })
Jihoon Kang478ca5b2023-08-11 23:33:05 +00001870
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001871func (al *ApiLibrary) sortApiFilesByApiScope(ctx android.ModuleContext, srcFilesInfo []JavaApiImportInfo) []JavaApiImportInfo {
1872 for _, srcFileInfo := range srcFilesInfo {
1873 if srcFileInfo.ApiSurface == "" {
1874 ctx.ModuleErrorf("Api surface not defined for the associated api file %s", srcFileInfo.ApiFile)
Jihoon Kang84473f52023-08-11 22:36:33 +00001875 }
1876 }
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001877 sort.Slice(srcFilesInfo, func(i, j int) bool {
1878 return scopeOrderMap[srcFilesInfo[i].ApiSurface] < scopeOrderMap[srcFilesInfo[j].ApiSurface]
1879 })
Jihoon Kang8fe19822023-09-14 06:27:36 +00001880
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001881 return srcFilesInfo
Jihoon Kang84473f52023-08-11 22:36:33 +00001882}
1883
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001884func (al *ApiLibrary) GenerateAndroidBuildActions(ctx android.ModuleContext) {
1885
1886 rule := android.NewRuleBuilder(pctx, ctx)
1887
1888 rule.Sbox(android.PathForModuleOut(ctx, "metalava"),
1889 android.PathForModuleOut(ctx, "metalava.sbox.textproto")).
1890 SandboxInputs()
1891
Jihoon Kang063ec002023-06-28 01:16:23 +00001892 stubsDir := android.OptionalPathForPath(android.PathForModuleOut(ctx, "metalava", "stubsDir"))
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001893 rule.Command().Text("rm -rf").Text(stubsDir.String())
1894 rule.Command().Text("mkdir -p").Text(stubsDir.String())
1895
1896 homeDir := android.PathForModuleOut(ctx, "metalava", "home")
1897
Jihoon Kang8fe19822023-09-14 06:27:36 +00001898 var srcFilesInfo []JavaApiImportInfo
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001899 var classPaths android.Paths
Jihoon Kange30fff02023-02-14 20:18:20 +00001900 var staticLibs android.Paths
Jihoon Kangca198c22023-06-22 23:13:51 +00001901 var depApiSrcsStubsJar android.Path
Jihoon Kang4ec24872023-10-05 17:26:09 +00001902 var systemModulesPaths android.Paths
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001903 ctx.VisitDirectDeps(func(dep android.Module) {
1904 tag := ctx.OtherModuleDependencyTag(dep)
1905 switch tag {
1906 case javaApiContributionTag:
Colin Cross313aa542023-12-13 13:47:44 -08001907 provider, _ := android.OtherModuleProvider(ctx, dep, JavaApiImportProvider)
Jihoon Kang8fe19822023-09-14 06:27:36 +00001908 if provider.ApiFile == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang3198f3c2023-01-26 08:08:52 +00001909 ctx.ModuleErrorf("Error: %s has an empty api file.", dep.Name())
1910 }
Jihoon Kang8fe19822023-09-14 06:27:36 +00001911 srcFilesInfo = append(srcFilesInfo, provider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001912 case libTag:
Colin Cross313aa542023-12-13 13:47:44 -08001913 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001914 classPaths = append(classPaths, provider.HeaderJars...)
Jihoon Kange30fff02023-02-14 20:18:20 +00001915 case staticLibTag:
Colin Cross313aa542023-12-13 13:47:44 -08001916 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kange30fff02023-02-14 20:18:20 +00001917 staticLibs = append(staticLibs, provider.HeaderJars...)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001918 case depApiSrcsTag:
Colin Cross313aa542023-12-13 13:47:44 -08001919 provider, _ := android.OtherModuleProvider(ctx, dep, JavaInfoProvider)
Jihoon Kangca198c22023-06-22 23:13:51 +00001920 depApiSrcsStubsJar = provider.HeaderJars[0]
Jihoon Kang4ec24872023-10-05 17:26:09 +00001921 case systemModulesTag:
1922 module := dep.(SystemModulesProvider)
1923 systemModulesPaths = append(systemModulesPaths, module.HeaderJars()...)
Jihoon Kang063ec002023-06-28 01:16:23 +00001924 case metalavaCurrentApiTimestampTag:
1925 if currentApiTimestampProvider, ok := dep.(currentApiTimestampProvider); ok {
1926 al.validationPaths = append(al.validationPaths, currentApiTimestampProvider.CurrentApiTimestamp())
1927 }
Jihoon Kang362aa9d2023-01-20 19:44:07 +00001928 }
Jihoon Kang60d4a092022-11-17 23:47:43 +00001929 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001930
Jihoon Kanga96a7b12023-09-20 23:43:32 +00001931 srcFilesInfo = al.sortApiFilesByApiScope(ctx, srcFilesInfo)
1932 var srcFiles android.Paths
1933 for _, srcFileInfo := range srcFilesInfo {
1934 srcFiles = append(srcFiles, android.PathForSource(ctx, srcFileInfo.ApiFile.String()))
Spandan Dasc082eb82022-12-01 21:43:06 +00001935 }
1936
Jihoon Kang160634c2023-05-25 05:28:29 +00001937 if srcFiles == nil && !ctx.Config().AllowMissingDependencies() {
Jihoon Kang01e522c2023-03-14 01:09:34 +00001938 ctx.ModuleErrorf("Error: %s has an empty api file.", ctx.ModuleName())
1939 }
1940
Jihoon Kang4ec24872023-10-05 17:26:09 +00001941 cmd := metalavaStubCmd(ctx, rule, srcFiles, homeDir, systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001942
1943 al.stubsFlags(ctx, cmd, stubsDir)
1944
Jihoon Kang862da6f2023-08-01 06:28:51 +00001945 migratingNullability := String(al.properties.Previous_api) != ""
1946 if migratingNullability {
1947 previousApi := android.PathForModuleSrc(ctx, String(al.properties.Previous_api))
1948 cmd.FlagWithInput("--migrate-nullness ", previousApi)
1949 }
1950
Jihoon Kang063ec002023-06-28 01:16:23 +00001951 al.addValidation(ctx, cmd, al.validationPaths)
1952
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001953 al.stubsSrcJar = android.PathForModuleOut(ctx, "metalava", ctx.ModuleName()+"-"+"stubs.srcjar")
Jihoon Kangca198c22023-06-22 23:13:51 +00001954 al.stubsJarWithoutStaticLibs = android.PathForModuleOut(ctx, "metalava", "stubs.jar")
1955 al.stubsJar = android.PathForModuleOut(ctx, ctx.ModuleName(), fmt.Sprintf("%s.jar", ctx.ModuleName()))
Jihoon Kang01e522c2023-03-14 01:09:34 +00001956
Jihoon Kangca198c22023-06-22 23:13:51 +00001957 if depApiSrcsStubsJar != nil {
1958 al.extractApiSrcs(ctx, rule, stubsDir, depApiSrcsStubsJar)
Jihoon Kang01e522c2023-03-14 01:09:34 +00001959 }
Jihoon Kangca198c22023-06-22 23:13:51 +00001960 rule.Command().
1961 BuiltTool("soong_zip").
1962 Flag("-write_if_changed").
1963 Flag("-jar").
1964 FlagWithOutput("-o ", al.stubsSrcJar).
1965 FlagWithArg("-C ", stubsDir.String()).
1966 FlagWithArg("-D ", stubsDir.String())
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001967
Paul Duffin336b16a2023-08-15 23:10:13 +01001968 rule.Build("metalava", "metalava merged text")
Jihoon Kang01e522c2023-03-14 01:09:34 +00001969
Jihoon Kangca198c22023-06-22 23:13:51 +00001970 if depApiSrcsStubsJar == nil {
1971 var flags javaBuilderFlags
1972 flags.javaVersion = getStubsJavaVersion()
1973 flags.javacFlags = strings.Join(al.properties.Javacflags, " ")
1974 flags.classpath = classpath(classPaths)
Jihoon Kang4ec24872023-10-05 17:26:09 +00001975 flags.bootClasspath = classpath(systemModulesPaths)
Jihoon Kang0ac87c22022-11-15 19:06:14 +00001976
Vadim Spivak3c496f02023-06-08 06:14:59 +00001977 annoSrcJar := android.PathForModuleOut(ctx, ctx.ModuleName(), "anno.srcjar")
1978
Jihoon Kangca198c22023-06-22 23:13:51 +00001979 TransformJavaToClasses(ctx, al.stubsJarWithoutStaticLibs, 0, android.Paths{},
Vadim Spivak3c496f02023-06-08 06:14:59 +00001980 android.Paths{al.stubsSrcJar}, annoSrcJar, flags, android.Paths{})
Jihoon Kangca198c22023-06-22 23:13:51 +00001981 }
Jihoon Kang423d2292022-11-29 23:10:10 +00001982
Jihoon Kange30fff02023-02-14 20:18:20 +00001983 builder := android.NewRuleBuilder(pctx, ctx)
1984 builder.Command().
1985 BuiltTool("merge_zips").
1986 Output(al.stubsJar).
Jihoon Kang01e522c2023-03-14 01:09:34 +00001987 Inputs(android.Paths{al.stubsJarWithoutStaticLibs}).
Jihoon Kange30fff02023-02-14 20:18:20 +00001988 Inputs(staticLibs)
1989 builder.Build("merge_zips", "merge jar files")
1990
Spandan Dascb368ea2023-03-22 04:27:05 +00001991 // compile stubs to .dex for hiddenapi processing
1992 dexParams := &compileDexParams{
1993 flags: javaBuilderFlags{},
1994 sdkVersion: al.SdkVersion(ctx),
1995 minSdkVersion: al.MinSdkVersion(ctx),
1996 classesJar: al.stubsJar,
1997 jarName: ctx.ModuleName() + ".jar",
1998 }
1999 dexOutputFile := al.dexer.compileDex(ctx, dexParams)
2000 uncompressed := true
2001 al.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), al.stubsJar, &uncompressed)
2002 dexOutputFile = al.hiddenAPIEncodeDex(ctx, dexOutputFile)
2003 al.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
2004
Jihoon Kang423d2292022-11-29 23:10:10 +00002005 ctx.Phony(ctx.ModuleName(), al.stubsJar)
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002006
Colin Cross40213022023-12-13 15:19:49 -08002007 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jihoon Kang1bff0342023-01-17 20:40:22 +00002008 HeaderJars: android.PathsIfNonNil(al.stubsJar),
2009 ImplementationAndResourcesJars: android.PathsIfNonNil(al.stubsJar),
2010 ImplementationJars: android.PathsIfNonNil(al.stubsJar),
2011 AidlIncludeDirs: android.Paths{},
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002012 // No aconfig libraries on api libraries
Jihoon Kang362aa9d2023-01-20 19:44:07 +00002013 })
Jihoon Kang0ac87c22022-11-15 19:06:14 +00002014}
2015
Spandan Das59a4a2b2024-01-09 21:35:56 +00002016func (al *ApiLibrary) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dascb368ea2023-03-22 04:27:05 +00002017 return al.dexJarFile
2018}
2019
2020func (al *ApiLibrary) DexJarInstallPath() android.Path {
2021 return al.dexJarFile.Path()
2022}
2023
2024func (al *ApiLibrary) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2025 return nil
2026}
2027
2028// java_api_library constitutes the sdk, and does not build against one
2029func (al *ApiLibrary) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2030 return android.SdkSpecNone
2031}
2032
2033// java_api_library is always at "current". Return FutureApiLevel
2034func (al *ApiLibrary) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2035 return android.FutureApiLevel
2036}
2037
2038// implement the following interfaces for hiddenapi processing
2039var _ hiddenAPIModule = (*ApiLibrary)(nil)
2040var _ UsesLibraryDependency = (*ApiLibrary)(nil)
2041
Colin Cross2fe66872015-03-30 17:20:39 -07002042//
2043// Java prebuilts
2044//
2045
Colin Cross74d73e22017-08-02 11:05:49 -07002046type ImportProperties struct {
Paul Duffina04c1072020-03-02 10:16:35 +00002047 Jars []string `android:"path,arch_variant"`
Colin Cross461bd1a2017-10-20 13:59:18 -07002048
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002049 // The version of the SDK that the source prebuilt file was built against. Defaults to the
2050 // current version if not specified.
Nan Zhangea568a42017-11-08 21:20:04 -08002051 Sdk_version *string
Colin Cross535e2cf2017-10-20 17:57:49 -07002052
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002053 // The minimum version of the SDK that this module supports. Defaults to sdk_version if not
2054 // specified.
2055 Min_sdk_version *string
2056
William Loh5a082f92022-05-17 20:21:50 +00002057 // The max sdk version placeholder used to replace maxSdkVersion attributes on permission
2058 // and uses-permission tags in manifest_fixer.
2059 Replace_max_sdk_version_placeholder *string
2060
Colin Cross535e2cf2017-10-20 17:57:49 -07002061 Installable *bool
Jiyong Park1be96912018-05-28 18:02:19 +09002062
Paul Duffin869de142021-07-15 14:14:41 +01002063 // If not empty, classes are restricted to the specified packages and their sub-packages.
Paul Duffin869de142021-07-15 14:14:41 +01002064 Permitted_packages []string
2065
Jiyong Park1be96912018-05-28 18:02:19 +09002066 // List of shared java libs that this module has dependencies to
2067 Libs []string
Colin Cross37f6d792018-07-12 12:28:41 -07002068
2069 // List of files to remove from the jar file(s)
2070 Exclude_files []string
2071
2072 // List of directories to remove from the jar file(s)
2073 Exclude_dirs []string
Nan Zhang4c819fb2018-08-27 18:31:46 -07002074
2075 // if set to true, run Jetifier against .jar file. Defaults to false.
Colin Cross1001a792019-03-21 22:21:39 -07002076 Jetifier *bool
Jiyong Park4c4c0242019-10-21 14:53:15 +09002077
2078 // set the name of the output
2079 Stem *string
Jiyong Park19604de2020-03-24 16:44:11 +09002080
2081 Aidl struct {
2082 // directories that should be added as include directories for any aidl sources of modules
2083 // that depend on this module, as well as to aidl for this module.
2084 Export_include_dirs []string
2085 }
Colin Cross74d73e22017-08-02 11:05:49 -07002086}
2087
2088type Import struct {
Colin Cross635c3b02016-05-18 15:37:25 -07002089 android.ModuleBase
Colin Cross48de9a42018-10-02 13:53:33 -07002090 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002091 android.ApexModuleBase
Colin Crossec7a0422017-07-07 14:47:12 -07002092 prebuilt android.Prebuilt
Colin Cross2fe66872015-03-30 17:20:39 -07002093
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002094 // Functionality common to Module and Import.
2095 embeddableInModuleAndImport
2096
Liz Kammerd6c31d22020-08-05 15:40:41 -07002097 hiddenAPI
2098 dexer
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002099 dexpreopter
Liz Kammerd6c31d22020-08-05 15:40:41 -07002100
Colin Cross74d73e22017-08-02 11:05:49 -07002101 properties ImportProperties
2102
Liz Kammerd6c31d22020-08-05 15:40:41 -07002103 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002104 dexJarFile OptionalDexJarPath
Spandan Dasfae468e2023-12-12 23:23:53 +00002105 dexJarFileErr error
Jeongik Chad5fe8782021-07-08 01:13:11 +09002106 dexJarInstallFile android.Path
Liz Kammerd6c31d22020-08-05 15:40:41 -07002107
Colin Cross0a6e0072017-08-30 14:24:55 -07002108 combinedClasspathFile android.Path
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002109 classLoaderContexts dexpreopt.ClassLoaderContextMap
Jiyong Park19604de2020-03-24 16:44:11 +09002110 exportAidlIncludeDirs android.Paths
Colin Cross56a83212020-09-15 18:30:11 -07002111
2112 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +09002113
2114 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002115 minSdkVersion android.ApiLevel
Colin Cross2fe66872015-03-30 17:20:39 -07002116}
2117
Paul Duffin630b11e2021-07-15 13:35:26 +01002118var _ PermittedPackagesForUpdatableBootJars = (*Import)(nil)
2119
2120func (j *Import) PermittedPackagesForUpdatableBootJars() []string {
2121 return j.properties.Permitted_packages
2122}
2123
Jiyong Park92315372021-04-02 08:45:46 +09002124func (j *Import) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
2125 return android.SdkSpecFrom(ctx, String(j.properties.Sdk_version))
Liz Kammer2d2fd852020-08-12 14:42:30 -07002126}
2127
Jiyong Parkf1691d22021-03-29 20:11:58 +09002128func (j *Import) SystemModules() string {
Liz Kammerd6c31d22020-08-05 15:40:41 -07002129 return "none"
2130}
2131
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002132func (j *Import) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002133 if j.properties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002134 return android.ApiLevelFrom(ctx, *j.properties.Min_sdk_version)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002135 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002136 return j.SdkVersion(ctx).ApiLevel
Colin Cross83bb3162018-06-25 15:48:06 -07002137}
2138
Spandan Dasa26eda72023-03-02 00:56:06 +00002139func (j *Import) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
William Loh5a082f92022-05-17 20:21:50 +00002140 if j.properties.Replace_max_sdk_version_placeholder != nil {
Spandan Dasa26eda72023-03-02 00:56:06 +00002141 return android.ApiLevelFrom(ctx, *j.properties.Replace_max_sdk_version_placeholder)
William Loh5a082f92022-05-17 20:21:50 +00002142 }
Spandan Dasa26eda72023-03-02 00:56:06 +00002143 // Default is PrivateApiLevel
2144 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +00002145}
2146
Spandan Dasca70fc42023-03-01 23:38:49 +00002147func (j *Import) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
2148 return j.SdkVersion(ctx).ApiLevel
Artur Satayev480e25b2020-04-27 18:53:18 +01002149}
2150
Colin Cross74d73e22017-08-02 11:05:49 -07002151func (j *Import) Prebuilt() *android.Prebuilt {
Colin Crossec7a0422017-07-07 14:47:12 -07002152 return &j.prebuilt
2153}
2154
Colin Cross74d73e22017-08-02 11:05:49 -07002155func (j *Import) PrebuiltSrcs() []string {
2156 return j.properties.Jars
2157}
2158
2159func (j *Import) Name() string {
Colin Cross5ea9bcc2017-07-27 15:41:32 -07002160 return j.prebuilt.Name(j.ModuleBase.Name())
2161}
2162
Jiyong Park0b238752019-10-29 11:23:10 +09002163func (j *Import) Stem() string {
2164 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2165}
2166
Jiyong Park618922e2020-01-08 13:35:43 +09002167func (a *Import) JacocoReportClassesFile() android.Path {
2168 return nil
2169}
2170
Bill Peckhama41a6962021-01-11 10:58:54 -08002171func (j *Import) LintDepSets() LintDepSets {
2172 return LintDepSets{}
2173}
2174
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002175func (j *Import) getStrictUpdatabilityLinting() bool {
2176 return false
2177}
2178
2179func (j *Import) setStrictUpdatabilityLinting(bool) {
2180}
2181
Colin Cross74d73e22017-08-02 11:05:49 -07002182func (j *Import) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Cross42d48b72018-08-29 14:10:52 -07002183 ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002184
2185 if ctx.Device() && Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002186 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002187 }
Colin Cross1e676be2016-10-12 14:38:15 -07002188}
2189
Sam Delmerico277795c2022-02-25 17:04:37 +00002190func (j *Import) commonBuildActions(ctx android.ModuleContext) {
Jiyong Park92315372021-04-02 08:45:46 +09002191 j.sdkVersion = j.SdkVersion(ctx)
2192 j.minSdkVersion = j.MinSdkVersion(ctx)
2193
Colin Crossff694a82023-12-13 15:54:49 -08002194 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
2195 if !apexInfo.IsForPlatform() {
Colin Cross56a83212020-09-15 18:30:11 -07002196 j.hideApexVariantFromMake = true
2197 }
2198
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002199 if ctx.Windows() {
2200 j.HideFromMake()
2201 }
Sam Delmerico277795c2022-02-25 17:04:37 +00002202}
2203
2204func (j *Import) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2205 j.commonBuildActions(ctx)
Dan Willemsen8e6b3712021-09-20 23:11:24 -07002206
Colin Cross8a497952019-03-05 22:25:09 -08002207 jars := android.PathsForModuleSrc(ctx, j.properties.Jars)
Colin Crosse1d62a82015-04-03 16:53:05 -07002208
Jiyong Park0b238752019-10-29 11:23:10 +09002209 jarName := j.Stem() + ".jar"
Nan Zhang4c819fb2018-08-27 18:31:46 -07002210 outputFile := android.PathForModuleOut(ctx, "combined", jarName)
Colin Cross37f6d792018-07-12 12:28:41 -07002211 TransformJarsToJar(ctx, outputFile, "for prebuilts", jars, android.OptionalPath{},
2212 false, j.properties.Exclude_files, j.properties.Exclude_dirs)
Colin Cross1001a792019-03-21 22:21:39 -07002213 if Bool(j.properties.Jetifier) {
Nan Zhang4c819fb2018-08-27 18:31:46 -07002214 inputFile := outputFile
2215 outputFile = android.PathForModuleOut(ctx, "jetifier", jarName)
2216 TransformJetifier(ctx, outputFile, inputFile)
2217 }
Colin Crosse9a275b2017-10-16 17:09:48 -07002218 j.combinedClasspathFile = outputFile
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002219 j.classLoaderContexts = make(dexpreopt.ClassLoaderContextMap)
Paul Duffin859fe962020-05-15 10:20:31 +01002220
Liz Kammerd6c31d22020-08-05 15:40:41 -07002221 var flags javaBuilderFlags
2222
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002223 j.collectTransitiveHeaderJars(ctx)
Jiyong Park1be96912018-05-28 18:02:19 +09002224 ctx.VisitDirectDeps(func(module android.Module) {
Jiyong Park1be96912018-05-28 18:02:19 +09002225 tag := ctx.OtherModuleDependencyTag(module)
Colin Cross313aa542023-12-13 13:47:44 -08002226 if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002227 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002228 case libTag, sdkLibTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002229 flags.classpath = append(flags.classpath, dep.HeaderJars...)
2230 flags.dexClasspath = append(flags.dexClasspath, dep.HeaderJars...)
2231 case staticLibTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002232 flags.classpath = append(flags.classpath, dep.HeaderJars...)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002233 case bootClasspathTag:
Colin Crossdcf71b22021-02-01 13:59:03 -08002234 flags.bootClasspath = append(flags.bootClasspath, dep.HeaderJars...)
Jiyong Park1be96912018-05-28 18:02:19 +09002235 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002236 } else if dep, ok := module.(SdkLibraryDependency); ok {
Jiyong Park1be96912018-05-28 18:02:19 +09002237 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002238 case libTag, sdkLibTag:
Jiyong Park92315372021-04-02 08:45:46 +09002239 flags.classpath = append(flags.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jiyong Park1be96912018-05-28 18:02:19 +09002240 }
2241 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002242
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002243 addCLCFromDep(ctx, module, j.classLoaderContexts)
Jiyong Park1be96912018-05-28 18:02:19 +09002244 })
2245
Sam Delmerico277795c2022-02-25 17:04:37 +00002246 j.maybeInstall(ctx, jarName, outputFile)
Jiyong Park19604de2020-03-24 16:44:11 +09002247
2248 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.properties.Aidl.Export_include_dirs)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002249
Paul Duffin064b70c2020-11-02 17:32:38 +00002250 if ctx.Device() {
2251 // If this is a variant created for a prebuilt_apex then use the dex implementation jar
2252 // obtained from the associated deapexer module.
Colin Crossff694a82023-12-13 15:54:49 -08002253 ai, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Paul Duffin064b70c2020-11-02 17:32:38 +00002254 if ai.ForPrebuiltApex {
Paul Duffin064b70c2020-11-02 17:32:38 +00002255 // Get the path of the dex implementation jar from the `deapexer` module.
Spandan Dasfae468e2023-12-12 23:23:53 +00002256 di, err := android.FindDeapexerProviderForModule(ctx)
2257 if err != nil {
2258 // An error was found, possibly due to multiple apexes in the tree that export this library
2259 // Defer the error till a client tries to call DexJarBuildPath
2260 j.dexJarFileErr = err
Spandan Das3a392012024-01-17 18:26:27 +00002261 j.initHiddenAPIError(err)
Spandan Dasfae468e2023-12-12 23:23:53 +00002262 return
Martin Stjernholm44825602021-09-17 01:44:12 +01002263 }
Spandan Das5be63332023-12-13 00:06:32 +00002264 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(j.BaseModuleName())
Jiakai Zhang81e46812023-02-08 21:56:07 +08002265 if dexOutputPath := di.PrebuiltExportPath(dexJarFileApexRootRelative); dexOutputPath != nil {
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002266 dexJarFile := makeDexJarPathFromPath(dexOutputPath)
2267 j.dexJarFile = dexJarFile
Spandan Das5be63332023-12-13 00:06:32 +00002268 installPath := android.PathForModuleInPartitionInstall(ctx, "apex", ai.ApexVariationName, ApexRootRelativePathToJavaLib(j.BaseModuleName()))
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002269 j.dexJarInstallFile = installPath
Paul Duffin74d18d12021-05-14 14:18:47 +01002270
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002271 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(ctx, installPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002272 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002273 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
Jiakai Zhang81e46812023-02-08 21:56:07 +08002274
2275 if profilePath := di.PrebuiltExportPath(dexJarFileApexRootRelative + ".prof"); profilePath != nil {
2276 j.dexpreopter.inputProfilePathOnHost = profilePath
2277 }
2278
Jiakai Zhang5b24f722021-09-30 09:32:57 +00002279 j.dexpreopt(ctx, dexOutputPath)
Jiakai Zhang22450f22021-10-11 03:05:20 +00002280
2281 // Initialize the hiddenapi structure.
2282 j.initHiddenAPI(ctx, dexJarFile, outputFile, j.dexProperties.Uncompress_dex)
Paul Duffin9d67ca62021-02-03 20:06:33 +00002283 } else {
Paul Duffin064b70c2020-11-02 17:32:38 +00002284 // This should never happen as a variant for a prebuilt_apex is only created if the
2285 // prebuilt_apex has been configured to export the java library dex file.
Martin Stjernholm44825602021-09-17 01:44:12 +01002286 ctx.ModuleErrorf("internal error: no dex implementation jar available from prebuilt APEX %s", di.ApexModuleName())
Paul Duffin064b70c2020-11-02 17:32:38 +00002287 }
2288 } else if Bool(j.dexProperties.Compile_dex) {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002289 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Paul Duffin064b70c2020-11-02 17:32:38 +00002290 if sdkDep.invalidVersion {
2291 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2292 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2293 } else if sdkDep.useFiles {
2294 // sdkDep.jar is actually equivalent to turbine header.jar.
2295 flags.classpath = append(flags.classpath, sdkDep.jars...)
2296 }
2297
2298 // Dex compilation
2299
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002300 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2301 ctx, android.PathForModuleInstall(ctx, "framework", jarName))
Jiakai Zhang22450f22021-10-11 03:05:20 +00002302 setUncompressDex(ctx, &j.dexpreopter, &j.dexer)
Paul Duffin064b70c2020-11-02 17:32:38 +00002303 j.dexpreopter.uncompressedDex = *j.dexProperties.Uncompress_dex
2304
Paul Duffin612e6102021-02-02 13:38:13 +00002305 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00002306 dexParams := &compileDexParams{
2307 flags: flags,
2308 sdkVersion: j.SdkVersion(ctx),
2309 minSdkVersion: j.MinSdkVersion(ctx),
2310 classesJar: outputFile,
2311 jarName: jarName,
2312 }
2313
2314 dexOutputFile = j.dexer.compileDex(ctx, dexParams)
Paul Duffin064b70c2020-11-02 17:32:38 +00002315 if ctx.Failed() {
2316 return
2317 }
2318
Paul Duffin74d18d12021-05-14 14:18:47 +01002319 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002320 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), outputFile, j.dexProperties.Uncompress_dex)
Paul Duffinafaa47c2021-05-14 13:04:04 +01002321
2322 // Encode hidden API flags in dex file.
Paul Duffin1bbd0622021-05-14 15:52:25 +01002323 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
Paul Duffin064b70c2020-11-02 17:32:38 +00002324
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002325 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jeongik Chad5fe8782021-07-08 01:13:11 +09002326 j.dexJarInstallFile = android.PathForModuleInstall(ctx, "framework", jarName)
Liz Kammerd6c31d22020-08-05 15:40:41 -07002327 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002328 }
Colin Crossdcf71b22021-02-01 13:59:03 -08002329
Colin Cross40213022023-12-13 15:19:49 -08002330 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Colin Crossdcf71b22021-02-01 13:59:03 -08002331 HeaderJars: android.PathsIfNonNil(j.combinedClasspathFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002332 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
2333 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Colin Crossdcf71b22021-02-01 13:59:03 -08002334 ImplementationAndResourcesJars: android.PathsIfNonNil(j.combinedClasspathFile),
2335 ImplementationJars: android.PathsIfNonNil(j.combinedClasspathFile),
2336 AidlIncludeDirs: j.exportAidlIncludeDirs,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002337 // TODO(b/289117800): LOCAL_ACONFIG_FILES for prebuilts
Colin Crossdcf71b22021-02-01 13:59:03 -08002338 })
Colin Cross2fe66872015-03-30 17:20:39 -07002339}
2340
Sam Delmerico277795c2022-02-25 17:04:37 +00002341func (j *Import) maybeInstall(ctx android.ModuleContext, jarName string, outputFile android.Path) {
2342 if !Bool(j.properties.Installable) {
2343 return
2344 }
2345
2346 var installDir android.InstallPath
2347 if ctx.InstallInTestcases() {
2348 var archDir string
2349 if !ctx.Host() {
2350 archDir = ctx.DeviceConfig().DeviceArch()
2351 }
2352 installDir = android.PathForModuleInstall(ctx, ctx.ModuleName(), archDir)
2353 } else {
2354 installDir = android.PathForModuleInstall(ctx, "framework")
2355 }
2356 ctx.InstallFile(installDir, jarName, outputFile)
2357}
2358
Paul Duffinaa55f742020-10-06 17:20:13 +01002359func (j *Import) OutputFiles(tag string) (android.Paths, error) {
2360 switch tag {
Saeid Farivar Asanjan128fe5c2020-10-15 17:54:40 +00002361 case "", ".jar":
Paul Duffinaa55f742020-10-06 17:20:13 +01002362 return android.Paths{j.combinedClasspathFile}, nil
2363 default:
2364 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
2365 }
2366}
2367
2368var _ android.OutputFileProducer = (*Import)(nil)
2369
Nan Zhanged19fc32017-10-19 13:06:22 -07002370func (j *Import) HeaderJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002371 if j.combinedClasspathFile == nil {
2372 return nil
2373 }
Colin Cross37f6d792018-07-12 12:28:41 -07002374 return android.Paths{j.combinedClasspathFile}
Nan Zhanged19fc32017-10-19 13:06:22 -07002375}
2376
Colin Cross331a1212018-08-15 20:40:52 -07002377func (j *Import) ImplementationAndResourcesJars() android.Paths {
albaltai36ff7dc2018-12-25 14:35:23 +08002378 if j.combinedClasspathFile == nil {
2379 return nil
2380 }
Colin Cross331a1212018-08-15 20:40:52 -07002381 return android.Paths{j.combinedClasspathFile}
2382}
2383
Spandan Das59a4a2b2024-01-09 21:35:56 +00002384func (j *Import) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Spandan Dasfae468e2023-12-12 23:23:53 +00002385 if j.dexJarFileErr != nil {
Spandan Das59a4a2b2024-01-09 21:35:56 +00002386 ctx.ModuleErrorf(j.dexJarFileErr.Error())
Spandan Dasfae468e2023-12-12 23:23:53 +00002387 }
Liz Kammerd6c31d22020-08-05 15:40:41 -07002388 return j.dexJarFile
Colin Crossf24a22a2019-01-31 14:12:44 -08002389}
2390
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002391func (j *Import) DexJarInstallPath() android.Path {
Jeongik Chad5fe8782021-07-08 01:13:11 +09002392 return j.dexJarInstallFile
Ulya Trafimovich9f3052c2020-06-09 14:31:19 +01002393}
2394
Ulya Trafimovichb23d28c2020-10-08 12:53:58 +01002395func (j *Import) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2396 return j.classLoaderContexts
Jiyong Park1be96912018-05-28 18:02:19 +09002397}
2398
Jiyong Park45bf82e2020-12-15 22:29:02 +09002399var _ android.ApexModule = (*Import)(nil)
2400
2401// Implements android.ApexModule
Jiyong Park0f80c182020-01-31 02:49:53 +09002402func (j *Import) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
Paul Duffin0d3c2e12020-05-17 08:34:50 +01002403 return j.depIsInSameApex(ctx, dep)
Jiyong Park0f80c182020-01-31 02:49:53 +09002404}
2405
Jiyong Park45bf82e2020-12-15 22:29:02 +09002406// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002407func (j *Import) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2408 sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002409 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002410 minSdkVersion := j.MinSdkVersion(ctx)
2411 if !minSdkVersion.Specified() {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002412 return fmt.Errorf("min_sdk_version is not specified")
2413 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002414 // If the module is compiling against core (via sdk_version), skip comparison check.
2415 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002416 return nil
2417 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002418 if minSdkVersion.GreaterThan(sdkVersion) {
2419 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung56e12db2021-04-02 00:38:25 +00002420 }
Jooyung Han749dc692020-04-15 11:03:39 +09002421 return nil
2422}
2423
Paul Duffinfef55002021-06-17 14:56:05 +01002424// requiredFilesFromPrebuiltApexForImport returns information about the files that a java_import or
2425// java_sdk_library_import with the specified base module name requires to be exported from a
2426// prebuilt_apex/apex_set.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002427func requiredFilesFromPrebuiltApexForImport(name string, d *dexpreopter) []string {
Spandan Das5be63332023-12-13 00:06:32 +00002428 dexJarFileApexRootRelative := ApexRootRelativePathToJavaLib(name)
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002429 // Add the dex implementation jar to the set of exported files.
Jiakai Zhang81e46812023-02-08 21:56:07 +08002430 files := []string{
2431 dexJarFileApexRootRelative,
Paul Duffinfef55002021-06-17 14:56:05 +01002432 }
Jiakai Zhang81e46812023-02-08 21:56:07 +08002433 if BoolDefault(d.importDexpreoptProperties.Dex_preopt.Profile_guided, false) {
2434 files = append(files, dexJarFileApexRootRelative+".prof")
2435 }
2436 return files
Paul Duffinfef55002021-06-17 14:56:05 +01002437}
2438
Spandan Das5be63332023-12-13 00:06:32 +00002439// ApexRootRelativePathToJavaLib returns the path, relative to the root of the apex's contents, for
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002440// the java library with the specified name.
Spandan Das5be63332023-12-13 00:06:32 +00002441func ApexRootRelativePathToJavaLib(name string) string {
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002442 return filepath.Join("javalib", name+".jar")
2443}
2444
Paul Duffinfef55002021-06-17 14:56:05 +01002445var _ android.RequiredFilesFromPrebuiltApex = (*Import)(nil)
2446
Paul Duffinb4bbf2c2021-06-17 15:59:07 +01002447func (j *Import) RequiredFilesFromPrebuiltApex(_ android.BaseModuleContext) []string {
Paul Duffinfef55002021-06-17 14:56:05 +01002448 name := j.BaseModuleName()
Jiakai Zhang81e46812023-02-08 21:56:07 +08002449 return requiredFilesFromPrebuiltApexForImport(name, &j.dexpreopter)
Paul Duffinfef55002021-06-17 14:56:05 +01002450}
2451
albaltai36ff7dc2018-12-25 14:35:23 +08002452// Add compile time check for interface implementation
2453var _ android.IDEInfo = (*Import)(nil)
2454var _ android.IDECustomizedModuleName = (*Import)(nil)
2455
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002456// Collect information for opening IDE project files in java/jdeps.go.
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002457
2458func (j *Import) IDEInfo(dpInfo *android.IdeInfo) {
2459 dpInfo.Jars = append(dpInfo.Jars, j.PrebuiltSrcs()...)
2460}
2461
2462func (j *Import) IDECustomizedModuleName() string {
2463 // TODO(b/113562217): Extract the base module name from the Import name, often the Import name
2464 // has a prefix "prebuilt_". Remove the prefix explicitly if needed until we find a better
2465 // solution to get the Import name.
Ulya Trafimovich497a0932021-07-14 16:35:33 +01002466 return android.RemoveOptionalPrebuiltPrefix(j.Name())
Brandon Lee5d45c6f2018-08-15 15:35:38 -07002467}
2468
Colin Cross74d73e22017-08-02 11:05:49 -07002469var _ android.PrebuiltInterface = (*Import)(nil)
Colin Cross2fe66872015-03-30 17:20:39 -07002470
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002471func (j *Import) IsInstallable() bool {
2472 return Bool(j.properties.Installable)
2473}
2474
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002475var _ DexpreopterInterface = (*Import)(nil)
Bill Peckhamff89ffa2020-12-23 16:13:04 -08002476
Colin Cross1b16b0e2019-02-12 14:41:32 -08002477// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library module.
2478//
2479// By default, a java_import has a single variant that expects a `.jar` file containing `.class` files that were
2480// compiled against an Android classpath.
2481//
2482// Specifying `host_supported: true` will produce two variants, one for use as a dependency of device modules and one
2483// for host modules.
Colin Cross74d73e22017-08-02 11:05:49 -07002484func ImportFactory() android.Module {
2485 module := &Import{}
Colin Cross36242852017-06-23 15:06:31 -07002486
Liz Kammerd6c31d22020-08-05 15:40:41 -07002487 module.AddProperties(
2488 &module.properties,
2489 &module.dexer.dexProperties,
Jiakai Zhang9c4dc192023-02-09 00:09:24 +08002490 &module.importDexpreoptProperties,
Liz Kammerd6c31d22020-08-05 15:40:41 -07002491 )
Colin Cross74d73e22017-08-02 11:05:49 -07002492
Paul Duffin71b33cc2021-06-23 11:39:47 +01002493 module.initModuleAndImport(module)
Paul Duffin859fe962020-05-15 10:20:31 +01002494
Liz Kammerd6c31d22020-08-05 15:40:41 -07002495 module.dexProperties.Optimize.EnabledByDefault = false
2496
Colin Cross74d73e22017-08-02 11:05:49 -07002497 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002498 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002499 InitJavaModule(module, android.HostAndDeviceSupported)
Colin Cross36242852017-06-23 15:06:31 -07002500 return module
Colin Cross2fe66872015-03-30 17:20:39 -07002501}
2502
Colin Cross1b16b0e2019-02-12 14:41:32 -08002503// java_import imports one or more `.jar` files into the build graph as if they were built by a java_library_host
2504// module.
2505//
2506// A java_import_host has a single variant that expects a `.jar` file containing `.class` files that were
2507// compiled against a host bootclasspath.
Colin Cross74d73e22017-08-02 11:05:49 -07002508func ImportFactoryHost() android.Module {
2509 module := &Import{}
2510
2511 module.AddProperties(&module.properties)
2512
2513 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002514 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002515 InitJavaModule(module, android.HostSupported)
Colin Cross74d73e22017-08-02 11:05:49 -07002516 return module
2517}
2518
Colin Cross42be7612019-02-21 18:12:14 -08002519// dex_import module
2520
2521type DexImportProperties struct {
Colin Cross5cfc70d2019-07-15 13:36:55 -07002522 Jars []string `android:"path"`
Jiyong Park4c4c0242019-10-21 14:53:15 +09002523
2524 // set the name of the output
2525 Stem *string
Colin Cross42be7612019-02-21 18:12:14 -08002526}
2527
2528type DexImport struct {
2529 android.ModuleBase
2530 android.DefaultableModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002531 android.ApexModuleBase
Colin Cross42be7612019-02-21 18:12:14 -08002532 prebuilt android.Prebuilt
2533
2534 properties DexImportProperties
2535
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002536 dexJarFile OptionalDexJarPath
Colin Cross42be7612019-02-21 18:12:14 -08002537
2538 dexpreopter
Colin Cross56a83212020-09-15 18:30:11 -07002539
2540 hideApexVariantFromMake bool
Colin Cross42be7612019-02-21 18:12:14 -08002541}
2542
2543func (j *DexImport) Prebuilt() *android.Prebuilt {
2544 return &j.prebuilt
2545}
2546
2547func (j *DexImport) PrebuiltSrcs() []string {
2548 return j.properties.Jars
2549}
2550
2551func (j *DexImport) Name() string {
2552 return j.prebuilt.Name(j.ModuleBase.Name())
2553}
2554
Jiyong Park0b238752019-10-29 11:23:10 +09002555func (j *DexImport) Stem() string {
2556 return proptools.StringDefault(j.properties.Stem, j.ModuleBase.Name())
2557}
2558
Jiyong Park77acec62020-06-01 21:39:15 +09002559func (a *DexImport) JacocoReportClassesFile() android.Path {
2560 return nil
2561}
2562
Colin Cross08dca382020-07-21 20:31:17 -07002563func (a *DexImport) LintDepSets() LintDepSets {
2564 return LintDepSets{}
2565}
2566
Martin Stjernholm6d415272020-01-31 17:10:36 +00002567func (j *DexImport) IsInstallable() bool {
2568 return true
2569}
2570
Jaewoong Jung476b9d62021-05-10 15:30:00 -07002571func (j *DexImport) getStrictUpdatabilityLinting() bool {
2572 return false
2573}
2574
2575func (j *DexImport) setStrictUpdatabilityLinting(bool) {
2576}
2577
Colin Cross42be7612019-02-21 18:12:14 -08002578func (j *DexImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2579 if len(j.properties.Jars) != 1 {
2580 ctx.PropertyErrorf("jars", "exactly one jar must be provided")
2581 }
2582
Colin Crossff694a82023-12-13 15:54:49 -08002583 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Colin Cross56a83212020-09-15 18:30:11 -07002584 if !apexInfo.IsForPlatform() {
2585 j.hideApexVariantFromMake = true
2586 }
2587
Jiakai Zhang519c5c82021-09-16 06:15:39 +00002588 j.dexpreopter.installPath = j.dexpreopter.getInstallPath(
2589 ctx, android.PathForModuleInstall(ctx, "framework", j.Stem()+".jar"))
Colin Cross42be7612019-02-21 18:12:14 -08002590 j.dexpreopter.uncompressedDex = shouldUncompressDex(ctx, &j.dexpreopter)
2591
2592 inputJar := ctx.ExpandSource(j.properties.Jars[0], "jars")
2593 dexOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar")
2594
2595 if j.dexpreopter.uncompressedDex {
Colin Crossf1a035e2020-11-16 17:32:30 -08002596 rule := android.NewRuleBuilder(pctx, ctx)
Colin Cross42be7612019-02-21 18:12:14 -08002597
2598 temporary := android.PathForModuleOut(ctx, ctx.ModuleName()+".jar.unaligned")
2599 rule.Temporary(temporary)
2600
2601 // use zip2zip to uncompress classes*.dex files
2602 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002603 BuiltTool("zip2zip").
Colin Cross42be7612019-02-21 18:12:14 -08002604 FlagWithInput("-i ", inputJar).
2605 FlagWithOutput("-o ", temporary).
2606 FlagWithArg("-0 ", "'classes*.dex'")
2607
2608 // use zipalign to align uncompressed classes*.dex files
2609 rule.Command().
Colin Crossf1a035e2020-11-16 17:32:30 -08002610 BuiltTool("zipalign").
Colin Cross42be7612019-02-21 18:12:14 -08002611 Flag("-f").
2612 Text("4").
2613 Input(temporary).
2614 Output(dexOutputFile)
2615
2616 rule.DeleteTemporaryFiles()
2617
Colin Crossf1a035e2020-11-16 17:32:30 -08002618 rule.Build("uncompress_dex", "uncompress dex")
Colin Cross42be7612019-02-21 18:12:14 -08002619 } else {
2620 ctx.Build(pctx, android.BuildParams{
2621 Rule: android.Cp,
2622 Input: inputJar,
2623 Output: dexOutputFile,
2624 })
2625 }
2626
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01002627 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002628
Jaewoong Jung4b97a562020-12-17 09:43:28 -08002629 j.dexpreopt(ctx, dexOutputFile)
Colin Cross42be7612019-02-21 18:12:14 -08002630
Colin Cross56a83212020-09-15 18:30:11 -07002631 if apexInfo.IsForPlatform() {
Jiyong Park01bca752020-06-08 19:24:09 +09002632 ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
2633 j.Stem()+".jar", dexOutputFile)
2634 }
Colin Cross42be7612019-02-21 18:12:14 -08002635}
2636
Spandan Das59a4a2b2024-01-09 21:35:56 +00002637func (j *DexImport) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Colin Cross42be7612019-02-21 18:12:14 -08002638 return j.dexJarFile
2639}
2640
Jiyong Park45bf82e2020-12-15 22:29:02 +09002641var _ android.ApexModule = (*DexImport)(nil)
2642
2643// Implements android.ApexModule
Dan Albertc8060532020-07-22 22:32:17 -07002644func (j *DexImport) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
2645 sdkVersion android.ApiLevel) error {
Jooyung Han749dc692020-04-15 11:03:39 +09002646 // we don't check prebuilt modules for sdk_version
2647 return nil
2648}
2649
Colin Cross42be7612019-02-21 18:12:14 -08002650// dex_import imports a `.jar` file containing classes.dex files.
2651//
2652// A dex_import module cannot be used as a dependency of a java_* or android_* module, it can only be installed
2653// to the device.
2654func DexImportFactory() android.Module {
2655 module := &DexImport{}
2656
2657 module.AddProperties(&module.properties)
2658
2659 android.InitPrebuiltModule(module, &module.properties.Jars)
Jiyong Park7f7766d2019-07-25 22:02:35 +09002660 android.InitApexModule(module)
Jooyung Han18020ea2019-11-13 10:50:48 +09002661 InitJavaModule(module, android.DeviceSupported)
Colin Cross42be7612019-02-21 18:12:14 -08002662 return module
2663}
2664
Colin Cross89536d42017-07-07 14:35:50 -07002665// Defaults
Colin Cross89536d42017-07-07 14:35:50 -07002666type Defaults struct {
2667 android.ModuleBase
2668 android.DefaultsModuleBase
Jiyong Park7f7766d2019-07-25 22:02:35 +09002669 android.ApexModuleBase
Colin Cross89536d42017-07-07 14:35:50 -07002670}
2671
Colin Cross1b16b0e2019-02-12 14:41:32 -08002672// java_defaults provides a set of properties that can be inherited by other java or android modules.
2673//
2674// A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`. Each
2675// property in the defaults module that exists in the depending module will be prepended to the depending module's
2676// value for that property.
2677//
2678// Example:
2679//
Sam Delmerico277795c2022-02-25 17:04:37 +00002680// java_defaults {
2681// name: "example_defaults",
2682// srcs: ["common/**/*.java"],
2683// javacflags: ["-Xlint:all"],
2684// aaptflags: ["--auto-add-overlay"],
2685// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002686//
Sam Delmerico277795c2022-02-25 17:04:37 +00002687// java_library {
2688// name: "example",
2689// defaults: ["example_defaults"],
2690// srcs: ["example/**/*.java"],
2691// }
Colin Cross1b16b0e2019-02-12 14:41:32 -08002692//
2693// is functionally identical to:
2694//
Sam Delmerico277795c2022-02-25 17:04:37 +00002695// java_library {
2696// name: "example",
2697// srcs: [
2698// "common/**/*.java",
2699// "example/**/*.java",
2700// ],
2701// javacflags: ["-Xlint:all"],
2702// }
Paul Duffin47357662019-12-05 14:07:14 +00002703func DefaultsFactory() android.Module {
Colin Cross89536d42017-07-07 14:35:50 -07002704 module := &Defaults{}
2705
Colin Cross89536d42017-07-07 14:35:50 -07002706 module.AddProperties(
Jaewoong Jungbc15e3a2021-03-10 17:02:43 -08002707 &CommonProperties{},
2708 &DeviceProperties{},
Jooyung Han01d80d82022-01-08 12:16:32 +09002709 &OverridableDeviceProperties{},
Liz Kammera7a64f32020-07-09 15:16:41 -07002710 &DexProperties{},
Colin Cross43f08db2018-11-12 10:13:39 -08002711 &DexpreoptProperties{},
Dan Willemsen6424d172018-03-08 13:27:59 -08002712 &android.ProtoProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002713 &aaptProperties{},
2714 &androidLibraryProperties{},
2715 &appProperties{},
2716 &appTestProperties{},
Jaewoong Jung525443a2019-02-28 15:35:54 -08002717 &overridableAppProperties{},
Kun Niubd0fd202023-05-23 17:51:44 +00002718 &hostTestProperties{},
Roland Levillainb5b0ff32020-02-04 15:45:49 +00002719 &testProperties{},
Colin Cross48de9a42018-10-02 13:53:33 -07002720 &ImportProperties{},
2721 &AARImportProperties{},
2722 &sdkLibraryProperties{},
Paul Duffin1b1e8062020-05-08 13:44:43 +01002723 &commonToSdkLibraryAndImportProperties{},
Colin Cross42be7612019-02-21 18:12:14 -08002724 &DexImportProperties{},
Jooyung Han18020ea2019-11-13 10:50:48 +09002725 &android.ApexProperties{},
Jaewoong Jungbf135462020-04-26 15:10:51 -07002726 &RuntimeResourceOverlayProperties{},
Colin Cross014489c2020-06-02 20:09:13 -07002727 &LintProperties{},
Colin Crosscbce0b02021-02-09 10:38:30 -08002728 &appTestHelperAppProperties{},
Jihoon Kang1c51f502023-01-09 23:42:40 +00002729 &JavaApiLibraryProperties{},
Colin Cross89536d42017-07-07 14:35:50 -07002730 )
2731
2732 android.InitDefaultsModule(module)
Colin Cross89536d42017-07-07 14:35:50 -07002733 return module
2734}
Nan Zhangea568a42017-11-08 21:20:04 -08002735
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002736func kytheExtractJavaFactory() android.Singleton {
2737 return &kytheExtractJavaSingleton{}
2738}
2739
2740type kytheExtractJavaSingleton struct {
2741}
2742
2743func (ks *kytheExtractJavaSingleton) GenerateBuildActions(ctx android.SingletonContext) {
2744 var xrefTargets android.Paths
2745 ctx.VisitAllModules(func(module android.Module) {
2746 if javaModule, ok := module.(xref); ok {
2747 xrefTargets = append(xrefTargets, javaModule.XrefJavaFiles()...)
2748 }
2749 })
2750 // TODO(asmundak): perhaps emit a rule to output a warning if there were no xrefTargets
2751 if len(xrefTargets) > 0 {
Colin Crossc3d87d32020-06-04 13:25:17 -07002752 ctx.Phony("xref_java", xrefTargets...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -08002753 }
2754}
2755
Nan Zhangea568a42017-11-08 21:20:04 -08002756var Bool = proptools.Bool
Colin Cross38b40df2018-04-10 16:14:46 -07002757var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -08002758var String = proptools.String
Sam Delmerico1717b3b2023-07-18 15:07:24 -04002759var inList = android.InList[string]
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002760
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002761// Add class loader context (CLC) of a given dependency to the current CLC.
2762func addCLCFromDep(ctx android.ModuleContext, depModule android.Module,
2763 clcMap dexpreopt.ClassLoaderContextMap) {
2764
2765 dep, ok := depModule.(UsesLibraryDependency)
2766 if !ok {
2767 return
2768 }
2769
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002770 depName := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(depModule))
2771
2772 var sdkLib *string
2773 if lib, ok := depModule.(SdkLibraryDependency); ok && lib.sharedLibrary() {
2774 // A shared SDK library. This should be added as a top-level CLC element.
2775 sdkLib = &depName
2776 } else if ulib, ok := depModule.(ProvidesUsesLib); ok {
2777 // A non-SDK library disguised as an SDK library by the means of `provides_uses_lib`
2778 // property. This should be handled in the same way as a shared SDK library.
2779 sdkLib = ulib.ProvidesUsesLib()
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002780 }
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002781
2782 depTag := ctx.OtherModuleDependencyTag(depModule)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002783 if IsLibDepTag(depTag) {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002784 // Ok, propagate <uses-library> through non-static library dependencies.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002785 } else if tag, ok := depTag.(usesLibraryDependencyTag); ok && tag.sdkVersion == dexpreopt.AnySdkVersion {
2786 // Ok, propagate <uses-library> through non-compatibility <uses-library> dependencies.
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002787 } else if depTag == staticLibTag {
2788 // Propagate <uses-library> through static library dependencies, unless it is a component
2789 // library (such as stubs). Component libraries have a dependency on their SDK library,
2790 // which should not be pulled just because of a static component library.
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002791 if sdkLib != nil {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002792 return
2793 }
2794 } else {
2795 // Don't propagate <uses-library> for other dependency tags.
2796 return
2797 }
2798
Ulya Trafimovich840efb62021-07-15 14:34:40 +01002799 // If this is an SDK (or SDK-like) library, then it should be added as a node in the CLC tree,
2800 // and its CLC should be added as subtree of that node. Otherwise the library is not a
2801 // <uses_library> and should not be added to CLC, but the transitive <uses-library> dependencies
2802 // from its CLC should be added to the current CLC.
2803 if sdkLib != nil {
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +01002804 clcMap.AddContext(ctx, dexpreopt.AnySdkVersion, *sdkLib, false,
Spandan Das59a4a2b2024-01-09 21:35:56 +00002805 dep.DexJarBuildPath(ctx).PathOrNil(), dep.DexJarInstallPath(), dep.ClassLoaderContexts())
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002806 } else {
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +00002807 clcMap.AddContextMap(dep.ClassLoaderContexts(), depName)
2808 }
Ulya Trafimovich65b03192020-12-03 16:50:22 +00002809}
Wei Libafb6d62021-12-10 03:14:59 -08002810
Jihoon Kangfdf32362023-09-12 00:36:43 +00002811type JavaApiContributionImport struct {
2812 JavaApiContribution
2813
2814 prebuilt android.Prebuilt
2815}
2816
2817func ApiContributionImportFactory() android.Module {
2818 module := &JavaApiContributionImport{}
2819 android.InitAndroidModule(module)
2820 android.InitDefaultableModule(module)
2821 android.InitPrebuiltModule(module, &[]string{""})
2822 module.AddProperties(&module.properties)
Spandan Das2cc80ba2023-10-27 17:21:52 +00002823 module.AddProperties(&module.sdkLibraryComponentProperties)
Jihoon Kangfdf32362023-09-12 00:36:43 +00002824 return module
2825}
2826
2827func (module *JavaApiContributionImport) Prebuilt() *android.Prebuilt {
2828 return &module.prebuilt
2829}
2830
2831func (module *JavaApiContributionImport) Name() string {
2832 return module.prebuilt.Name(module.ModuleBase.Name())
2833}
2834
2835func (ap *JavaApiContributionImport) GenerateAndroidBuildActions(ctx android.ModuleContext) {
2836 ap.JavaApiContribution.GenerateAndroidBuildActions(ctx)
2837}