blob: ce94335d617512d6f7bfb6998845b1f1f1b668ea [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"
Jihoon Kang1bfb6f22023-07-01 00:13:47 +000024
Jaewoong Jung26342642021-03-17 15:56:23 -070025 "github.com/google/blueprint/pathtools"
26 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
29 "android/soong/dexpreopt"
30 "android/soong/java/config"
31)
32
33// This file contains the definition and the implementation of the base module that most
34// source-based Java module structs embed.
35
36// TODO:
37// Autogenerated files:
38// Renderscript
39// Post-jar passes:
40// Proguard
41// Rmtypedefs
42// DroidDoc
43// Findbugs
44
45// Properties that are common to most Java modules, i.e. whether it's a host or device module.
46type CommonProperties struct {
47 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
48 // or .aidl files.
49 Srcs []string `android:"path,arch_variant"`
50
51 // list Kotlin of source files containing Kotlin code that should be treated as common code in
52 // a codebase that supports Kotlin multiplatform. See
53 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
54 Common_srcs []string `android:"path,arch_variant"`
55
56 // list of source files that should not be used to build the Java module.
57 // This is most useful in the arch/multilib variants to remove non-common files
58 Exclude_srcs []string `android:"path,arch_variant"`
59
60 // list of directories containing Java resources
61 Java_resource_dirs []string `android:"arch_variant"`
62
63 // list of directories that should be excluded from java_resource_dirs
64 Exclude_java_resource_dirs []string `android:"arch_variant"`
65
66 // list of files to use as Java resources
67 Java_resources []string `android:"path,arch_variant"`
68
69 // list of files that should be excluded from java_resources and java_resource_dirs
70 Exclude_java_resources []string `android:"path,arch_variant"`
71
72 // list of module-specific flags that will be used for javac compiles
73 Javacflags []string `android:"arch_variant"`
74
75 // list of module-specific flags that will be used for kotlinc compiles
76 Kotlincflags []string `android:"arch_variant"`
77
78 // list of java libraries that will be in the classpath
79 Libs []string `android:"arch_variant"`
80
81 // list of java libraries that will be compiled into the resulting jar
82 Static_libs []string `android:"arch_variant"`
83
Jihoon Kang381c2fa2023-06-01 22:17:32 +000084 // list of java libraries that should not be used to build this module
85 Exclude_static_libs []string `android:"arch_variant"`
86
Jaewoong Jung26342642021-03-17 15:56:23 -070087 // manifest file to be included in resulting jar
88 Manifest *string `android:"path"`
89
90 // if not blank, run jarjar using the specified rules file
91 Jarjar_rules *string `android:"path,arch_variant"`
92
93 // If not blank, set the java version passed to javac as -source and -target
94 Java_version *string
95
96 // If set to true, allow this module to be dexed and installed on devices. Has no
97 // effect on host modules, which are always considered installable.
98 Installable *bool
99
100 // If set to true, include sources used to compile the module in to the final jar
101 Include_srcs *bool
102
103 // If not empty, classes are restricted to the specified packages and their sub-packages.
104 // This restriction is checked after applying jarjar rules and including static libs.
105 Permitted_packages []string
106
107 // List of modules to use as annotation processors
108 Plugins []string
109
110 // List of modules to export to libraries that directly depend on this library as annotation
111 // processors. Note that if the plugins set generates_api: true this will disable the turbine
112 // optimization on modules that depend on this module, which will reduce parallelism and cause
113 // more recompilation.
114 Exported_plugins []string
115
116 // The number of Java source entries each Javac instance can process
117 Javac_shard_size *int64
118
119 // Add host jdk tools.jar to bootclasspath
120 Use_tools_jar *bool
121
122 Openjdk9 struct {
123 // List of source files that should only be used when passing -source 1.9 or higher
124 Srcs []string `android:"path"`
125
126 // List of javac flags that should only be used when passing -source 1.9 or higher
127 Javacflags []string
128 }
129
130 // When compiling language level 9+ .java code in packages that are part of
131 // a system module, patch_module names the module that your sources and
132 // dependencies should be patched into. The Android runtime currently
133 // doesn't implement the JEP 261 module system so this option is only
134 // supported at compile time. It should only be needed to compile tests in
135 // packages that exist in libcore and which are inconvenient to move
136 // elsewhere.
137 Patch_module *string `android:"arch_variant"`
138
139 Jacoco struct {
140 // List of classes to include for instrumentation with jacoco to collect coverage
141 // information at runtime when building with coverage enabled. If unset defaults to all
142 // classes.
143 // Supports '*' as the last character of an entry in the list as a wildcard match.
144 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
145 // it matches classes in the package that have the class name as a prefix.
146 Include_filter []string
147
148 // List of classes to exclude from instrumentation with jacoco to collect coverage
149 // information at runtime when building with coverage enabled. Overrides classes selected
150 // by the include_filter property.
151 // Supports '*' as the last character of an entry in the list as a wildcard match.
152 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
153 // it matches classes in the package that have the class name as a prefix.
154 Exclude_filter []string
155 }
156
157 Errorprone struct {
158 // List of javac flags that should only be used when running errorprone.
159 Javacflags []string
160
161 // List of java_plugin modules that provide extra errorprone checks.
162 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700163
Cole Faust2b1536e2021-06-18 12:25:54 -0700164 // This property can be in 3 states. When set to true, errorprone will
165 // be run during the regular build. When set to false, errorprone will
166 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
167 // environment variable is true. Setting this to false will improve build
168 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700169 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700170 }
171
172 Proto struct {
173 // List of extra options that will be passed to the proto generator.
174 Output_params []string
175 }
176
Sam Delmericoc7593722022-08-31 15:57:52 -0400177 // If true, then jacocoagent is automatically added as a libs dependency so that
178 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000180 // If true, then the module supports statically including the jacocoagent
181 // into the library.
182 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700183
184 // List of files to include in the META-INF/services folder of the resulting jar.
185 Services []string `android:"path,arch_variant"`
186
187 // If true, package the kotlin stdlib into the jar. Defaults to true.
188 Static_kotlin_stdlib *bool `android:"arch_variant"`
189
190 // A list of java_library instances that provide additional hiddenapi annotations for the library.
191 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700192
193 // Additional srcJars tacked in by GeneratedJavaLibraryModule
194 Generated_srcjars []android.Path `android:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700195}
196
197// Properties that are specific to device modules. Host module factories should not add these when
198// constructing a new module.
199type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000200 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000201 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000202 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000203 // 1) numerical API level, "current", "none", or "core_platform"
204 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
205 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
206 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700207 Sdk_version *string
208
209 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000210 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 Min_sdk_version *string
212
satayev0a420e72021-11-29 17:25:52 +0000213 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
214 // Defaults to empty string "". See sdk_version for possible values.
215 Max_sdk_version *string
216
William Loh5a082f92022-05-17 20:21:50 +0000217 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
218 // Defaults to empty string "". See sdk_version for possible values.
219 Replace_max_sdk_version_placeholder *string
220
Jaewoong Jung26342642021-03-17 15:56:23 -0700221 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000222 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700223 Target_sdk_version *string
224
225 // Whether to compile against the platform APIs instead of an SDK.
226 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000227 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700228 Platform_apis *bool
229
230 Aidl struct {
231 // Top level directories to pass to aidl tool
232 Include_dirs []string
233
234 // Directories rooted at the Android.bp file to pass to aidl tool
235 Local_include_dirs []string
236
237 // directories that should be added as include directories for any aidl sources of modules
238 // that depend on this module, as well as to aidl for this module.
239 Export_include_dirs []string
240
241 // whether to generate traces (for systrace) for this interface
242 Generate_traces *bool
243
244 // whether to generate Binder#GetTransaction name method.
245 Generate_get_transaction_name *bool
246
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100247 // whether all interfaces should be annotated with required permissions.
248 Enforce_permissions *bool
249
250 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
251 Enforce_permissions_exceptions []string `android:"path"`
252
Jaewoong Jung26342642021-03-17 15:56:23 -0700253 // list of flags that will be passed to the AIDL compiler
254 Flags []string
255 }
256
257 // If true, export a copy of the module as a -hostdex module for host testing.
258 Hostdex *bool
259
260 Target struct {
261 Hostdex struct {
262 // Additional required dependencies to add to -hostdex modules.
263 Required []string
264 }
265 }
266
267 // When targeting 1.9 and above, override the modules to use with --system,
268 // otherwise provides defaults libraries to add to the bootclasspath.
269 System_modules *string
270
Jaewoong Jung26342642021-03-17 15:56:23 -0700271 IsSDKLibrary bool `blueprint:"mutated"`
272
273 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
274 // Defaults to false.
275 V4_signature *bool
276
277 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
278 // public stubs library.
279 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000280
281 HiddenAPIPackageProperties
282 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700283}
284
Jooyung Han01d80d82022-01-08 12:16:32 +0900285// Device properties that can be overridden by overriding module (e.g. override_android_app)
286type OverridableDeviceProperties struct {
287 // set the name of the output. If not set, `name` is used.
288 // To override a module with this property set, overriding module might need to set this as well.
289 // Otherwise, both the overridden and the overriding modules will have the same output name, which
290 // can cause the duplicate output error.
291 Stem *string
292}
293
Jaewoong Jung26342642021-03-17 15:56:23 -0700294// Functionality common to Module and Import
295//
296// It is embedded in Module so its functionality can be used by methods in Module
297// but it is currently only initialized by Import and Library.
298type embeddableInModuleAndImport struct {
299
300 // Functionality related to this being used as a component of a java_sdk_library.
301 EmbeddableSdkLibraryComponent
302}
303
Paul Duffin71b33cc2021-06-23 11:39:47 +0100304func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
305 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700306}
307
308// Module/Import's DepIsInSameApex(...) delegates to this method.
309//
310// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
311// the one provided by ApexModuleBase.
312func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
313 // dependencies other than the static linkage are all considered crossing APEX boundary
314 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
315 return true
316 }
317 return false
318}
319
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100320// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
321// or an invalid path describing the reason it is invalid.
322//
323// It is unset if a dex jar isn't applicable, i.e. no build rule has been
324// requested to create one.
325//
326// If a dex jar has been requested to be built then it is set, and it may be
327// either a valid android.Path, or invalid with a reason message. The latter
328// happens if the source that should produce the dex file isn't able to.
329//
330// E.g. it is invalid with a reason message if there is a prebuilt APEX that
331// could produce the dex jar through a deapexer module, but the APEX isn't
332// installable so doing so wouldn't be safe.
333type OptionalDexJarPath struct {
334 isSet bool
335 path android.OptionalPath
336}
337
338// IsSet returns true if a path has been set, either invalid or valid.
339func (o OptionalDexJarPath) IsSet() bool {
340 return o.isSet
341}
342
343// Valid returns true if there is a path that is valid.
344func (o OptionalDexJarPath) Valid() bool {
345 return o.isSet && o.path.Valid()
346}
347
348// Path returns the valid path, or panics if it's either not set or is invalid.
349func (o OptionalDexJarPath) Path() android.Path {
350 if !o.isSet {
351 panic("path isn't set")
352 }
353 return o.path.Path()
354}
355
356// PathOrNil returns the path if it's set and valid, or else nil.
357func (o OptionalDexJarPath) PathOrNil() android.Path {
358 if o.Valid() {
359 return o.Path()
360 }
361 return nil
362}
363
364// InvalidReason returns the reason for an invalid path, which is never "". It
365// returns "" for an unset or valid path.
366func (o OptionalDexJarPath) InvalidReason() string {
367 if !o.isSet {
368 return ""
369 }
370 return o.path.InvalidReason()
371}
372
373func (o OptionalDexJarPath) String() string {
374 if !o.isSet {
375 return "<unset>"
376 }
377 return o.path.String()
378}
379
380// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
381func makeUnsetDexJarPath() OptionalDexJarPath {
382 return OptionalDexJarPath{isSet: false}
383}
384
385// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
386// the given OptionalPath, which may be valid or invalid.
387func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
388 return OptionalDexJarPath{isSet: true, path: path}
389}
390
391// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
392// valid given path. It returns an unset OptionalDexJarPath if the given path is
393// nil.
394func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
395 if path == nil {
396 return makeUnsetDexJarPath()
397 }
398 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
399}
400
Jaewoong Jung26342642021-03-17 15:56:23 -0700401// Module contains the properties and members used by all java module types
402type Module struct {
403 android.ModuleBase
404 android.DefaultableModuleBase
405 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800406 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700407
408 // Functionality common to Module and Import.
409 embeddableInModuleAndImport
410
411 properties CommonProperties
412 protoProperties android.ProtoProperties
413 deviceProperties DeviceProperties
414
Jooyung Han01d80d82022-01-08 12:16:32 +0900415 overridableDeviceProperties OverridableDeviceProperties
416
Jaewoong Jung26342642021-03-17 15:56:23 -0700417 // jar file containing header classes including static library dependencies, suitable for
418 // inserting into the bootclasspath/classpath of another compile
419 headerJarFile android.Path
420
421 // jar file containing implementation classes including static library dependencies but no
422 // resources
423 implementationJarFile android.Path
424
425 // jar file containing only resources including from static library dependencies
426 resourceJar android.Path
427
428 // args and dependencies to package source files into a srcjar
429 srcJarArgs []string
430 srcJarDeps android.Paths
431
432 // jar file containing implementation classes and resources including static library
433 // dependencies
434 implementationAndResourcesJar android.Path
435
436 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100437 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700438
439 // output file containing uninstrumented classes that will be instrumented by jacoco
440 jacocoReportClassesFile android.Path
441
442 // output file of the module, which may be a classes jar or a dex jar
443 outputFile android.Path
444 extraOutputFiles android.Paths
445
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100446 exportAidlIncludeDirs android.Paths
447 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700448
449 logtagsSrcs android.Paths
450
451 // installed file for binary dependency
452 installFile android.Path
453
Colin Cross3108ce12021-11-10 14:38:50 -0800454 // installed file for hostdex copy
455 hostdexInstallFile android.InstallPath
456
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800457 // list of unique .java and .kt source files
458 uniqueSrcFiles android.Paths
459
460 // list of srcjars that was passed to javac
461 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700462
463 // manifest file to use instead of properties.Manifest
464 overrideManifest android.OptionalPath
465
Jaewoong Jung26342642021-03-17 15:56:23 -0700466 // list of plugins that this java module is exporting
467 exportedPluginJars android.Paths
468
469 // list of plugins that this java module is exporting
470 exportedPluginClasses []string
471
472 // if true, the exported plugins generate API and require disabling turbine.
473 exportedDisableTurbine bool
474
475 // list of source files, collected from srcFiles with unique java and all kt files,
476 // will be used by android.IDEInfo struct
477 expandIDEInfoCompiledSrcs []string
478
479 // expanded Jarjar_rules
480 expandJarjarRules android.Path
481
Jaewoong Jung26342642021-03-17 15:56:23 -0700482 // Extra files generated by the module type to be added as java resources.
483 extraResources android.Paths
484
485 hiddenAPI
486 dexer
487 dexpreopter
488 usesLibrary
489 linter
490
491 // list of the xref extraction files
492 kytheFiles android.Paths
493
494 // Collect the module directory for IDE info in java/jdeps.go.
495 modulePaths []string
496
497 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900498
499 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000500 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000501 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400502
503 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000504
505 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000506
507 // output file name based on Stem property.
508 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
509 // or the module should override Stem().
510 stem string
Jaewoong Jung26342642021-03-17 15:56:23 -0700511}
512
Jiyong Park92315372021-04-02 08:45:46 +0900513func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
514 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900515 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700516 return nil
517 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900518 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000519 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700520 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
521 } else {
522 // Treat stable core platform as stable.
523 return nil
524 }
525 } else {
526 return fmt.Errorf("non stable SDK %v", sdkVersion)
527 }
528}
529
530// checkSdkVersions enforces restrictions around SDK dependencies.
531func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
532 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900533 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900534 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700535 ctx.PropertyErrorf("sdk_version",
536 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
537 }
538 }
539 }
540
541 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
542 // See rank() for details.
543 ctx.VisitDirectDeps(func(module android.Module) {
544 tag := ctx.OtherModuleDependencyTag(module)
545 switch module.(type) {
546 // TODO(satayev): cover other types as well, e.g. imports
547 case *Library, *AndroidLibrary:
548 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400549 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700550 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
551 }
552 }
553 })
554}
555
556func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900557 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700558 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900559 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700560 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000561 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 -0700562 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000563 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 -0700564 }
565
566 }
567}
568
569func (j *Module) addHostProperties() {
570 j.AddProperties(
571 &j.properties,
572 &j.protoProperties,
573 &j.usesLibraryProperties,
574 )
575}
576
577func (j *Module) addHostAndDeviceProperties() {
578 j.addHostProperties()
579 j.AddProperties(
580 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900581 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700582 &j.dexer.dexProperties,
583 &j.dexpreoptProperties,
584 &j.linter.properties,
585 )
586}
587
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000588// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
589// makes it available through the hiddenAPIPropertyInfoProvider.
590func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
591 hiddenAPIInfo := newHiddenAPIPropertyInfo()
592
593 // Populate with flag file paths from the properties.
594 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
595
596 // Populate with package rules from the properties.
597 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
598
599 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
600}
601
Jaewoong Jung26342642021-03-17 15:56:23 -0700602func (j *Module) OutputFiles(tag string) (android.Paths, error) {
603 switch tag {
604 case "":
605 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
606 case android.DefaultDistTag:
607 return android.Paths{j.outputFile}, nil
608 case ".jar":
609 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700610 case ".hjar":
611 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700612 case ".proguard_map":
613 if j.dexer.proguardDictionary.Valid() {
614 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
615 }
616 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
617 default:
618 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
619 }
620}
621
622var _ android.OutputFileProducer = (*Module)(nil)
623
624func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
625 initJavaModule(module, hod, false)
626}
627
628func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
629 initJavaModule(module, hod, true)
630}
631
632func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
633 multilib := android.MultilibCommon
634 if multiTargets {
635 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
636 } else {
637 android.InitAndroidArchModule(module, hod, multilib)
638 }
639 android.InitDefaultableModule(module)
640}
641
642func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
643 return j.properties.Instrument &&
644 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
645 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
646}
647
648func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000649 return j.properties.Supports_static_instrumentation &&
650 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700651 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
652 ctx.Config().UnbundledBuild())
653}
654
655func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
656 // Force enable the instrumentation for java code that is built for APEXes ...
657 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
658 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
659 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
660 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
661 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
662 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
663 return true
664 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
665 return true
666 }
667 }
668 return false
669}
670
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400671func (j *Module) setInstrument(value bool) {
672 j.properties.Instrument = value
673}
674
Jiyong Park92315372021-04-02 08:45:46 +0900675func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
676 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700677}
678
Jiyong Parkf1691d22021-03-29 20:11:58 +0900679func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700680 return proptools.String(j.deviceProperties.System_modules)
681}
682
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000683func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700684 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000685 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700686 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000687 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700688}
689
Spandan Dasa26eda72023-03-02 00:56:06 +0000690func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
691 if j.deviceProperties.Max_sdk_version != nil {
692 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
693 }
694 // Default is PrivateApiLevel
695 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000696}
697
Spandan Dasa26eda72023-03-02 00:56:06 +0000698func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
699 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
700 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
701 }
702 // Default is PrivateApiLevel
703 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000704}
705
Jiyong Parkf1691d22021-03-29 20:11:58 +0900706func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000707 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900708}
709
Spandan Dasca70fc42023-03-01 23:38:49 +0000710func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900711 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000712 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900713 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000714 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700715}
716
717func (j *Module) AvailableFor(what string) bool {
718 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
719 // Exception: for hostdex: true libraries, the platform variant is created
720 // even if it's not marked as available to platform. In that case, the platform
721 // variant is used only for the hostdex and not installed to the device.
722 return true
723 }
724 return j.ApexModuleBase.AvailableFor(what)
725}
726
727func (j *Module) deps(ctx android.BottomUpMutatorContext) {
728 if ctx.Device() {
729 j.linter.deps(ctx)
730
Jiyong Parkf1691d22021-03-29 20:11:58 +0900731 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700732
733 if j.deviceProperties.SyspropPublicStub != "" {
734 // This is a sysprop implementation library that has a corresponding sysprop public
735 // stubs library, and a dependency on it so that dependencies on the implementation can
736 // be forwarded to the public stubs library when necessary.
737 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
738 }
739 }
740
741 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000742
743 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700744 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
745
746 // Add dependency on libraries that provide additional hidden api annotations.
747 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
748
749 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
750 // Require java_sdk_library at inter-partition java dependency to ensure stable
751 // interface between partitions. If inter-partition java_library dependency is detected,
752 // raise build error because java_library doesn't have a stable interface.
753 //
754 // Inputs:
755 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
756 // if true, enable enforcement
757 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
758 // exception list of java_library names to allow inter-partition dependency
759 for idx := range j.properties.Libs {
760 if libDeps[idx] == nil {
761 continue
762 }
763
764 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
765 // java_sdk_library is always allowed at inter-partition dependency.
766 // So, skip check.
767 if _, ok := javaDep.(*SdkLibrary); ok {
768 continue
769 }
770
771 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
772 }
773 }
774 }
775
776 // For library dependencies that are component libraries (like stubs), add the implementation
777 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
778 for _, dep := range libDeps {
779 if dep != nil {
780 if component, ok := dep.(SdkLibraryComponentDependency); ok {
781 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100782 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100783 tag := usesLibReqTag
784 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
785 tag = usesLibOptTag
786 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100787 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700788 }
789 }
790 }
791 }
792
793 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
794 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
795 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
796
797 android.ProtoDeps(ctx, &j.protoProperties)
798 if j.hasSrcExt(".proto") {
799 protoDeps(ctx, &j.protoProperties)
800 }
801
802 if j.hasSrcExt(".kt") {
803 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
804 // Kotlin files
805 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
806 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700807 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700808 }
809
810 // Framework libraries need special handling in static coverage builds: they should not have
811 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
812 // the same jacoco classes coming from different bootclasspath jars.
813 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
814 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
815 j.properties.Instrument = true
816 }
817 } else if j.shouldInstrumentStatic(ctx) {
818 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
819 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700820
821 if j.useCompose() {
822 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
823 "androidx.compose.compiler_compiler-hosted")
824 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700825}
826
827func hasSrcExt(srcs []string, ext string) bool {
828 for _, src := range srcs {
829 if filepath.Ext(src) == ext {
830 return true
831 }
832 }
833
834 return false
835}
836
837func (j *Module) hasSrcExt(ext string) bool {
838 return hasSrcExt(j.properties.Srcs, ext)
839}
840
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100841func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
842 var flags string
843
844 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
845 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
846 flags = "-Wmissing-permission-annotation -Werror"
847 }
848 }
849 return flags
850}
851
Jaewoong Jung26342642021-03-17 15:56:23 -0700852func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000853 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700854
855 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
856 aidlIncludes = append(aidlIncludes,
857 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
858 aidlIncludes = append(aidlIncludes,
859 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
860
861 var flags []string
862 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000863 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700864
865 flags = append(flags, j.deviceProperties.Aidl.Flags...)
866
867 if aidlPreprocess.Valid() {
868 flags = append(flags, "-p"+aidlPreprocess.String())
869 deps = append(deps, aidlPreprocess.Path())
870 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000871 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 }
873
874 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000875 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700876 }
877
878 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000879 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700880 }
881
Sam Delmerico2351eac2022-05-24 17:10:02 +0000882 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700883 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000884 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700885 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000886 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
887 // add flags for dirs containing AIDL srcs that haven't been specified yet
888 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700889
Zim8774ae12022-08-17 11:46:34 +0100890 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000891 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100892 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700893 flags = append(flags, "-t")
894 }
895
896 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
897 flags = append(flags, "--transaction_names")
898 }
899
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100900 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
901 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
902 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
903 }
904
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000905 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900906 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
907
Jaewoong Jung26342642021-03-17 15:56:23 -0700908 return strings.Join(flags, " "), deps
909}
910
911func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
912
913 var flags javaBuilderFlags
914
915 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900916 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700917
Cole Faust2b1536e2021-06-18 12:25:54 -0700918 epEnabled := j.properties.Errorprone.Enabled
919 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100920 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700921 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
922 }
923
924 errorProneFlags := []string{
925 "-Xplugin:ErrorProne",
926 "${config.ErrorProneChecks}",
927 }
928 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
929
Colin Cross8bf6cad2022-02-28 13:07:03 -0800930 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700931 "'" + strings.Join(errorProneFlags, " ") + "'"
932 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
933 }
934
935 // classpath
936 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
937 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700938 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700939 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
940 flags.processorPath = append(flags.processorPath, deps.processorPath...)
941 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
942
943 flags.processors = append(flags.processors, deps.processorClasses...)
944 flags.processors = android.FirstUniqueStrings(flags.processors)
945
946 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900947 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700948 // Give host-side tools a version of OpenJDK's standard libraries
949 // close to what they're targeting. As of Dec 2017, AOSP is only
950 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
951 //
952 // When building with OpenJDK 8, the following should have no
953 // effect since those jars would be available by default.
954 //
955 // When building with OpenJDK 9 but targeting a version < 1.8,
956 // putting them on the bootclasspath means that:
957 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
958 // b) references to existing APIs are not reinterpreted in an
959 // OpenJDK 9-specific way, eg. calls to subclasses of
960 // java.nio.Buffer as in http://b/70862583
961 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
962 flags.bootClasspath = append(flags.bootClasspath,
963 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
964 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
965 if Bool(j.properties.Use_tools_jar) {
966 flags.bootClasspath = append(flags.bootClasspath,
967 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
968 }
969 }
970
971 // systemModules
972 flags.systemModules = deps.systemModules
973
Jaewoong Jung26342642021-03-17 15:56:23 -0700974 return flags
975}
976
977func (j *Module) collectJavacFlags(
978 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
979 // javac flags.
980 javacFlags := j.properties.Javacflags
981
982 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
983 // For non-host binaries, override the -g flag passed globally to remove
984 // local variable debug info to reduce disk and memory usage.
985 javacFlags = append(javacFlags, "-g:source,lines")
986 }
987 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
988
989 if flags.javaVersion.usesJavaModules() {
990 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
991
992 if j.properties.Patch_module != nil {
993 // Manually specify build directory in case it is not under the repo root.
994 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
995 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200996 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700997
998 // b/150878007
999 //
1000 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1001 // execution root for --patch-module. If this javac command line is
1002 // invoked within Bazel's execution root working directory, the top
1003 // level directories (e.g. libcore/, tools/, frameworks/) are all
1004 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1005 // --patch-module to fail source file lookups when invoked in the
1006 // execution root.
1007 //
1008 // Short of patching javac or enumerating *all* directories as possible
1009 // input dirs, manually add the top level dir of the source files to be
1010 // compiled.
1011 topLevelDirs := map[string]bool{}
1012 for _, srcFilePath := range srcFiles {
1013 srcFileParts := strings.Split(srcFilePath.String(), "/")
1014 // Ignore source files that are already in the top level directory
1015 // as well as generated files in the out directory. The out
1016 // directory may be an absolute path, which means srcFileParts[0] is the
1017 // empty string, so check that as well. Note that "out" in Bazel's execution
1018 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1019 // anyway, so it's fine to not apply this workaround for generated
1020 // source files.
1021 if len(srcFileParts) > 1 &&
1022 srcFileParts[0] != "" &&
1023 srcFileParts[0] != "out" {
1024 topLevelDirs[srcFileParts[0]] = true
1025 }
1026 }
Cole Faust18994c72023-02-28 16:02:16 -08001027 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001028
1029 classPath := flags.classpath.FormJavaClassPath("")
1030 if classPath != "" {
1031 patchPaths = append(patchPaths, classPath)
1032 }
1033 javacFlags = append(
1034 javacFlags,
1035 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1036 }
1037 }
1038
1039 if len(javacFlags) > 0 {
1040 // optimization.
1041 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1042 flags.javacFlags = "$javacFlags"
1043 }
1044
1045 return flags
1046}
1047
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001048func (j *Module) AddJSONData(d *map[string]interface{}) {
1049 (&j.ModuleBase).AddJSONData(d)
1050 (*d)["Java"] = map[string]interface{}{
1051 "SourceExtensions": j.sourceExtensions,
1052 }
1053
1054}
1055
Joe Onorato175073c2023-06-01 14:42:59 -07001056func (module *Module) addGeneratedSrcJars(path android.Path) {
1057 module.properties.Generated_srcjars = append(module.properties.Generated_srcjars, path)
1058}
1059
Colin Cross4eae06d2023-06-20 22:40:02 -07001060func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001061 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1062
1063 deps := j.collectDeps(ctx)
1064 flags := j.collectBuilderFlags(ctx, deps)
1065
1066 if flags.javaVersion.usesJavaModules() {
1067 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1068 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001069
Jaewoong Jung26342642021-03-17 15:56:23 -07001070 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001071 j.sourceExtensions = []string{}
1072 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1073 if hasSrcExt(srcFiles.Strings(), ext) {
1074 j.sourceExtensions = append(j.sourceExtensions, ext)
1075 }
1076 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001077 if hasSrcExt(srcFiles.Strings(), ".proto") {
1078 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1079 }
1080
1081 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1082 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1083 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1084 }
1085
Sam Delmerico2351eac2022-05-24 17:10:02 +00001086 aidlSrcs := srcFiles.FilterByExt(".aidl")
1087 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1088
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001089 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001090 srcFiles = j.genSources(ctx, srcFiles, flags)
1091
1092 // Collect javac flags only after computing the full set of srcFiles to
1093 // ensure that the --patch-module lookup paths are complete.
1094 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1095
1096 srcJars := srcFiles.FilterByExt(".srcjar")
1097 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001098 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001099 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001100 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001101
1102 if j.properties.Jarjar_rules != nil {
1103 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1104 }
1105
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001106 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001107
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001108 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001109 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001110 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001111 if _, found := set[v.String()]; !found {
1112 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001113 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001114 }
1115 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001116 var uniqueKtFiles android.Paths
1117 for _, v := range srcFiles.FilterByExt(".kt") {
1118 if _, found := set[v.String()]; !found {
1119 set[v.String()] = true
1120 uniqueKtFiles = append(uniqueKtFiles, v)
1121 }
1122 }
1123
1124 var uniqueSrcFiles android.Paths
1125 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1126 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1127 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001128
Colin Crossb5db4012022-03-28 17:12:39 -07001129 // We don't currently run annotation processors in turbine, which means we can't use turbine
1130 // generated header jars when an annotation processor that generates API is enabled. One
1131 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1132 // is used to run all of the annotation processors.
1133 disableTurbine := deps.disableTurbine
1134
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001135 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001136 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1137
1138 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001139 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001140
Colin Cross4eae06d2023-06-20 22:40:02 -07001141 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1142 // any dependencies so that it can override any non-final R classes from dependencies with the
1143 // final R classes from the app.
1144 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1145
Jaewoong Jung26342642021-03-17 15:56:23 -07001146 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001147 // When using kotlin sources turbine is used to generate annotation processor sources,
1148 // including for annotation processors that generate API, so we can use turbine for
1149 // java sources too.
1150 disableTurbine = false
1151
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 // user defined kotlin flags.
1153 kotlincFlags := j.properties.Kotlincflags
1154 CheckKotlincFlags(ctx, kotlincFlags)
1155
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001156 // Workaround for KT-46512
1157 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001158
1159 // If there are kotlin files, compile them first but pass all the kotlin and java files
1160 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1161 // won't emit any classes for them.
1162 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1163 if ctx.Device() {
1164 kotlincFlags = append(kotlincFlags, "-no-jdk")
1165 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001166
1167 for _, plugin := range deps.kotlinPlugins {
1168 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1169 }
1170 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1171
Jaewoong Jung26342642021-03-17 15:56:23 -07001172 if len(kotlincFlags) > 0 {
1173 // optimization.
1174 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1175 flags.kotlincFlags += "$kotlincFlags"
1176 }
1177
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001178 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001179 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1180
1181 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1182 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1183
1184 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1185 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1186
Isaac Chioua23d9942022-04-06 06:14:38 +00001187 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001188 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001189 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1190 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001191 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001192 srcJars = append(srcJars, kaptSrcJar)
1193 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001194 // Disable annotation processing in javac, it's already been handled by kapt
1195 flags.processorPath = nil
1196 flags.processors = nil
1197 }
1198
1199 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001200 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001201 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001202 if ctx.Failed() {
1203 return
1204 }
1205
Isaac Chioua23d9942022-04-06 06:14:38 +00001206 // Make javac rule depend on the kotlinc rule
1207 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1208
Jaewoong Jung26342642021-03-17 15:56:23 -07001209 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001210 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1211
Jaewoong Jung26342642021-03-17 15:56:23 -07001212 // Jar kotlin classes into the final jar after javac
1213 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1214 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001215 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001216 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001217 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001218 } else {
1219 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001220 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001221 }
1222 }
1223
1224 jars := append(android.Paths(nil), kotlinJars...)
1225
Jaewoong Jung26342642021-03-17 15:56:23 -07001226 j.compiledSrcJars = srcJars
1227
1228 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001229 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001230 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001231 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1232 enableSharding = true
1233 // Formerly, there was a check here that prevented annotation processors
1234 // from being used when sharding was enabled, as some annotation processors
1235 // do not function correctly in sharded environments. It was removed to
1236 // allow for the use of annotation processors that do function correctly
1237 // with sharding enabled. See: b/77284273.
1238 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001239 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001240 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001241 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001242 if ctx.Failed() {
1243 return
1244 }
1245 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001246 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001247 hasErrorproneableFiles := false
1248 for _, ext := range j.sourceExtensions {
1249 if ext != ".proto" && ext != ".aidl" {
1250 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1251 // compile, and it's not useful to have warnings on these generated sources.
1252 hasErrorproneableFiles = true
1253 break
1254 }
1255 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001256 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001257 if Bool(j.properties.Errorprone.Enabled) {
1258 // If error-prone is enabled, enable errorprone flags on the regular
1259 // build.
1260 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001261 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001262 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1263 // a new jar file just for compiling with the errorprone compiler to.
1264 // This is because we don't want to cause the java files to get completely
1265 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1266 // We also don't want to run this if errorprone is enabled by default for
1267 // this module, or else we could have duplicated errorprone messages.
1268 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001269 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001270 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001271
Vadim Spivak3c496f02023-06-08 06:14:59 +00001272 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001273 "errorprone", "errorprone")
1274
Jaewoong Jung26342642021-03-17 15:56:23 -07001275 extraJarDeps = append(extraJarDeps, errorprone)
1276 }
1277
1278 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001279 if headerJarFileWithoutDepsOrJarjar != nil {
1280 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1281 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001282 shardSize := int(*(j.properties.Javac_shard_size))
1283 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001284 if len(uniqueJavaFiles) > 0 {
1285 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001286 for idx, shardSrc := range shardSrcs {
1287 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1288 nil, flags, extraJarDeps)
1289 jars = append(jars, classes)
1290 }
1291 }
1292 if len(srcJars) > 0 {
1293 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1294 nil, srcJars, flags, extraJarDeps)
1295 jars = append(jars, classes)
1296 }
1297 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001298 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001299 jars = append(jars, classes)
1300 }
1301 if ctx.Failed() {
1302 return
1303 }
1304 }
1305
1306 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1307
1308 var includeSrcJar android.WritablePath
1309 if Bool(j.properties.Include_srcs) {
1310 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1311 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1312 }
1313
1314 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1315 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1316 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1317 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1318
1319 var resArgs []string
1320 var resDeps android.Paths
1321
1322 resArgs = append(resArgs, dirArgs...)
1323 resDeps = append(resDeps, dirDeps...)
1324
1325 resArgs = append(resArgs, fileArgs...)
1326 resDeps = append(resDeps, fileDeps...)
1327
1328 resArgs = append(resArgs, extraArgs...)
1329 resDeps = append(resDeps, extraDeps...)
1330
1331 if len(resArgs) > 0 {
1332 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1333 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1334 j.resourceJar = resourceJar
1335 if ctx.Failed() {
1336 return
1337 }
1338 }
1339
1340 var resourceJars android.Paths
1341 if j.resourceJar != nil {
1342 resourceJars = append(resourceJars, j.resourceJar)
1343 }
1344 if Bool(j.properties.Include_srcs) {
1345 resourceJars = append(resourceJars, includeSrcJar)
1346 }
1347 resourceJars = append(resourceJars, deps.staticResourceJars...)
1348
1349 if len(resourceJars) > 1 {
1350 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1351 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1352 false, nil, nil)
1353 j.resourceJar = combinedJar
1354 } else if len(resourceJars) == 1 {
1355 j.resourceJar = resourceJars[0]
1356 }
1357
1358 if len(deps.staticJars) > 0 {
1359 jars = append(jars, deps.staticJars...)
1360 }
1361
1362 manifest := j.overrideManifest
1363 if !manifest.Valid() && j.properties.Manifest != nil {
1364 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1365 }
1366
1367 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1368 if len(services) > 0 {
1369 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1370 var zipargs []string
1371 for _, file := range services {
1372 serviceFile := file.String()
1373 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1374 }
1375 rule := zip
1376 args := map[string]string{
1377 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1378 }
1379 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1380 rule = zipRE
1381 args["implicits"] = strings.Join(services.Strings(), ",")
1382 }
1383 ctx.Build(pctx, android.BuildParams{
1384 Rule: rule,
1385 Output: servicesJar,
1386 Implicits: services,
1387 Args: args,
1388 })
1389 jars = append(jars, servicesJar)
1390 }
1391
Colin Cross4eae06d2023-06-20 22:40:02 -07001392 jars = append(android.CopyOf(extraCombinedJars), jars...)
1393
Jaewoong Jung26342642021-03-17 15:56:23 -07001394 // Combine the classes built from sources, any manifests, and any static libraries into
1395 // classes.jar. If there is only one input jar this step will be skipped.
1396 var outputFile android.OutputPath
1397
1398 if len(jars) == 1 && !manifest.Valid() {
1399 // Optimization: skip the combine step as there is nothing to do
1400 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1401 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1402 // any if len(jars) == 1.
1403
Jihoon Kang1147b312023-06-08 23:25:57 +00001404 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1405 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1406 // either with .from-source or .from-text suffix.
1407 // outputFile should be agnostic to the build configuration,
1408 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1409 // to the copy rules.
1410 stub, _ := moduleStubLinkType(ctx.ModuleName())
1411
Jaewoong Jung26342642021-03-17 15:56:23 -07001412 // Transform the single path to the jar into an OutputPath as that is required by the following
1413 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001414 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001415 // The path contains an embedded OutputPath so reuse that.
1416 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001417 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001418 // The path is an OutputPath so reuse it directly.
1419 outputFile = outputPath
1420 } else {
1421 // The file is not in the out directory so create an OutputPath into which it can be copied
1422 // and which the following code can use to refer to it.
1423 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1424 ctx.Build(pctx, android.BuildParams{
1425 Rule: android.Cp,
1426 Input: jars[0],
1427 Output: combinedJar,
1428 })
1429 outputFile = combinedJar.OutputPath
1430 }
1431 } else {
1432 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1433 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1434 false, nil, nil)
1435 outputFile = combinedJar.OutputPath
1436 }
1437
1438 // jarjar implementation jar if necessary
1439 if j.expandJarjarRules != nil {
1440 // Transform classes.jar into classes-jarjar.jar
1441 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1442 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1443 outputFile = jarjarFile
1444
1445 // jarjar resource jar if necessary
1446 if j.resourceJar != nil {
1447 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1448 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1449 j.resourceJar = resourceJarJarFile
1450 }
1451
1452 if ctx.Failed() {
1453 return
1454 }
1455 }
1456
1457 // Check package restrictions if necessary.
1458 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001459 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001460 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001461
1462 // Create a rule to copy the output jar to another path and add a validate dependency that
1463 // will check that the jar only contains the permitted packages. The new location will become
1464 // the output file of this module.
1465 inputFile := outputFile
1466 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1467 ctx.Build(pctx, android.BuildParams{
1468 Rule: android.Cp,
1469 Input: inputFile,
1470 Output: outputFile,
1471 // Make sure that any dependency on the output file will cause ninja to run the package check
1472 // rule.
1473 Validation: pkgckFile,
1474 })
1475
1476 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001477 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001478
1479 if ctx.Failed() {
1480 return
1481 }
1482 }
1483
1484 j.implementationJarFile = outputFile
1485 if j.headerJarFile == nil {
1486 j.headerJarFile = j.implementationJarFile
1487 }
1488
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001489 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1490 specs := j.jacocoModuleToZipCommand(ctx)
1491 if ctx.Failed() {
1492 return
1493 }
1494
Jaewoong Jung26342642021-03-17 15:56:23 -07001495 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001496 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001497 }
1498
1499 // merge implementation jar with resources if necessary
1500 implementationAndResourcesJar := outputFile
1501 if j.resourceJar != nil {
1502 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1503 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1504 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1505 false, nil, nil)
1506 implementationAndResourcesJar = combinedJar
1507 }
1508
1509 j.implementationAndResourcesJar = implementationAndResourcesJar
1510
1511 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001512 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1514 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001515 if compileDex == nil {
1516 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001517 }
1518 if j.deviceProperties.Hostdex == nil {
1519 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1520 }
1521 }
1522
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001523 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001524 if j.hasCode(ctx) {
1525 if j.shouldInstrumentStatic(ctx) {
1526 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1527 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1528 }
1529 // Dex compilation
1530 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001531 params := &compileDexParams{
1532 flags: flags,
1533 sdkVersion: j.SdkVersion(ctx),
1534 minSdkVersion: j.MinSdkVersion(ctx),
1535 classesJar: implementationAndResourcesJar,
1536 jarName: jarName,
1537 }
1538 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001539 if ctx.Failed() {
1540 return
1541 }
1542
Jaewoong Jung26342642021-03-17 15:56:23 -07001543 // merge dex jar with resources if necessary
1544 if j.resourceJar != nil {
1545 jars := android.Paths{dexOutputFile, j.resourceJar}
1546 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1547 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1548 false, nil, nil)
1549 if *j.dexProperties.Uncompress_dex {
1550 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1551 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1552 dexOutputFile = combinedAlignedJar
1553 } else {
1554 dexOutputFile = combinedJar
1555 }
1556 }
1557
Paul Duffin4de94502021-05-16 05:21:16 +01001558 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001559
1560 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001561
1562 // Encode hidden API flags in dex file, if needed.
1563 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1564
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001565 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001566
1567 // Dexpreopting
1568 j.dexpreopt(ctx, dexOutputFile)
1569
1570 outputFile = dexOutputFile
1571 } else {
1572 // There is no code to compile into a dex jar, make sure the resources are propagated
1573 // to the APK if this is an app.
1574 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001575 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001576 }
1577
1578 if ctx.Failed() {
1579 return
1580 }
1581 } else {
1582 outputFile = implementationAndResourcesJar
1583 }
1584
1585 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001586 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1587 if !apiLevel.IsPreview() {
1588 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001590 // When running metalava, we pass --version-codename. When that value
1591 // is not REL, metalava will add 1 to the --current-version argument.
1592 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1593 // branch) and the codename is REL, except potentially on the most
1594 // recent non-master branch. On that branch, it goes through two other
1595 // phases before it gets to the phase previously described:
1596 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1597 // is not rel. This happens for most of the internal branch's life
1598 // while the branch has been cut but is still under active development.
1599 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1600 // REL. This happens briefly during the release process. During this
1601 // state the code to add --current-version is commented out, and then
1602 // that commenting out is reverted after the codename is set to REL.
1603 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1604 // prior version and the codename is always non-REL.
1605 //
1606 // We need to add one here to match metalava adding 1. Technically
1607 // this means that in the state described in the second bullet point
1608 // above, this number is 1 higher than it should be.
1609 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001610 }
1611 }
1612
1613 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001614 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1615 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001616 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1617 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001618 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001619 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001620 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001621 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001622 j.linter.javaLanguageLevel = flags.javaVersion.String()
1623 j.linter.kotlinLanguageLevel = "1.3"
1624 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1625 j.linter.buildModuleReportZip = true
1626 }
1627 j.linter.lint(ctx)
1628 }
1629
1630 ctx.CheckbuildFile(outputFile)
1631
1632 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1633 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001634 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1635 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001636 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1637 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1638 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1639 AidlIncludeDirs: j.exportAidlIncludeDirs,
1640 SrcJarArgs: j.srcJarArgs,
1641 SrcJarDeps: j.srcJarDeps,
1642 ExportedPlugins: j.exportedPluginJars,
1643 ExportedPluginClasses: j.exportedPluginClasses,
1644 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1645 JacocoReportClassesFile: j.jacocoReportClassesFile,
1646 })
1647
1648 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1649 j.outputFile = outputFile.WithoutRel()
1650}
1651
Colin Crossa1ff7c62021-09-17 14:11:52 -07001652func (j *Module) useCompose() bool {
1653 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1654}
1655
Cole Faust75fffb12021-06-13 15:23:16 -07001656// Returns a copy of the supplied flags, but with all the errorprone-related
1657// fields copied to the regular build's fields.
1658func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1659 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1660
1661 if len(flags.errorProneExtraJavacFlags) > 0 {
1662 if len(flags.javacFlags) > 0 {
1663 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1664 } else {
1665 flags.javacFlags = flags.errorProneExtraJavacFlags
1666 }
1667 }
1668 return flags
1669}
1670
Jaewoong Jung26342642021-03-17 15:56:23 -07001671func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1672 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1673
1674 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001675 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001676 if idx >= 0 {
1677 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001678 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001679 jarName += strconv.Itoa(idx)
1680 }
1681
1682 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001683 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001684
1685 if ctx.Config().EmitXrefRules() {
1686 extractionFile := android.PathForModuleOut(ctx, kzipName)
1687 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1688 j.kytheFiles = append(j.kytheFiles, extractionFile)
1689 }
1690
Vadim Spivak3c496f02023-06-08 06:14:59 +00001691 if len(flags.processorPath) > 0 {
1692 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1693 }
1694
Jaewoong Jung26342642021-03-17 15:56:23 -07001695 return classes
1696}
1697
1698// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1699// since some of these flags may be used internally.
1700func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1701 for _, flag := range flags {
1702 flag = strings.TrimSpace(flag)
1703
1704 if !strings.HasPrefix(flag, "-") {
1705 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1706 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1707 ctx.PropertyErrorf("kotlincflags",
1708 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1709 } else if inList(flag, config.KotlincIllegalFlags) {
1710 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1711 } else if flag == "-include-runtime" {
1712 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1713 } else {
1714 args := strings.Split(flag, " ")
1715 if args[0] == "-kotlin-home" {
1716 ctx.PropertyErrorf("kotlincflags",
1717 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1718 }
1719 }
1720 }
1721}
1722
1723func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1724 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001725 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001726
1727 var jars android.Paths
1728 if len(srcFiles) > 0 || len(srcJars) > 0 {
1729 // Compile java sources into turbine.jar.
1730 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1731 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1732 if ctx.Failed() {
1733 return nil, nil
1734 }
1735 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001736 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001737 }
1738
1739 jars = append(jars, extraJars...)
1740
1741 // Combine any static header libraries into classes-header.jar. If there is only
1742 // one input jar this step will be skipped.
1743 jars = append(jars, deps.staticHeaderJars...)
1744
1745 // we cannot skip the combine step for now if there is only one jar
1746 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1747 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1748 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1749 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001750 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001751
1752 if j.expandJarjarRules != nil {
1753 // Transform classes.jar into classes-jarjar.jar
1754 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001755 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1756 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001757 if ctx.Failed() {
1758 return nil, nil
1759 }
1760 }
1761
Colin Cross3d56ed52021-11-18 22:23:12 -08001762 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001763}
1764
1765func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001766 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001767
1768 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1769 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1770
1771 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1772
1773 j.jacocoReportClassesFile = jacocoReportClassesFile
1774
1775 return instrumentedJar
1776}
1777
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001778type providesTransitiveHeaderJars struct {
1779 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001780 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001781 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001782 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001783}
1784
Colin Crossc85750b2022-04-21 12:50:51 -07001785func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001786 return j.transitiveLibsHeaderJars
1787}
1788
Colin Crossc85750b2022-04-21 12:50:51 -07001789func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001790 return j.transitiveStaticLibsHeaderJars
1791}
1792
1793func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1794 directLibs := android.Paths{}
1795 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001796 transitiveLibs := []*android.DepSet[android.Path]{}
1797 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001798 ctx.VisitDirectDeps(func(module android.Module) {
1799 // don't add deps of the prebuilt version of the same library
1800 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1801 return
1802 }
1803
1804 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1805 if dep.TransitiveLibsHeaderJars != nil {
1806 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1807 }
1808 if dep.TransitiveStaticLibsHeaderJars != nil {
1809 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1810 }
1811
1812 tag := ctx.OtherModuleDependencyTag(module)
1813 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1814 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1815 directLibs = append(directLibs, dep.HeaderJars...)
1816 } else if tag == staticLibTag {
1817 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1818 }
1819 })
1820 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1821 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1822}
1823
Jaewoong Jung26342642021-03-17 15:56:23 -07001824func (j *Module) HeaderJars() android.Paths {
1825 if j.headerJarFile == nil {
1826 return nil
1827 }
1828 return android.Paths{j.headerJarFile}
1829}
1830
1831func (j *Module) ImplementationJars() android.Paths {
1832 if j.implementationJarFile == nil {
1833 return nil
1834 }
1835 return android.Paths{j.implementationJarFile}
1836}
1837
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001838func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001839 return j.dexJarFile
1840}
1841
1842func (j *Module) DexJarInstallPath() android.Path {
1843 return j.installFile
1844}
1845
1846func (j *Module) ImplementationAndResourcesJars() android.Paths {
1847 if j.implementationAndResourcesJar == nil {
1848 return nil
1849 }
1850 return android.Paths{j.implementationAndResourcesJar}
1851}
1852
1853func (j *Module) AidlIncludeDirs() android.Paths {
1854 // exportAidlIncludeDirs is type android.Paths already
1855 return j.exportAidlIncludeDirs
1856}
1857
1858func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1859 return j.classLoaderContexts
1860}
1861
1862// Collect information for opening IDE project files in java/jdeps.go.
1863func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1864 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1865 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1866 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1867 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1868 if j.expandJarjarRules != nil {
1869 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1870 }
1871 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001872 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1873 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001874 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001875}
1876
1877func (j *Module) CompilerDeps() []string {
1878 jdeps := []string{}
1879 jdeps = append(jdeps, j.properties.Libs...)
1880 jdeps = append(jdeps, j.properties.Static_libs...)
1881 return jdeps
1882}
1883
1884func (j *Module) hasCode(ctx android.ModuleContext) bool {
1885 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1886 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1887}
1888
1889// Implements android.ApexModule
1890func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1891 return j.depIsInSameApex(ctx, dep)
1892}
1893
1894// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001895func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001896 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001897 minSdkVersion := j.MinSdkVersion(ctx)
1898 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001899 return fmt.Errorf("min_sdk_version is not specified")
1900 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001901 // If the module is compiling against core (via sdk_version), skip comparison check.
1902 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001903 return nil
1904 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001905 if minSdkVersion.GreaterThan(sdkVersion) {
1906 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001907 }
1908 return nil
1909}
1910
1911func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001912 if j.stem == "" {
1913 panic("Stem() called before stem property was set")
1914 }
1915 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07001916}
1917
Jaewoong Jung26342642021-03-17 15:56:23 -07001918func (j *Module) JacocoReportClassesFile() android.Path {
1919 return j.jacocoReportClassesFile
1920}
1921
1922func (j *Module) IsInstallable() bool {
1923 return Bool(j.properties.Installable)
1924}
1925
1926type sdkLinkType int
1927
1928const (
1929 // TODO(jiyong) rename these for better readability. Make the allowed
1930 // and disallowed link types explicit
1931 // order is important here. See rank()
1932 javaCore sdkLinkType = iota
1933 javaSdk
1934 javaSystem
1935 javaModule
1936 javaSystemServer
1937 javaPlatform
1938)
1939
1940func (lt sdkLinkType) String() string {
1941 switch lt {
1942 case javaCore:
1943 return "core Java API"
1944 case javaSdk:
1945 return "Android API"
1946 case javaSystem:
1947 return "system API"
1948 case javaModule:
1949 return "module API"
1950 case javaSystemServer:
1951 return "system server API"
1952 case javaPlatform:
1953 return "private API"
1954 default:
1955 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1956 }
1957}
1958
1959// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1960// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1961// can't statically depend on modules that use Platform API.
1962func (lt sdkLinkType) rank() int {
1963 return int(lt)
1964}
1965
1966type moduleWithSdkDep interface {
1967 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001968 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001969}
1970
Jiyong Park92315372021-04-02 08:45:46 +09001971func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001972 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001973 case android.SdkCore.DefaultJavaLibraryName(),
1974 "legacy.core.platform.api.stubs",
1975 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001977 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001978 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001979 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001980 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001981 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001982 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001983 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001984 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001985 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001986 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001987 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001988 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001989 return javaSystem, true
1990 }
1991
1992 if stub, linkType := moduleStubLinkType(name); stub {
1993 return linkType, true
1994 }
1995
Jiyong Park92315372021-04-02 08:45:46 +09001996 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001997 switch ver.Kind {
1998 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001999 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002000 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002001 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002002 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002003 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002004 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002005 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002006 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002007 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002008 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002009 return javaPlatform, false
2010 }
2011
Jiyong Parkf1691d22021-03-29 20:11:58 +09002012 if !ver.Valid() {
2013 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002014 }
2015 return javaSdk, false
2016}
2017
2018// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2019// this module's. See the comment on rank() for details and an example.
2020func (j *Module) checkSdkLinkType(
2021 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2022 if ctx.Host() {
2023 return
2024 }
2025
Jiyong Park92315372021-04-02 08:45:46 +09002026 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002027 if stubs {
2028 return
2029 }
Jiyong Park92315372021-04-02 08:45:46 +09002030 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002031
2032 if myLinkType.rank() < depLinkType.rank() {
2033 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2034 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2035 "property of the source or target module so that target module is built "+
2036 "with the same or smaller API set when compared to the source.",
2037 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2038 }
2039}
2040
2041func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2042 var deps deps
2043
2044 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002045 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002046 if sdkDep.invalidVersion {
2047 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2048 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2049 } else if sdkDep.useFiles {
2050 // sdkDep.jar is actually equivalent to turbine header.jar.
2051 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002052 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002053 deps.aidlPreprocess = sdkDep.aidl
2054 } else {
2055 deps.aidlPreprocess = sdkDep.aidl
2056 }
2057 }
2058
Jiyong Park92315372021-04-02 08:45:46 +09002059 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002060
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002061 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002062 ctx.VisitDirectDeps(func(module android.Module) {
2063 otherName := ctx.OtherModuleName(module)
2064 tag := ctx.OtherModuleDependencyTag(module)
2065
2066 if IsJniDepTag(tag) {
2067 // Handled by AndroidApp.collectAppDeps
2068 return
2069 }
2070 if tag == certificateTag {
2071 // Handled by AndroidApp.collectAppDeps
2072 return
2073 }
2074
2075 if dep, ok := module.(SdkLibraryDependency); ok {
2076 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002077 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002078 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2079 deps.classpath = append(deps.classpath, depHeaderJars...)
2080 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002081 case staticLibTag:
2082 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2083 }
2084 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2085 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2086 if sdkLinkType != javaPlatform &&
2087 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2088 // dep is a sysprop implementation library, but this module is not linking against
2089 // the platform, so it gets the sysprop public stubs library instead. Replace
2090 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2091 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2092 dep = syspropDep.JavaInfo
2093 }
2094 switch tag {
2095 case bootClasspathTag:
2096 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002097 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002098 if _, ok := module.(*Plugin); ok {
2099 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2100 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002101 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002102 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002103 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2104 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2105 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2106 case java9LibTag:
2107 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2108 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002109 if _, ok := module.(*Plugin); ok {
2110 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2111 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002112 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2113 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2114 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2115 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2116 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2117 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2118 // Turbine doesn't run annotation processors, so any module that uses an
2119 // annotation processor that generates API is incompatible with the turbine
2120 // optimization.
2121 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2122 case pluginTag:
2123 if plugin, ok := module.(*Plugin); ok {
2124 if plugin.pluginProperties.Processor_class != nil {
2125 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2126 } else {
2127 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2128 }
2129 // Turbine doesn't run annotation processors, so any module that uses an
2130 // annotation processor that generates API is incompatible with the turbine
2131 // optimization.
2132 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2133 } else {
2134 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2135 }
2136 case errorpronePluginTag:
2137 if _, ok := module.(*Plugin); ok {
2138 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2139 } else {
2140 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2141 }
2142 case exportedPluginTag:
2143 if plugin, ok := module.(*Plugin); ok {
2144 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2145 if plugin.pluginProperties.Processor_class != nil {
2146 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2147 }
2148 // Turbine doesn't run annotation processors, so any module that uses an
2149 // annotation processor that generates API is incompatible with the turbine
2150 // optimization.
2151 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2152 } else {
2153 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2154 }
2155 case kotlinStdlibTag:
2156 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2157 case kotlinAnnotationsTag:
2158 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002159 case kotlinPluginTag:
2160 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002161 case syspropPublicStubDepTag:
2162 // This is a sysprop implementation library, forward the JavaInfoProvider from
2163 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2164 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2165 JavaInfo: dep,
2166 })
2167 }
2168 } else if dep, ok := module.(android.SourceFileProducer); ok {
2169 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002170 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002171 checkProducesJars(ctx, dep)
2172 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002173 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002174 case staticLibTag:
2175 checkProducesJars(ctx, dep)
2176 deps.classpath = append(deps.classpath, dep.Srcs()...)
2177 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2178 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2179 }
2180 } else {
2181 switch tag {
2182 case bootClasspathTag:
2183 // If a system modules dependency has been added to the bootclasspath
2184 // then add its libs to the bootclasspath.
2185 sm := module.(SystemModulesProvider)
2186 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2187
2188 case systemModulesTag:
2189 if deps.systemModules != nil {
2190 panic("Found two system module dependencies")
2191 }
2192 sm := module.(SystemModulesProvider)
2193 outputDir, outputDeps := sm.OutputDirAndDeps()
2194 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002195
2196 case instrumentationForTag:
2197 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 -07002198 }
2199 }
2200
2201 addCLCFromDep(ctx, module, j.classLoaderContexts)
2202 })
2203
2204 return deps
2205}
2206
2207func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2208 deps.processorPath = append(deps.processorPath, pluginJars...)
2209 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2210}
2211
2212// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2213// this interface.
2214type ProvidesUsesLib interface {
2215 ProvidesUsesLib() *string
2216}
2217
2218func (j *Module) ProvidesUsesLib() *string {
2219 return j.usesLibraryProperties.Provides_uses_lib
2220}
satayev1c564cc2021-05-25 19:50:30 +01002221
2222type ModuleWithStem interface {
2223 Stem() string
2224}
2225
2226var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002227
2228func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2229 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002230 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002231 if lib, ok := ctx.Module().(*Library); ok {
2232 javaLibraryBp2Build(ctx, lib)
2233 }
2234 case "java_binary_host":
2235 if binary, ok := ctx.Module().(*Binary); ok {
2236 javaBinaryHostBp2Build(ctx, binary)
2237 }
Zi Wang65b36722023-05-23 15:18:33 -07002238 case "java_test_host":
2239 if testHost, ok := ctx.Module().(*TestHost); ok {
2240 javaTestHostBp2Build(ctx, testHost)
2241 }
Chris Parsons39a16972023-06-08 14:28:51 +00002242 default:
2243 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002244 }
Wei Libafb6d62021-12-10 03:14:59 -08002245}