blob: cb08ef3800c4c5ee853e4001f965a81f2821b3e7 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 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
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
Chris Parsons39a16972023-06-08 14:28:51 +000023 "android/soong/ui/metrics/bp2build_metrics_proto"
Jaewoong Jung26342642021-03-17 15:56:23 -070024 "github.com/google/blueprint/pathtools"
25 "github.com/google/blueprint/proptools"
26
27 "android/soong/android"
28 "android/soong/dexpreopt"
29 "android/soong/java/config"
30)
31
32// This file contains the definition and the implementation of the base module that most
33// source-based Java module structs embed.
34
35// TODO:
36// Autogenerated files:
37// Renderscript
38// Post-jar passes:
39// Proguard
40// Rmtypedefs
41// DroidDoc
42// Findbugs
43
44// Properties that are common to most Java modules, i.e. whether it's a host or device module.
45type CommonProperties struct {
46 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
47 // or .aidl files.
48 Srcs []string `android:"path,arch_variant"`
49
50 // list Kotlin of source files containing Kotlin code that should be treated as common code in
51 // a codebase that supports Kotlin multiplatform. See
52 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
53 Common_srcs []string `android:"path,arch_variant"`
54
55 // list of source files that should not be used to build the Java module.
56 // This is most useful in the arch/multilib variants to remove non-common files
57 Exclude_srcs []string `android:"path,arch_variant"`
58
59 // list of directories containing Java resources
60 Java_resource_dirs []string `android:"arch_variant"`
61
62 // list of directories that should be excluded from java_resource_dirs
63 Exclude_java_resource_dirs []string `android:"arch_variant"`
64
65 // list of files to use as Java resources
66 Java_resources []string `android:"path,arch_variant"`
67
68 // list of files that should be excluded from java_resources and java_resource_dirs
69 Exclude_java_resources []string `android:"path,arch_variant"`
70
71 // list of module-specific flags that will be used for javac compiles
72 Javacflags []string `android:"arch_variant"`
73
74 // list of module-specific flags that will be used for kotlinc compiles
75 Kotlincflags []string `android:"arch_variant"`
76
77 // list of java libraries that will be in the classpath
78 Libs []string `android:"arch_variant"`
79
80 // list of java libraries that will be compiled into the resulting jar
81 Static_libs []string `android:"arch_variant"`
82
Jihoon Kang381c2fa2023-06-01 22:17:32 +000083 // list of java libraries that should not be used to build this module
84 Exclude_static_libs []string `android:"arch_variant"`
85
Jaewoong Jung26342642021-03-17 15:56:23 -070086 // manifest file to be included in resulting jar
87 Manifest *string `android:"path"`
88
89 // if not blank, run jarjar using the specified rules file
90 Jarjar_rules *string `android:"path,arch_variant"`
91
92 // If not blank, set the java version passed to javac as -source and -target
93 Java_version *string
94
95 // If set to true, allow this module to be dexed and installed on devices. Has no
96 // effect on host modules, which are always considered installable.
97 Installable *bool
98
99 // If set to true, include sources used to compile the module in to the final jar
100 Include_srcs *bool
101
102 // If not empty, classes are restricted to the specified packages and their sub-packages.
103 // This restriction is checked after applying jarjar rules and including static libs.
104 Permitted_packages []string
105
106 // List of modules to use as annotation processors
107 Plugins []string
108
109 // List of modules to export to libraries that directly depend on this library as annotation
110 // processors. Note that if the plugins set generates_api: true this will disable the turbine
111 // optimization on modules that depend on this module, which will reduce parallelism and cause
112 // more recompilation.
113 Exported_plugins []string
114
115 // The number of Java source entries each Javac instance can process
116 Javac_shard_size *int64
117
118 // Add host jdk tools.jar to bootclasspath
119 Use_tools_jar *bool
120
121 Openjdk9 struct {
122 // List of source files that should only be used when passing -source 1.9 or higher
123 Srcs []string `android:"path"`
124
125 // List of javac flags that should only be used when passing -source 1.9 or higher
126 Javacflags []string
127 }
128
129 // When compiling language level 9+ .java code in packages that are part of
130 // a system module, patch_module names the module that your sources and
131 // dependencies should be patched into. The Android runtime currently
132 // doesn't implement the JEP 261 module system so this option is only
133 // supported at compile time. It should only be needed to compile tests in
134 // packages that exist in libcore and which are inconvenient to move
135 // elsewhere.
136 Patch_module *string `android:"arch_variant"`
137
138 Jacoco struct {
139 // List of classes to include for instrumentation with jacoco to collect coverage
140 // information at runtime when building with coverage enabled. If unset defaults to all
141 // classes.
142 // Supports '*' as the last character of an entry in the list as a wildcard match.
143 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
144 // it matches classes in the package that have the class name as a prefix.
145 Include_filter []string
146
147 // List of classes to exclude from instrumentation with jacoco to collect coverage
148 // information at runtime when building with coverage enabled. Overrides classes selected
149 // by the include_filter property.
150 // Supports '*' as the last character of an entry in the list as a wildcard match.
151 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
152 // it matches classes in the package that have the class name as a prefix.
153 Exclude_filter []string
154 }
155
156 Errorprone struct {
157 // List of javac flags that should only be used when running errorprone.
158 Javacflags []string
159
160 // List of java_plugin modules that provide extra errorprone checks.
161 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700162
Cole Faust2b1536e2021-06-18 12:25:54 -0700163 // This property can be in 3 states. When set to true, errorprone will
164 // be run during the regular build. When set to false, errorprone will
165 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
166 // environment variable is true. Setting this to false will improve build
167 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700168 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700169 }
170
171 Proto struct {
172 // List of extra options that will be passed to the proto generator.
173 Output_params []string
174 }
175
Sam Delmericoc7593722022-08-31 15:57:52 -0400176 // If true, then jacocoagent is automatically added as a libs dependency so that
177 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700178 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000179 // If true, then the module supports statically including the jacocoagent
180 // into the library.
181 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700182
183 // List of files to include in the META-INF/services folder of the resulting jar.
184 Services []string `android:"path,arch_variant"`
185
186 // If true, package the kotlin stdlib into the jar. Defaults to true.
187 Static_kotlin_stdlib *bool `android:"arch_variant"`
188
189 // A list of java_library instances that provide additional hiddenapi annotations for the library.
190 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700191
192 // Additional srcJars tacked in by GeneratedJavaLibraryModule
193 Generated_srcjars []android.Path `android:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700194}
195
196// Properties that are specific to device modules. Host module factories should not add these when
197// constructing a new module.
198type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000199 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000200 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000201 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000202 // 1) numerical API level, "current", "none", or "core_platform"
203 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
204 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
205 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Sdk_version *string
207
208 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000209 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700210 Min_sdk_version *string
211
satayev0a420e72021-11-29 17:25:52 +0000212 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
213 // Defaults to empty string "". See sdk_version for possible values.
214 Max_sdk_version *string
215
William Loh5a082f92022-05-17 20:21:50 +0000216 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
217 // Defaults to empty string "". See sdk_version for possible values.
218 Replace_max_sdk_version_placeholder *string
219
Jaewoong Jung26342642021-03-17 15:56:23 -0700220 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000221 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700222 Target_sdk_version *string
223
224 // Whether to compile against the platform APIs instead of an SDK.
225 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000226 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700227 Platform_apis *bool
228
229 Aidl struct {
230 // Top level directories to pass to aidl tool
231 Include_dirs []string
232
233 // Directories rooted at the Android.bp file to pass to aidl tool
234 Local_include_dirs []string
235
236 // directories that should be added as include directories for any aidl sources of modules
237 // that depend on this module, as well as to aidl for this module.
238 Export_include_dirs []string
239
240 // whether to generate traces (for systrace) for this interface
241 Generate_traces *bool
242
243 // whether to generate Binder#GetTransaction name method.
244 Generate_get_transaction_name *bool
245
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100246 // whether all interfaces should be annotated with required permissions.
247 Enforce_permissions *bool
248
249 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
250 Enforce_permissions_exceptions []string `android:"path"`
251
Jaewoong Jung26342642021-03-17 15:56:23 -0700252 // list of flags that will be passed to the AIDL compiler
253 Flags []string
254 }
255
256 // If true, export a copy of the module as a -hostdex module for host testing.
257 Hostdex *bool
258
259 Target struct {
260 Hostdex struct {
261 // Additional required dependencies to add to -hostdex modules.
262 Required []string
263 }
264 }
265
266 // When targeting 1.9 and above, override the modules to use with --system,
267 // otherwise provides defaults libraries to add to the bootclasspath.
268 System_modules *string
269
Jaewoong Jung26342642021-03-17 15:56:23 -0700270 IsSDKLibrary bool `blueprint:"mutated"`
271
272 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
273 // Defaults to false.
274 V4_signature *bool
275
276 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
277 // public stubs library.
278 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000279
280 HiddenAPIPackageProperties
281 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700282}
283
Jooyung Han01d80d82022-01-08 12:16:32 +0900284// Device properties that can be overridden by overriding module (e.g. override_android_app)
285type OverridableDeviceProperties struct {
286 // set the name of the output. If not set, `name` is used.
287 // To override a module with this property set, overriding module might need to set this as well.
288 // Otherwise, both the overridden and the overriding modules will have the same output name, which
289 // can cause the duplicate output error.
290 Stem *string
291}
292
Jaewoong Jung26342642021-03-17 15:56:23 -0700293// Functionality common to Module and Import
294//
295// It is embedded in Module so its functionality can be used by methods in Module
296// but it is currently only initialized by Import and Library.
297type embeddableInModuleAndImport struct {
298
299 // Functionality related to this being used as a component of a java_sdk_library.
300 EmbeddableSdkLibraryComponent
301}
302
Paul Duffin71b33cc2021-06-23 11:39:47 +0100303func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
304 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700305}
306
307// Module/Import's DepIsInSameApex(...) delegates to this method.
308//
309// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
310// the one provided by ApexModuleBase.
311func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
312 // dependencies other than the static linkage are all considered crossing APEX boundary
313 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
314 return true
315 }
316 return false
317}
318
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100319// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
320// or an invalid path describing the reason it is invalid.
321//
322// It is unset if a dex jar isn't applicable, i.e. no build rule has been
323// requested to create one.
324//
325// If a dex jar has been requested to be built then it is set, and it may be
326// either a valid android.Path, or invalid with a reason message. The latter
327// happens if the source that should produce the dex file isn't able to.
328//
329// E.g. it is invalid with a reason message if there is a prebuilt APEX that
330// could produce the dex jar through a deapexer module, but the APEX isn't
331// installable so doing so wouldn't be safe.
332type OptionalDexJarPath struct {
333 isSet bool
334 path android.OptionalPath
335}
336
337// IsSet returns true if a path has been set, either invalid or valid.
338func (o OptionalDexJarPath) IsSet() bool {
339 return o.isSet
340}
341
342// Valid returns true if there is a path that is valid.
343func (o OptionalDexJarPath) Valid() bool {
344 return o.isSet && o.path.Valid()
345}
346
347// Path returns the valid path, or panics if it's either not set or is invalid.
348func (o OptionalDexJarPath) Path() android.Path {
349 if !o.isSet {
350 panic("path isn't set")
351 }
352 return o.path.Path()
353}
354
355// PathOrNil returns the path if it's set and valid, or else nil.
356func (o OptionalDexJarPath) PathOrNil() android.Path {
357 if o.Valid() {
358 return o.Path()
359 }
360 return nil
361}
362
363// InvalidReason returns the reason for an invalid path, which is never "". It
364// returns "" for an unset or valid path.
365func (o OptionalDexJarPath) InvalidReason() string {
366 if !o.isSet {
367 return ""
368 }
369 return o.path.InvalidReason()
370}
371
372func (o OptionalDexJarPath) String() string {
373 if !o.isSet {
374 return "<unset>"
375 }
376 return o.path.String()
377}
378
379// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
380func makeUnsetDexJarPath() OptionalDexJarPath {
381 return OptionalDexJarPath{isSet: false}
382}
383
384// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
385// the given OptionalPath, which may be valid or invalid.
386func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
387 return OptionalDexJarPath{isSet: true, path: path}
388}
389
390// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
391// valid given path. It returns an unset OptionalDexJarPath if the given path is
392// nil.
393func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
394 if path == nil {
395 return makeUnsetDexJarPath()
396 }
397 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
398}
399
Jaewoong Jung26342642021-03-17 15:56:23 -0700400// Module contains the properties and members used by all java module types
401type Module struct {
402 android.ModuleBase
403 android.DefaultableModuleBase
404 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800405 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700406
407 // Functionality common to Module and Import.
408 embeddableInModuleAndImport
409
410 properties CommonProperties
411 protoProperties android.ProtoProperties
412 deviceProperties DeviceProperties
413
Jooyung Han01d80d82022-01-08 12:16:32 +0900414 overridableDeviceProperties OverridableDeviceProperties
415
Jaewoong Jung26342642021-03-17 15:56:23 -0700416 // jar file containing header classes including static library dependencies, suitable for
417 // inserting into the bootclasspath/classpath of another compile
418 headerJarFile android.Path
419
420 // jar file containing implementation classes including static library dependencies but no
421 // resources
422 implementationJarFile android.Path
423
424 // jar file containing only resources including from static library dependencies
425 resourceJar android.Path
426
427 // args and dependencies to package source files into a srcjar
428 srcJarArgs []string
429 srcJarDeps android.Paths
430
431 // jar file containing implementation classes and resources including static library
432 // dependencies
433 implementationAndResourcesJar android.Path
434
435 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100436 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700437
438 // output file containing uninstrumented classes that will be instrumented by jacoco
439 jacocoReportClassesFile android.Path
440
441 // output file of the module, which may be a classes jar or a dex jar
442 outputFile android.Path
443 extraOutputFiles android.Paths
444
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100445 exportAidlIncludeDirs android.Paths
446 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700447
448 logtagsSrcs android.Paths
449
450 // installed file for binary dependency
451 installFile android.Path
452
Colin Cross3108ce12021-11-10 14:38:50 -0800453 // installed file for hostdex copy
454 hostdexInstallFile android.InstallPath
455
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800456 // list of unique .java and .kt source files
457 uniqueSrcFiles android.Paths
458
459 // list of srcjars that was passed to javac
460 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700461
462 // manifest file to use instead of properties.Manifest
463 overrideManifest android.OptionalPath
464
Jaewoong Jung26342642021-03-17 15:56:23 -0700465 // list of plugins that this java module is exporting
466 exportedPluginJars android.Paths
467
468 // list of plugins that this java module is exporting
469 exportedPluginClasses []string
470
471 // if true, the exported plugins generate API and require disabling turbine.
472 exportedDisableTurbine bool
473
474 // list of source files, collected from srcFiles with unique java and all kt files,
475 // will be used by android.IDEInfo struct
476 expandIDEInfoCompiledSrcs []string
477
478 // expanded Jarjar_rules
479 expandJarjarRules android.Path
480
Jaewoong Jung26342642021-03-17 15:56:23 -0700481 // Extra files generated by the module type to be added as java resources.
482 extraResources android.Paths
483
484 hiddenAPI
485 dexer
486 dexpreopter
487 usesLibrary
488 linter
489
490 // list of the xref extraction files
491 kytheFiles android.Paths
492
493 // Collect the module directory for IDE info in java/jdeps.go.
494 modulePaths []string
495
496 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900497
498 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000499 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000500 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400501
502 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000503
504 annoSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700505}
506
Jiyong Park92315372021-04-02 08:45:46 +0900507func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
508 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900509 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700510 return nil
511 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900512 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000513 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700514 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
515 } else {
516 // Treat stable core platform as stable.
517 return nil
518 }
519 } else {
520 return fmt.Errorf("non stable SDK %v", sdkVersion)
521 }
522}
523
524// checkSdkVersions enforces restrictions around SDK dependencies.
525func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
526 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900527 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900528 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700529 ctx.PropertyErrorf("sdk_version",
530 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
531 }
532 }
533 }
534
535 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
536 // See rank() for details.
537 ctx.VisitDirectDeps(func(module android.Module) {
538 tag := ctx.OtherModuleDependencyTag(module)
539 switch module.(type) {
540 // TODO(satayev): cover other types as well, e.g. imports
541 case *Library, *AndroidLibrary:
542 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400543 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700544 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
545 }
546 }
547 })
548}
549
550func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900551 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700552 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900553 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700554 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000555 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
Jaewoong Jung26342642021-03-17 15:56:23 -0700556 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000557 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
Jaewoong Jung26342642021-03-17 15:56:23 -0700558 }
559
560 }
561}
562
563func (j *Module) addHostProperties() {
564 j.AddProperties(
565 &j.properties,
566 &j.protoProperties,
567 &j.usesLibraryProperties,
568 )
569}
570
571func (j *Module) addHostAndDeviceProperties() {
572 j.addHostProperties()
573 j.AddProperties(
574 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900575 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700576 &j.dexer.dexProperties,
577 &j.dexpreoptProperties,
578 &j.linter.properties,
579 )
580}
581
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000582// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
583// makes it available through the hiddenAPIPropertyInfoProvider.
584func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
585 hiddenAPIInfo := newHiddenAPIPropertyInfo()
586
587 // Populate with flag file paths from the properties.
588 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
589
590 // Populate with package rules from the properties.
591 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
592
593 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
594}
595
Jaewoong Jung26342642021-03-17 15:56:23 -0700596func (j *Module) OutputFiles(tag string) (android.Paths, error) {
597 switch tag {
598 case "":
599 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
600 case android.DefaultDistTag:
601 return android.Paths{j.outputFile}, nil
602 case ".jar":
603 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700604 case ".hjar":
605 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700606 case ".proguard_map":
607 if j.dexer.proguardDictionary.Valid() {
608 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
609 }
610 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
611 default:
612 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
613 }
614}
615
616var _ android.OutputFileProducer = (*Module)(nil)
617
618func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
619 initJavaModule(module, hod, false)
620}
621
622func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
623 initJavaModule(module, hod, true)
624}
625
626func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
627 multilib := android.MultilibCommon
628 if multiTargets {
629 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
630 } else {
631 android.InitAndroidArchModule(module, hod, multilib)
632 }
633 android.InitDefaultableModule(module)
634}
635
636func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
637 return j.properties.Instrument &&
638 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
639 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
640}
641
642func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000643 return j.properties.Supports_static_instrumentation &&
644 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700645 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
646 ctx.Config().UnbundledBuild())
647}
648
649func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
650 // Force enable the instrumentation for java code that is built for APEXes ...
651 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
652 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
653 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
654 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
655 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
656 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
657 return true
658 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
659 return true
660 }
661 }
662 return false
663}
664
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400665func (j *Module) setInstrument(value bool) {
666 j.properties.Instrument = value
667}
668
Jiyong Park92315372021-04-02 08:45:46 +0900669func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
670 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700671}
672
Jiyong Parkf1691d22021-03-29 20:11:58 +0900673func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700674 return proptools.String(j.deviceProperties.System_modules)
675}
676
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000677func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700678 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000679 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700680 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000681 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700682}
683
Spandan Dasa26eda72023-03-02 00:56:06 +0000684func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
685 if j.deviceProperties.Max_sdk_version != nil {
686 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
687 }
688 // Default is PrivateApiLevel
689 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000690}
691
Spandan Dasa26eda72023-03-02 00:56:06 +0000692func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
693 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
694 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
695 }
696 // Default is PrivateApiLevel
697 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000698}
699
Jiyong Parkf1691d22021-03-29 20:11:58 +0900700func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000701 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900702}
703
Spandan Dasca70fc42023-03-01 23:38:49 +0000704func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900705 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000706 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900707 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000708 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700709}
710
711func (j *Module) AvailableFor(what string) bool {
712 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
713 // Exception: for hostdex: true libraries, the platform variant is created
714 // even if it's not marked as available to platform. In that case, the platform
715 // variant is used only for the hostdex and not installed to the device.
716 return true
717 }
718 return j.ApexModuleBase.AvailableFor(what)
719}
720
721func (j *Module) deps(ctx android.BottomUpMutatorContext) {
722 if ctx.Device() {
723 j.linter.deps(ctx)
724
Jiyong Parkf1691d22021-03-29 20:11:58 +0900725 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700726
727 if j.deviceProperties.SyspropPublicStub != "" {
728 // This is a sysprop implementation library that has a corresponding sysprop public
729 // stubs library, and a dependency on it so that dependencies on the implementation can
730 // be forwarded to the public stubs library when necessary.
731 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
732 }
733 }
734
735 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000736
737 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700738 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
739
740 // Add dependency on libraries that provide additional hidden api annotations.
741 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
742
743 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
744 // Require java_sdk_library at inter-partition java dependency to ensure stable
745 // interface between partitions. If inter-partition java_library dependency is detected,
746 // raise build error because java_library doesn't have a stable interface.
747 //
748 // Inputs:
749 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
750 // if true, enable enforcement
751 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
752 // exception list of java_library names to allow inter-partition dependency
753 for idx := range j.properties.Libs {
754 if libDeps[idx] == nil {
755 continue
756 }
757
758 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
759 // java_sdk_library is always allowed at inter-partition dependency.
760 // So, skip check.
761 if _, ok := javaDep.(*SdkLibrary); ok {
762 continue
763 }
764
765 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
766 }
767 }
768 }
769
770 // For library dependencies that are component libraries (like stubs), add the implementation
771 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
772 for _, dep := range libDeps {
773 if dep != nil {
774 if component, ok := dep.(SdkLibraryComponentDependency); ok {
775 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100776 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100777 tag := usesLibReqTag
778 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
779 tag = usesLibOptTag
780 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100781 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700782 }
783 }
784 }
785 }
786
787 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
788 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
789 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
790
791 android.ProtoDeps(ctx, &j.protoProperties)
792 if j.hasSrcExt(".proto") {
793 protoDeps(ctx, &j.protoProperties)
794 }
795
796 if j.hasSrcExt(".kt") {
797 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
798 // Kotlin files
799 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
800 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700801 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700802 }
803
804 // Framework libraries need special handling in static coverage builds: they should not have
805 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
806 // the same jacoco classes coming from different bootclasspath jars.
807 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
808 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
809 j.properties.Instrument = true
810 }
811 } else if j.shouldInstrumentStatic(ctx) {
812 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
813 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700814
815 if j.useCompose() {
816 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
817 "androidx.compose.compiler_compiler-hosted")
818 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700819}
820
821func hasSrcExt(srcs []string, ext string) bool {
822 for _, src := range srcs {
823 if filepath.Ext(src) == ext {
824 return true
825 }
826 }
827
828 return false
829}
830
831func (j *Module) hasSrcExt(ext string) bool {
832 return hasSrcExt(j.properties.Srcs, ext)
833}
834
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100835func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
836 var flags string
837
838 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
839 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
840 flags = "-Wmissing-permission-annotation -Werror"
841 }
842 }
843 return flags
844}
845
Jaewoong Jung26342642021-03-17 15:56:23 -0700846func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000847 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700848
849 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
850 aidlIncludes = append(aidlIncludes,
851 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
852 aidlIncludes = append(aidlIncludes,
853 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
854
855 var flags []string
856 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000857 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700858
859 flags = append(flags, j.deviceProperties.Aidl.Flags...)
860
861 if aidlPreprocess.Valid() {
862 flags = append(flags, "-p"+aidlPreprocess.String())
863 deps = append(deps, aidlPreprocess.Path())
864 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000865 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700866 }
867
868 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000869 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700870 }
871
872 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000873 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700874 }
875
Sam Delmerico2351eac2022-05-24 17:10:02 +0000876 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700877 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000878 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700879 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000880 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
881 // add flags for dirs containing AIDL srcs that haven't been specified yet
882 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700883
Zim8774ae12022-08-17 11:46:34 +0100884 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000885 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100886 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700887 flags = append(flags, "-t")
888 }
889
890 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
891 flags = append(flags, "--transaction_names")
892 }
893
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100894 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
895 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
896 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
897 }
898
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000899 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900900 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
901
Jaewoong Jung26342642021-03-17 15:56:23 -0700902 return strings.Join(flags, " "), deps
903}
904
905func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
906
907 var flags javaBuilderFlags
908
909 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900910 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700911
Cole Faust2b1536e2021-06-18 12:25:54 -0700912 epEnabled := j.properties.Errorprone.Enabled
913 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100914 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700915 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
916 }
917
918 errorProneFlags := []string{
919 "-Xplugin:ErrorProne",
920 "${config.ErrorProneChecks}",
921 }
922 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
923
Colin Cross8bf6cad2022-02-28 13:07:03 -0800924 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700925 "'" + strings.Join(errorProneFlags, " ") + "'"
926 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
927 }
928
929 // classpath
930 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
931 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700932 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700933 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
934 flags.processorPath = append(flags.processorPath, deps.processorPath...)
935 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
936
937 flags.processors = append(flags.processors, deps.processorClasses...)
938 flags.processors = android.FirstUniqueStrings(flags.processors)
939
940 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900941 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700942 // Give host-side tools a version of OpenJDK's standard libraries
943 // close to what they're targeting. As of Dec 2017, AOSP is only
944 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
945 //
946 // When building with OpenJDK 8, the following should have no
947 // effect since those jars would be available by default.
948 //
949 // When building with OpenJDK 9 but targeting a version < 1.8,
950 // putting them on the bootclasspath means that:
951 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
952 // b) references to existing APIs are not reinterpreted in an
953 // OpenJDK 9-specific way, eg. calls to subclasses of
954 // java.nio.Buffer as in http://b/70862583
955 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
956 flags.bootClasspath = append(flags.bootClasspath,
957 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
958 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
959 if Bool(j.properties.Use_tools_jar) {
960 flags.bootClasspath = append(flags.bootClasspath,
961 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
962 }
963 }
964
965 // systemModules
966 flags.systemModules = deps.systemModules
967
Jaewoong Jung26342642021-03-17 15:56:23 -0700968 return flags
969}
970
971func (j *Module) collectJavacFlags(
972 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
973 // javac flags.
974 javacFlags := j.properties.Javacflags
975
976 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
977 // For non-host binaries, override the -g flag passed globally to remove
978 // local variable debug info to reduce disk and memory usage.
979 javacFlags = append(javacFlags, "-g:source,lines")
980 }
981 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
982
983 if flags.javaVersion.usesJavaModules() {
984 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
985
986 if j.properties.Patch_module != nil {
987 // Manually specify build directory in case it is not under the repo root.
988 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
989 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200990 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700991
992 // b/150878007
993 //
994 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
995 // execution root for --patch-module. If this javac command line is
996 // invoked within Bazel's execution root working directory, the top
997 // level directories (e.g. libcore/, tools/, frameworks/) are all
998 // symlinks. JDK9 javac does not traverse into symlinks, which causes
999 // --patch-module to fail source file lookups when invoked in the
1000 // execution root.
1001 //
1002 // Short of patching javac or enumerating *all* directories as possible
1003 // input dirs, manually add the top level dir of the source files to be
1004 // compiled.
1005 topLevelDirs := map[string]bool{}
1006 for _, srcFilePath := range srcFiles {
1007 srcFileParts := strings.Split(srcFilePath.String(), "/")
1008 // Ignore source files that are already in the top level directory
1009 // as well as generated files in the out directory. The out
1010 // directory may be an absolute path, which means srcFileParts[0] is the
1011 // empty string, so check that as well. Note that "out" in Bazel's execution
1012 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1013 // anyway, so it's fine to not apply this workaround for generated
1014 // source files.
1015 if len(srcFileParts) > 1 &&
1016 srcFileParts[0] != "" &&
1017 srcFileParts[0] != "out" {
1018 topLevelDirs[srcFileParts[0]] = true
1019 }
1020 }
Cole Faust18994c72023-02-28 16:02:16 -08001021 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001022
1023 classPath := flags.classpath.FormJavaClassPath("")
1024 if classPath != "" {
1025 patchPaths = append(patchPaths, classPath)
1026 }
1027 javacFlags = append(
1028 javacFlags,
1029 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1030 }
1031 }
1032
1033 if len(javacFlags) > 0 {
1034 // optimization.
1035 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1036 flags.javacFlags = "$javacFlags"
1037 }
1038
1039 return flags
1040}
1041
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001042func (j *Module) AddJSONData(d *map[string]interface{}) {
1043 (&j.ModuleBase).AddJSONData(d)
1044 (*d)["Java"] = map[string]interface{}{
1045 "SourceExtensions": j.sourceExtensions,
1046 }
1047
1048}
1049
Joe Onorato175073c2023-06-01 14:42:59 -07001050func (module *Module) addGeneratedSrcJars(path android.Path) {
1051 module.properties.Generated_srcjars = append(module.properties.Generated_srcjars, path)
1052}
1053
Jaewoong Jung26342642021-03-17 15:56:23 -07001054func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1055 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1056
1057 deps := j.collectDeps(ctx)
1058 flags := j.collectBuilderFlags(ctx, deps)
1059
1060 if flags.javaVersion.usesJavaModules() {
1061 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1062 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001063
Jaewoong Jung26342642021-03-17 15:56:23 -07001064 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001065 j.sourceExtensions = []string{}
1066 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1067 if hasSrcExt(srcFiles.Strings(), ext) {
1068 j.sourceExtensions = append(j.sourceExtensions, ext)
1069 }
1070 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001071 if hasSrcExt(srcFiles.Strings(), ".proto") {
1072 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1073 }
1074
1075 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1076 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1077 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1078 }
1079
Sam Delmerico2351eac2022-05-24 17:10:02 +00001080 aidlSrcs := srcFiles.FilterByExt(".aidl")
1081 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1082
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001083 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001084 srcFiles = j.genSources(ctx, srcFiles, flags)
1085
1086 // Collect javac flags only after computing the full set of srcFiles to
1087 // ensure that the --patch-module lookup paths are complete.
1088 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1089
1090 srcJars := srcFiles.FilterByExt(".srcjar")
1091 srcJars = append(srcJars, deps.srcJars...)
1092 if aaptSrcJar != nil {
1093 srcJars = append(srcJars, aaptSrcJar)
1094 }
Joe Onorato175073c2023-06-01 14:42:59 -07001095 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001096 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001097
1098 if j.properties.Jarjar_rules != nil {
1099 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1100 }
1101
1102 jarName := ctx.ModuleName() + ".jar"
1103
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001104 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001105 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001106 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 if _, found := set[v.String()]; !found {
1108 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001109 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001110 }
1111 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001112 var uniqueKtFiles android.Paths
1113 for _, v := range srcFiles.FilterByExt(".kt") {
1114 if _, found := set[v.String()]; !found {
1115 set[v.String()] = true
1116 uniqueKtFiles = append(uniqueKtFiles, v)
1117 }
1118 }
1119
1120 var uniqueSrcFiles android.Paths
1121 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1122 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1123 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001124
Colin Crossb5db4012022-03-28 17:12:39 -07001125 // We don't currently run annotation processors in turbine, which means we can't use turbine
1126 // generated header jars when an annotation processor that generates API is enabled. One
1127 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1128 // is used to run all of the annotation processors.
1129 disableTurbine := deps.disableTurbine
1130
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001131 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001132 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1133
1134 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001135 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001136
1137 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001138 // When using kotlin sources turbine is used to generate annotation processor sources,
1139 // including for annotation processors that generate API, so we can use turbine for
1140 // java sources too.
1141 disableTurbine = false
1142
Jaewoong Jung26342642021-03-17 15:56:23 -07001143 // user defined kotlin flags.
1144 kotlincFlags := j.properties.Kotlincflags
1145 CheckKotlincFlags(ctx, kotlincFlags)
1146
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001147 // Workaround for KT-46512
1148 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001149
1150 // If there are kotlin files, compile them first but pass all the kotlin and java files
1151 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1152 // won't emit any classes for them.
1153 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1154 if ctx.Device() {
1155 kotlincFlags = append(kotlincFlags, "-no-jdk")
1156 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001157
1158 for _, plugin := range deps.kotlinPlugins {
1159 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1160 }
1161 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1162
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 if len(kotlincFlags) > 0 {
1164 // optimization.
1165 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1166 flags.kotlincFlags += "$kotlincFlags"
1167 }
1168
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001169 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001170 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1171
1172 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1173 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1174
1175 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1176 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1177
Isaac Chioua23d9942022-04-06 06:14:38 +00001178 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001179 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001180 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1181 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001182 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001183 srcJars = append(srcJars, kaptSrcJar)
1184 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001185 // Disable annotation processing in javac, it's already been handled by kapt
1186 flags.processorPath = nil
1187 flags.processors = nil
1188 }
1189
1190 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001191 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001192 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 if ctx.Failed() {
1194 return
1195 }
1196
Isaac Chioua23d9942022-04-06 06:14:38 +00001197 // Make javac rule depend on the kotlinc rule
1198 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1199
Jaewoong Jung26342642021-03-17 15:56:23 -07001200 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001201 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1202
Jaewoong Jung26342642021-03-17 15:56:23 -07001203 // Jar kotlin classes into the final jar after javac
1204 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1205 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001206 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001207 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001208 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001209 } else {
1210 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001211 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001212 }
1213 }
1214
1215 jars := append(android.Paths(nil), kotlinJars...)
1216
Jaewoong Jung26342642021-03-17 15:56:23 -07001217 j.compiledSrcJars = srcJars
1218
1219 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001220 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001221 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001222 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1223 enableSharding = true
1224 // Formerly, there was a check here that prevented annotation processors
1225 // from being used when sharding was enabled, as some annotation processors
1226 // do not function correctly in sharded environments. It was removed to
1227 // allow for the use of annotation processors that do function correctly
1228 // with sharding enabled. See: b/77284273.
1229 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001230 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001231 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 if ctx.Failed() {
1233 return
1234 }
1235 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001236 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001237 hasErrorproneableFiles := false
1238 for _, ext := range j.sourceExtensions {
1239 if ext != ".proto" && ext != ".aidl" {
1240 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1241 // compile, and it's not useful to have warnings on these generated sources.
1242 hasErrorproneableFiles = true
1243 break
1244 }
1245 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001246 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001247 if Bool(j.properties.Errorprone.Enabled) {
1248 // If error-prone is enabled, enable errorprone flags on the regular
1249 // build.
1250 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001251 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001252 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1253 // a new jar file just for compiling with the errorprone compiler to.
1254 // This is because we don't want to cause the java files to get completely
1255 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1256 // We also don't want to run this if errorprone is enabled by default for
1257 // this module, or else we could have duplicated errorprone messages.
1258 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001259 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001260 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001261
Vadim Spivak3c496f02023-06-08 06:14:59 +00001262 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001263 "errorprone", "errorprone")
1264
Jaewoong Jung26342642021-03-17 15:56:23 -07001265 extraJarDeps = append(extraJarDeps, errorprone)
1266 }
1267
1268 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001269 if headerJarFileWithoutDepsOrJarjar != nil {
1270 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1271 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001272 shardSize := int(*(j.properties.Javac_shard_size))
1273 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001274 if len(uniqueJavaFiles) > 0 {
1275 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001276 for idx, shardSrc := range shardSrcs {
1277 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1278 nil, flags, extraJarDeps)
1279 jars = append(jars, classes)
1280 }
1281 }
1282 if len(srcJars) > 0 {
1283 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1284 nil, srcJars, flags, extraJarDeps)
1285 jars = append(jars, classes)
1286 }
1287 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001288 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001289 jars = append(jars, classes)
1290 }
1291 if ctx.Failed() {
1292 return
1293 }
1294 }
1295
1296 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1297
1298 var includeSrcJar android.WritablePath
1299 if Bool(j.properties.Include_srcs) {
1300 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1301 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1302 }
1303
1304 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1305 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1306 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1307 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1308
1309 var resArgs []string
1310 var resDeps android.Paths
1311
1312 resArgs = append(resArgs, dirArgs...)
1313 resDeps = append(resDeps, dirDeps...)
1314
1315 resArgs = append(resArgs, fileArgs...)
1316 resDeps = append(resDeps, fileDeps...)
1317
1318 resArgs = append(resArgs, extraArgs...)
1319 resDeps = append(resDeps, extraDeps...)
1320
1321 if len(resArgs) > 0 {
1322 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1323 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1324 j.resourceJar = resourceJar
1325 if ctx.Failed() {
1326 return
1327 }
1328 }
1329
1330 var resourceJars android.Paths
1331 if j.resourceJar != nil {
1332 resourceJars = append(resourceJars, j.resourceJar)
1333 }
1334 if Bool(j.properties.Include_srcs) {
1335 resourceJars = append(resourceJars, includeSrcJar)
1336 }
1337 resourceJars = append(resourceJars, deps.staticResourceJars...)
1338
1339 if len(resourceJars) > 1 {
1340 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1341 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1342 false, nil, nil)
1343 j.resourceJar = combinedJar
1344 } else if len(resourceJars) == 1 {
1345 j.resourceJar = resourceJars[0]
1346 }
1347
1348 if len(deps.staticJars) > 0 {
1349 jars = append(jars, deps.staticJars...)
1350 }
1351
1352 manifest := j.overrideManifest
1353 if !manifest.Valid() && j.properties.Manifest != nil {
1354 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1355 }
1356
1357 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1358 if len(services) > 0 {
1359 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1360 var zipargs []string
1361 for _, file := range services {
1362 serviceFile := file.String()
1363 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1364 }
1365 rule := zip
1366 args := map[string]string{
1367 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1368 }
1369 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1370 rule = zipRE
1371 args["implicits"] = strings.Join(services.Strings(), ",")
1372 }
1373 ctx.Build(pctx, android.BuildParams{
1374 Rule: rule,
1375 Output: servicesJar,
1376 Implicits: services,
1377 Args: args,
1378 })
1379 jars = append(jars, servicesJar)
1380 }
1381
1382 // Combine the classes built from sources, any manifests, and any static libraries into
1383 // classes.jar. If there is only one input jar this step will be skipped.
1384 var outputFile android.OutputPath
1385
1386 if len(jars) == 1 && !manifest.Valid() {
1387 // Optimization: skip the combine step as there is nothing to do
1388 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1389 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1390 // any if len(jars) == 1.
1391
Jihoon Kang1147b312023-06-08 23:25:57 +00001392 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1393 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1394 // either with .from-source or .from-text suffix.
1395 // outputFile should be agnostic to the build configuration,
1396 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1397 // to the copy rules.
1398 stub, _ := moduleStubLinkType(ctx.ModuleName())
1399
Jaewoong Jung26342642021-03-17 15:56:23 -07001400 // Transform the single path to the jar into an OutputPath as that is required by the following
1401 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001402 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001403 // The path contains an embedded OutputPath so reuse that.
1404 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001405 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001406 // The path is an OutputPath so reuse it directly.
1407 outputFile = outputPath
1408 } else {
1409 // The file is not in the out directory so create an OutputPath into which it can be copied
1410 // and which the following code can use to refer to it.
1411 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1412 ctx.Build(pctx, android.BuildParams{
1413 Rule: android.Cp,
1414 Input: jars[0],
1415 Output: combinedJar,
1416 })
1417 outputFile = combinedJar.OutputPath
1418 }
1419 } else {
1420 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1421 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1422 false, nil, nil)
1423 outputFile = combinedJar.OutputPath
1424 }
1425
1426 // jarjar implementation jar if necessary
1427 if j.expandJarjarRules != nil {
1428 // Transform classes.jar into classes-jarjar.jar
1429 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1430 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1431 outputFile = jarjarFile
1432
1433 // jarjar resource jar if necessary
1434 if j.resourceJar != nil {
1435 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1436 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1437 j.resourceJar = resourceJarJarFile
1438 }
1439
1440 if ctx.Failed() {
1441 return
1442 }
1443 }
1444
1445 // Check package restrictions if necessary.
1446 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001447 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001448 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001449
1450 // Create a rule to copy the output jar to another path and add a validate dependency that
1451 // will check that the jar only contains the permitted packages. The new location will become
1452 // the output file of this module.
1453 inputFile := outputFile
1454 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1455 ctx.Build(pctx, android.BuildParams{
1456 Rule: android.Cp,
1457 Input: inputFile,
1458 Output: outputFile,
1459 // Make sure that any dependency on the output file will cause ninja to run the package check
1460 // rule.
1461 Validation: pkgckFile,
1462 })
1463
1464 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001466
1467 if ctx.Failed() {
1468 return
1469 }
1470 }
1471
1472 j.implementationJarFile = outputFile
1473 if j.headerJarFile == nil {
1474 j.headerJarFile = j.implementationJarFile
1475 }
1476
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001477 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1478 specs := j.jacocoModuleToZipCommand(ctx)
1479 if ctx.Failed() {
1480 return
1481 }
1482
Jaewoong Jung26342642021-03-17 15:56:23 -07001483 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001484 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 }
1486
1487 // merge implementation jar with resources if necessary
1488 implementationAndResourcesJar := outputFile
1489 if j.resourceJar != nil {
1490 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1491 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1492 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1493 false, nil, nil)
1494 implementationAndResourcesJar = combinedJar
1495 }
1496
1497 j.implementationAndResourcesJar = implementationAndResourcesJar
1498
1499 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001500 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1502 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001503 if compileDex == nil {
1504 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001505 }
1506 if j.deviceProperties.Hostdex == nil {
1507 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1508 }
1509 }
1510
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001511 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001512 if j.hasCode(ctx) {
1513 if j.shouldInstrumentStatic(ctx) {
1514 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1515 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1516 }
1517 // Dex compilation
1518 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001519 params := &compileDexParams{
1520 flags: flags,
1521 sdkVersion: j.SdkVersion(ctx),
1522 minSdkVersion: j.MinSdkVersion(ctx),
1523 classesJar: implementationAndResourcesJar,
1524 jarName: jarName,
1525 }
1526 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001527 if ctx.Failed() {
1528 return
1529 }
1530
Jaewoong Jung26342642021-03-17 15:56:23 -07001531 // merge dex jar with resources if necessary
1532 if j.resourceJar != nil {
1533 jars := android.Paths{dexOutputFile, j.resourceJar}
1534 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1535 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1536 false, nil, nil)
1537 if *j.dexProperties.Uncompress_dex {
1538 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1539 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1540 dexOutputFile = combinedAlignedJar
1541 } else {
1542 dexOutputFile = combinedJar
1543 }
1544 }
1545
Paul Duffin4de94502021-05-16 05:21:16 +01001546 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001547
1548 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001549
1550 // Encode hidden API flags in dex file, if needed.
1551 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1552
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001553 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001554
1555 // Dexpreopting
1556 j.dexpreopt(ctx, dexOutputFile)
1557
1558 outputFile = dexOutputFile
1559 } else {
1560 // There is no code to compile into a dex jar, make sure the resources are propagated
1561 // to the APK if this is an app.
1562 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001563 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001564 }
1565
1566 if ctx.Failed() {
1567 return
1568 }
1569 } else {
1570 outputFile = implementationAndResourcesJar
1571 }
1572
1573 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001574 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1575 if !apiLevel.IsPreview() {
1576 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001577 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001578 // When running metalava, we pass --version-codename. When that value
1579 // is not REL, metalava will add 1 to the --current-version argument.
1580 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1581 // branch) and the codename is REL, except potentially on the most
1582 // recent non-master branch. On that branch, it goes through two other
1583 // phases before it gets to the phase previously described:
1584 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1585 // is not rel. This happens for most of the internal branch's life
1586 // while the branch has been cut but is still under active development.
1587 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1588 // REL. This happens briefly during the release process. During this
1589 // state the code to add --current-version is commented out, and then
1590 // that commenting out is reverted after the codename is set to REL.
1591 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1592 // prior version and the codename is always non-REL.
1593 //
1594 // We need to add one here to match metalava adding 1. Technically
1595 // this means that in the state described in the second bullet point
1596 // above, this number is 1 higher than it should be.
1597 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001598 }
1599 }
1600
1601 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001602 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1603 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001604 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1605 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001606 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001607 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001608 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001609 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001610 j.linter.javaLanguageLevel = flags.javaVersion.String()
1611 j.linter.kotlinLanguageLevel = "1.3"
1612 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1613 j.linter.buildModuleReportZip = true
1614 }
1615 j.linter.lint(ctx)
1616 }
1617
1618 ctx.CheckbuildFile(outputFile)
1619
1620 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1621 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001622 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1623 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001624 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1625 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1626 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1627 AidlIncludeDirs: j.exportAidlIncludeDirs,
1628 SrcJarArgs: j.srcJarArgs,
1629 SrcJarDeps: j.srcJarDeps,
1630 ExportedPlugins: j.exportedPluginJars,
1631 ExportedPluginClasses: j.exportedPluginClasses,
1632 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1633 JacocoReportClassesFile: j.jacocoReportClassesFile,
1634 })
1635
1636 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1637 j.outputFile = outputFile.WithoutRel()
1638}
1639
Colin Crossa1ff7c62021-09-17 14:11:52 -07001640func (j *Module) useCompose() bool {
1641 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1642}
1643
Cole Faust75fffb12021-06-13 15:23:16 -07001644// Returns a copy of the supplied flags, but with all the errorprone-related
1645// fields copied to the regular build's fields.
1646func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1647 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1648
1649 if len(flags.errorProneExtraJavacFlags) > 0 {
1650 if len(flags.javacFlags) > 0 {
1651 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1652 } else {
1653 flags.javacFlags = flags.errorProneExtraJavacFlags
1654 }
1655 }
1656 return flags
1657}
1658
Jaewoong Jung26342642021-03-17 15:56:23 -07001659func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1660 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1661
1662 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001663 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001664 if idx >= 0 {
1665 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001666 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001667 jarName += strconv.Itoa(idx)
1668 }
1669
1670 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001671 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001672
1673 if ctx.Config().EmitXrefRules() {
1674 extractionFile := android.PathForModuleOut(ctx, kzipName)
1675 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1676 j.kytheFiles = append(j.kytheFiles, extractionFile)
1677 }
1678
Vadim Spivak3c496f02023-06-08 06:14:59 +00001679 if len(flags.processorPath) > 0 {
1680 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1681 }
1682
Jaewoong Jung26342642021-03-17 15:56:23 -07001683 return classes
1684}
1685
1686// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1687// since some of these flags may be used internally.
1688func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1689 for _, flag := range flags {
1690 flag = strings.TrimSpace(flag)
1691
1692 if !strings.HasPrefix(flag, "-") {
1693 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1694 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1695 ctx.PropertyErrorf("kotlincflags",
1696 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1697 } else if inList(flag, config.KotlincIllegalFlags) {
1698 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1699 } else if flag == "-include-runtime" {
1700 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1701 } else {
1702 args := strings.Split(flag, " ")
1703 if args[0] == "-kotlin-home" {
1704 ctx.PropertyErrorf("kotlincflags",
1705 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1706 }
1707 }
1708 }
1709}
1710
1711func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1712 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001713 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001714
1715 var jars android.Paths
1716 if len(srcFiles) > 0 || len(srcJars) > 0 {
1717 // Compile java sources into turbine.jar.
1718 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1719 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1720 if ctx.Failed() {
1721 return nil, nil
1722 }
1723 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001724 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001725 }
1726
1727 jars = append(jars, extraJars...)
1728
1729 // Combine any static header libraries into classes-header.jar. If there is only
1730 // one input jar this step will be skipped.
1731 jars = append(jars, deps.staticHeaderJars...)
1732
1733 // we cannot skip the combine step for now if there is only one jar
1734 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1735 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1736 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1737 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001738 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001739
1740 if j.expandJarjarRules != nil {
1741 // Transform classes.jar into classes-jarjar.jar
1742 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001743 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1744 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001745 if ctx.Failed() {
1746 return nil, nil
1747 }
1748 }
1749
Colin Cross3d56ed52021-11-18 22:23:12 -08001750 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001751}
1752
1753func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001754 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001755
1756 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1757 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1758
1759 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1760
1761 j.jacocoReportClassesFile = jacocoReportClassesFile
1762
1763 return instrumentedJar
1764}
1765
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001766type providesTransitiveHeaderJars struct {
1767 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001768 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001769 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001770 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001771}
1772
Colin Crossc85750b2022-04-21 12:50:51 -07001773func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001774 return j.transitiveLibsHeaderJars
1775}
1776
Colin Crossc85750b2022-04-21 12:50:51 -07001777func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001778 return j.transitiveStaticLibsHeaderJars
1779}
1780
1781func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1782 directLibs := android.Paths{}
1783 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001784 transitiveLibs := []*android.DepSet[android.Path]{}
1785 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001786 ctx.VisitDirectDeps(func(module android.Module) {
1787 // don't add deps of the prebuilt version of the same library
1788 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1789 return
1790 }
1791
1792 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1793 if dep.TransitiveLibsHeaderJars != nil {
1794 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1795 }
1796 if dep.TransitiveStaticLibsHeaderJars != nil {
1797 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1798 }
1799
1800 tag := ctx.OtherModuleDependencyTag(module)
1801 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1802 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1803 directLibs = append(directLibs, dep.HeaderJars...)
1804 } else if tag == staticLibTag {
1805 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1806 }
1807 })
1808 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1809 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1810}
1811
Jaewoong Jung26342642021-03-17 15:56:23 -07001812func (j *Module) HeaderJars() android.Paths {
1813 if j.headerJarFile == nil {
1814 return nil
1815 }
1816 return android.Paths{j.headerJarFile}
1817}
1818
1819func (j *Module) ImplementationJars() android.Paths {
1820 if j.implementationJarFile == nil {
1821 return nil
1822 }
1823 return android.Paths{j.implementationJarFile}
1824}
1825
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001826func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001827 return j.dexJarFile
1828}
1829
1830func (j *Module) DexJarInstallPath() android.Path {
1831 return j.installFile
1832}
1833
1834func (j *Module) ImplementationAndResourcesJars() android.Paths {
1835 if j.implementationAndResourcesJar == nil {
1836 return nil
1837 }
1838 return android.Paths{j.implementationAndResourcesJar}
1839}
1840
1841func (j *Module) AidlIncludeDirs() android.Paths {
1842 // exportAidlIncludeDirs is type android.Paths already
1843 return j.exportAidlIncludeDirs
1844}
1845
1846func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1847 return j.classLoaderContexts
1848}
1849
1850// Collect information for opening IDE project files in java/jdeps.go.
1851func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1852 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1853 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1854 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1855 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1856 if j.expandJarjarRules != nil {
1857 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1858 }
1859 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001860 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1861 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001862 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001863}
1864
1865func (j *Module) CompilerDeps() []string {
1866 jdeps := []string{}
1867 jdeps = append(jdeps, j.properties.Libs...)
1868 jdeps = append(jdeps, j.properties.Static_libs...)
1869 return jdeps
1870}
1871
1872func (j *Module) hasCode(ctx android.ModuleContext) bool {
1873 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1874 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1875}
1876
1877// Implements android.ApexModule
1878func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1879 return j.depIsInSameApex(ctx, dep)
1880}
1881
1882// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001883func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001884 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001885 minSdkVersion := j.MinSdkVersion(ctx)
1886 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 return fmt.Errorf("min_sdk_version is not specified")
1888 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001889 // If the module is compiling against core (via sdk_version), skip comparison check.
1890 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001891 return nil
1892 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001893 if minSdkVersion.GreaterThan(sdkVersion) {
1894 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001895 }
1896 return nil
1897}
1898
1899func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001900 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001901}
1902
Jaewoong Jung26342642021-03-17 15:56:23 -07001903func (j *Module) JacocoReportClassesFile() android.Path {
1904 return j.jacocoReportClassesFile
1905}
1906
1907func (j *Module) IsInstallable() bool {
1908 return Bool(j.properties.Installable)
1909}
1910
1911type sdkLinkType int
1912
1913const (
1914 // TODO(jiyong) rename these for better readability. Make the allowed
1915 // and disallowed link types explicit
1916 // order is important here. See rank()
1917 javaCore sdkLinkType = iota
1918 javaSdk
1919 javaSystem
1920 javaModule
1921 javaSystemServer
1922 javaPlatform
1923)
1924
1925func (lt sdkLinkType) String() string {
1926 switch lt {
1927 case javaCore:
1928 return "core Java API"
1929 case javaSdk:
1930 return "Android API"
1931 case javaSystem:
1932 return "system API"
1933 case javaModule:
1934 return "module API"
1935 case javaSystemServer:
1936 return "system server API"
1937 case javaPlatform:
1938 return "private API"
1939 default:
1940 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1941 }
1942}
1943
1944// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1945// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1946// can't statically depend on modules that use Platform API.
1947func (lt sdkLinkType) rank() int {
1948 return int(lt)
1949}
1950
1951type moduleWithSdkDep interface {
1952 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001953 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001954}
1955
Jiyong Park92315372021-04-02 08:45:46 +09001956func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001957 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001958 case android.SdkCore.DefaultJavaLibraryName(),
1959 "legacy.core.platform.api.stubs",
1960 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001961 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001962 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001963 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001964 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001965 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001966 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001967 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001968 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001969 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001970 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001971 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001972 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001973 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001974 return javaSystem, true
1975 }
1976
1977 if stub, linkType := moduleStubLinkType(name); stub {
1978 return linkType, true
1979 }
1980
Jiyong Park92315372021-04-02 08:45:46 +09001981 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001982 switch ver.Kind {
1983 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001984 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001985 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001986 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001987 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001988 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001989 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001990 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001991 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001992 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001993 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001994 return javaPlatform, false
1995 }
1996
Jiyong Parkf1691d22021-03-29 20:11:58 +09001997 if !ver.Valid() {
1998 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001999 }
2000 return javaSdk, false
2001}
2002
2003// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2004// this module's. See the comment on rank() for details and an example.
2005func (j *Module) checkSdkLinkType(
2006 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2007 if ctx.Host() {
2008 return
2009 }
2010
Jiyong Park92315372021-04-02 08:45:46 +09002011 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002012 if stubs {
2013 return
2014 }
Jiyong Park92315372021-04-02 08:45:46 +09002015 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002016
2017 if myLinkType.rank() < depLinkType.rank() {
2018 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2019 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2020 "property of the source or target module so that target module is built "+
2021 "with the same or smaller API set when compared to the source.",
2022 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2023 }
2024}
2025
2026func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2027 var deps deps
2028
2029 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002030 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002031 if sdkDep.invalidVersion {
2032 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2033 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2034 } else if sdkDep.useFiles {
2035 // sdkDep.jar is actually equivalent to turbine header.jar.
2036 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002037 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002038 deps.aidlPreprocess = sdkDep.aidl
2039 } else {
2040 deps.aidlPreprocess = sdkDep.aidl
2041 }
2042 }
2043
Jiyong Park92315372021-04-02 08:45:46 +09002044 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002045
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002046 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002047 ctx.VisitDirectDeps(func(module android.Module) {
2048 otherName := ctx.OtherModuleName(module)
2049 tag := ctx.OtherModuleDependencyTag(module)
2050
2051 if IsJniDepTag(tag) {
2052 // Handled by AndroidApp.collectAppDeps
2053 return
2054 }
2055 if tag == certificateTag {
2056 // Handled by AndroidApp.collectAppDeps
2057 return
2058 }
2059
2060 if dep, ok := module.(SdkLibraryDependency); ok {
2061 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002062 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002063 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2064 deps.classpath = append(deps.classpath, depHeaderJars...)
2065 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002066 case staticLibTag:
2067 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2068 }
2069 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2070 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2071 if sdkLinkType != javaPlatform &&
2072 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2073 // dep is a sysprop implementation library, but this module is not linking against
2074 // the platform, so it gets the sysprop public stubs library instead. Replace
2075 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2076 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2077 dep = syspropDep.JavaInfo
2078 }
2079 switch tag {
2080 case bootClasspathTag:
2081 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002082 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002083 if _, ok := module.(*Plugin); ok {
2084 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2085 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002086 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002087 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002088 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2089 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2090 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2091 case java9LibTag:
2092 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2093 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002094 if _, ok := module.(*Plugin); ok {
2095 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2096 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002097 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2098 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2099 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2100 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2101 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2102 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2103 // Turbine doesn't run annotation processors, so any module that uses an
2104 // annotation processor that generates API is incompatible with the turbine
2105 // optimization.
2106 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2107 case pluginTag:
2108 if plugin, ok := module.(*Plugin); ok {
2109 if plugin.pluginProperties.Processor_class != nil {
2110 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2111 } else {
2112 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2113 }
2114 // Turbine doesn't run annotation processors, so any module that uses an
2115 // annotation processor that generates API is incompatible with the turbine
2116 // optimization.
2117 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2118 } else {
2119 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2120 }
2121 case errorpronePluginTag:
2122 if _, ok := module.(*Plugin); ok {
2123 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2124 } else {
2125 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2126 }
2127 case exportedPluginTag:
2128 if plugin, ok := module.(*Plugin); ok {
2129 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2130 if plugin.pluginProperties.Processor_class != nil {
2131 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2132 }
2133 // Turbine doesn't run annotation processors, so any module that uses an
2134 // annotation processor that generates API is incompatible with the turbine
2135 // optimization.
2136 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2137 } else {
2138 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2139 }
2140 case kotlinStdlibTag:
2141 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2142 case kotlinAnnotationsTag:
2143 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002144 case kotlinPluginTag:
2145 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002146 case syspropPublicStubDepTag:
2147 // This is a sysprop implementation library, forward the JavaInfoProvider from
2148 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2149 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2150 JavaInfo: dep,
2151 })
2152 }
2153 } else if dep, ok := module.(android.SourceFileProducer); ok {
2154 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002155 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002156 checkProducesJars(ctx, dep)
2157 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002158 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002159 case staticLibTag:
2160 checkProducesJars(ctx, dep)
2161 deps.classpath = append(deps.classpath, dep.Srcs()...)
2162 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2163 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2164 }
2165 } else {
2166 switch tag {
2167 case bootClasspathTag:
2168 // If a system modules dependency has been added to the bootclasspath
2169 // then add its libs to the bootclasspath.
2170 sm := module.(SystemModulesProvider)
2171 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2172
2173 case systemModulesTag:
2174 if deps.systemModules != nil {
2175 panic("Found two system module dependencies")
2176 }
2177 sm := module.(SystemModulesProvider)
2178 outputDir, outputDeps := sm.OutputDirAndDeps()
2179 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002180
2181 case instrumentationForTag:
2182 ctx.PropertyErrorf("instrumentation_for", "dependency %q of type %q does not provide JavaInfo so is unsuitable for use with this property", ctx.OtherModuleName(module), ctx.OtherModuleType(module))
Jaewoong Jung26342642021-03-17 15:56:23 -07002183 }
2184 }
2185
2186 addCLCFromDep(ctx, module, j.classLoaderContexts)
2187 })
2188
2189 return deps
2190}
2191
2192func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2193 deps.processorPath = append(deps.processorPath, pluginJars...)
2194 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2195}
2196
2197// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2198// this interface.
2199type ProvidesUsesLib interface {
2200 ProvidesUsesLib() *string
2201}
2202
2203func (j *Module) ProvidesUsesLib() *string {
2204 return j.usesLibraryProperties.Provides_uses_lib
2205}
satayev1c564cc2021-05-25 19:50:30 +01002206
2207type ModuleWithStem interface {
2208 Stem() string
2209}
2210
2211var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002212
2213func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2214 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002215 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002216 if lib, ok := ctx.Module().(*Library); ok {
2217 javaLibraryBp2Build(ctx, lib)
2218 }
2219 case "java_binary_host":
2220 if binary, ok := ctx.Module().(*Binary); ok {
2221 javaBinaryHostBp2Build(ctx, binary)
2222 }
Zi Wang65b36722023-05-23 15:18:33 -07002223 case "java_test_host":
2224 if testHost, ok := ctx.Module().(*TestHost); ok {
2225 javaTestHostBp2Build(ctx, testHost)
2226 }
Chris Parsons39a16972023-06-08 14:28:51 +00002227 default:
2228 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002229 }
Wei Libafb6d62021-12-10 03:14:59 -08002230}