blob: 2b81f5e36a9ba699a0d21b78f7d857389bd095a0 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
Chris Parsons39a16972023-06-08 14:28:51 +000023 "android/soong/ui/metrics/bp2build_metrics_proto"
Jaewoong Jung26342642021-03-17 15:56:23 -070024 "github.com/google/blueprint/pathtools"
25 "github.com/google/blueprint/proptools"
26
27 "android/soong/android"
28 "android/soong/dexpreopt"
29 "android/soong/java/config"
30)
31
32// This file contains the definition and the implementation of the base module that most
33// source-based Java module structs embed.
34
35// TODO:
36// Autogenerated files:
37// Renderscript
38// Post-jar passes:
39// Proguard
40// Rmtypedefs
41// DroidDoc
42// Findbugs
43
44// Properties that are common to most Java modules, i.e. whether it's a host or device module.
45type CommonProperties struct {
46 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
47 // or .aidl files.
48 Srcs []string `android:"path,arch_variant"`
49
50 // list Kotlin of source files containing Kotlin code that should be treated as common code in
51 // a codebase that supports Kotlin multiplatform. See
52 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
53 Common_srcs []string `android:"path,arch_variant"`
54
55 // list of source files that should not be used to build the Java module.
56 // This is most useful in the arch/multilib variants to remove non-common files
57 Exclude_srcs []string `android:"path,arch_variant"`
58
59 // list of directories containing Java resources
60 Java_resource_dirs []string `android:"arch_variant"`
61
62 // list of directories that should be excluded from java_resource_dirs
63 Exclude_java_resource_dirs []string `android:"arch_variant"`
64
65 // list of files to use as Java resources
66 Java_resources []string `android:"path,arch_variant"`
67
68 // list of files that should be excluded from java_resources and java_resource_dirs
69 Exclude_java_resources []string `android:"path,arch_variant"`
70
71 // list of module-specific flags that will be used for javac compiles
72 Javacflags []string `android:"arch_variant"`
73
74 // list of module-specific flags that will be used for kotlinc compiles
75 Kotlincflags []string `android:"arch_variant"`
76
77 // list of java libraries that will be in the classpath
78 Libs []string `android:"arch_variant"`
79
80 // list of java libraries that will be compiled into the resulting jar
81 Static_libs []string `android:"arch_variant"`
82
Jihoon Kang381c2fa2023-06-01 22:17:32 +000083 // list of java libraries that should not be used to build this module
84 Exclude_static_libs []string `android:"arch_variant"`
85
Jaewoong Jung26342642021-03-17 15:56:23 -070086 // manifest file to be included in resulting jar
87 Manifest *string `android:"path"`
88
89 // if not blank, run jarjar using the specified rules file
90 Jarjar_rules *string `android:"path,arch_variant"`
91
92 // If not blank, set the java version passed to javac as -source and -target
93 Java_version *string
94
95 // If set to true, allow this module to be dexed and installed on devices. Has no
96 // effect on host modules, which are always considered installable.
97 Installable *bool
98
99 // If set to true, include sources used to compile the module in to the final jar
100 Include_srcs *bool
101
102 // If not empty, classes are restricted to the specified packages and their sub-packages.
103 // This restriction is checked after applying jarjar rules and including static libs.
104 Permitted_packages []string
105
106 // List of modules to use as annotation processors
107 Plugins []string
108
109 // List of modules to export to libraries that directly depend on this library as annotation
110 // processors. Note that if the plugins set generates_api: true this will disable the turbine
111 // optimization on modules that depend on this module, which will reduce parallelism and cause
112 // more recompilation.
113 Exported_plugins []string
114
115 // The number of Java source entries each Javac instance can process
116 Javac_shard_size *int64
117
118 // Add host jdk tools.jar to bootclasspath
119 Use_tools_jar *bool
120
121 Openjdk9 struct {
122 // List of source files that should only be used when passing -source 1.9 or higher
123 Srcs []string `android:"path"`
124
125 // List of javac flags that should only be used when passing -source 1.9 or higher
126 Javacflags []string
127 }
128
129 // When compiling language level 9+ .java code in packages that are part of
130 // a system module, patch_module names the module that your sources and
131 // dependencies should be patched into. The Android runtime currently
132 // doesn't implement the JEP 261 module system so this option is only
133 // supported at compile time. It should only be needed to compile tests in
134 // packages that exist in libcore and which are inconvenient to move
135 // elsewhere.
136 Patch_module *string `android:"arch_variant"`
137
138 Jacoco struct {
139 // List of classes to include for instrumentation with jacoco to collect coverage
140 // information at runtime when building with coverage enabled. If unset defaults to all
141 // classes.
142 // Supports '*' as the last character of an entry in the list as a wildcard match.
143 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
144 // it matches classes in the package that have the class name as a prefix.
145 Include_filter []string
146
147 // List of classes to exclude from instrumentation with jacoco to collect coverage
148 // information at runtime when building with coverage enabled. Overrides classes selected
149 // by the include_filter property.
150 // Supports '*' as the last character of an entry in the list as a wildcard match.
151 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
152 // it matches classes in the package that have the class name as a prefix.
153 Exclude_filter []string
154 }
155
156 Errorprone struct {
157 // List of javac flags that should only be used when running errorprone.
158 Javacflags []string
159
160 // List of java_plugin modules that provide extra errorprone checks.
161 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700162
Cole Faust2b1536e2021-06-18 12:25:54 -0700163 // This property can be in 3 states. When set to true, errorprone will
164 // be run during the regular build. When set to false, errorprone will
165 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
166 // environment variable is true. Setting this to false will improve build
167 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700168 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700169 }
170
171 Proto struct {
172 // List of extra options that will be passed to the proto generator.
173 Output_params []string
174 }
175
Sam Delmericoc7593722022-08-31 15:57:52 -0400176 // If true, then jacocoagent is automatically added as a libs dependency so that
177 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700178 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000179 // If true, then the module supports statically including the jacocoagent
180 // into the library.
181 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700182
183 // List of files to include in the META-INF/services folder of the resulting jar.
184 Services []string `android:"path,arch_variant"`
185
186 // If true, package the kotlin stdlib into the jar. Defaults to true.
187 Static_kotlin_stdlib *bool `android:"arch_variant"`
188
189 // A list of java_library instances that provide additional hiddenapi annotations for the library.
190 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700191
192 // Additional srcJars tacked in by GeneratedJavaLibraryModule
193 Generated_srcjars []android.Path `android:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700194}
195
196// Properties that are specific to device modules. Host module factories should not add these when
197// constructing a new module.
198type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000199 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000200 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000201 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000202 // 1) numerical API level, "current", "none", or "core_platform"
203 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
204 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
205 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Sdk_version *string
207
208 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000209 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700210 Min_sdk_version *string
211
satayev0a420e72021-11-29 17:25:52 +0000212 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
213 // Defaults to empty string "". See sdk_version for possible values.
214 Max_sdk_version *string
215
William Loh5a082f92022-05-17 20:21:50 +0000216 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
217 // Defaults to empty string "". See sdk_version for possible values.
218 Replace_max_sdk_version_placeholder *string
219
Jaewoong Jung26342642021-03-17 15:56:23 -0700220 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000221 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700222 Target_sdk_version *string
223
224 // Whether to compile against the platform APIs instead of an SDK.
225 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000226 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700227 Platform_apis *bool
228
229 Aidl struct {
230 // Top level directories to pass to aidl tool
231 Include_dirs []string
232
233 // Directories rooted at the Android.bp file to pass to aidl tool
234 Local_include_dirs []string
235
236 // directories that should be added as include directories for any aidl sources of modules
237 // that depend on this module, as well as to aidl for this module.
238 Export_include_dirs []string
239
240 // whether to generate traces (for systrace) for this interface
241 Generate_traces *bool
242
243 // whether to generate Binder#GetTransaction name method.
244 Generate_get_transaction_name *bool
245
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100246 // whether all interfaces should be annotated with required permissions.
247 Enforce_permissions *bool
248
249 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
250 Enforce_permissions_exceptions []string `android:"path"`
251
Jaewoong Jung26342642021-03-17 15:56:23 -0700252 // list of flags that will be passed to the AIDL compiler
253 Flags []string
254 }
255
256 // If true, export a copy of the module as a -hostdex module for host testing.
257 Hostdex *bool
258
259 Target struct {
260 Hostdex struct {
261 // Additional required dependencies to add to -hostdex modules.
262 Required []string
263 }
264 }
265
266 // When targeting 1.9 and above, override the modules to use with --system,
267 // otherwise provides defaults libraries to add to the bootclasspath.
268 System_modules *string
269
Jaewoong Jung26342642021-03-17 15:56:23 -0700270 IsSDKLibrary bool `blueprint:"mutated"`
271
272 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
273 // Defaults to false.
274 V4_signature *bool
275
276 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
277 // public stubs library.
278 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000279
280 HiddenAPIPackageProperties
281 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700282}
283
Jooyung Han01d80d82022-01-08 12:16:32 +0900284// Device properties that can be overridden by overriding module (e.g. override_android_app)
285type OverridableDeviceProperties struct {
286 // set the name of the output. If not set, `name` is used.
287 // To override a module with this property set, overriding module might need to set this as well.
288 // Otherwise, both the overridden and the overriding modules will have the same output name, which
289 // can cause the duplicate output error.
290 Stem *string
291}
292
Jaewoong Jung26342642021-03-17 15:56:23 -0700293// Functionality common to Module and Import
294//
295// It is embedded in Module so its functionality can be used by methods in Module
296// but it is currently only initialized by Import and Library.
297type embeddableInModuleAndImport struct {
298
299 // Functionality related to this being used as a component of a java_sdk_library.
300 EmbeddableSdkLibraryComponent
301}
302
Paul Duffin71b33cc2021-06-23 11:39:47 +0100303func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
304 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700305}
306
307// Module/Import's DepIsInSameApex(...) delegates to this method.
308//
309// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
310// the one provided by ApexModuleBase.
311func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
312 // dependencies other than the static linkage are all considered crossing APEX boundary
313 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
314 return true
315 }
316 return false
317}
318
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100319// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
320// or an invalid path describing the reason it is invalid.
321//
322// It is unset if a dex jar isn't applicable, i.e. no build rule has been
323// requested to create one.
324//
325// If a dex jar has been requested to be built then it is set, and it may be
326// either a valid android.Path, or invalid with a reason message. The latter
327// happens if the source that should produce the dex file isn't able to.
328//
329// E.g. it is invalid with a reason message if there is a prebuilt APEX that
330// could produce the dex jar through a deapexer module, but the APEX isn't
331// installable so doing so wouldn't be safe.
332type OptionalDexJarPath struct {
333 isSet bool
334 path android.OptionalPath
335}
336
337// IsSet returns true if a path has been set, either invalid or valid.
338func (o OptionalDexJarPath) IsSet() bool {
339 return o.isSet
340}
341
342// Valid returns true if there is a path that is valid.
343func (o OptionalDexJarPath) Valid() bool {
344 return o.isSet && o.path.Valid()
345}
346
347// Path returns the valid path, or panics if it's either not set or is invalid.
348func (o OptionalDexJarPath) Path() android.Path {
349 if !o.isSet {
350 panic("path isn't set")
351 }
352 return o.path.Path()
353}
354
355// PathOrNil returns the path if it's set and valid, or else nil.
356func (o OptionalDexJarPath) PathOrNil() android.Path {
357 if o.Valid() {
358 return o.Path()
359 }
360 return nil
361}
362
363// InvalidReason returns the reason for an invalid path, which is never "". It
364// returns "" for an unset or valid path.
365func (o OptionalDexJarPath) InvalidReason() string {
366 if !o.isSet {
367 return ""
368 }
369 return o.path.InvalidReason()
370}
371
372func (o OptionalDexJarPath) String() string {
373 if !o.isSet {
374 return "<unset>"
375 }
376 return o.path.String()
377}
378
379// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
380func makeUnsetDexJarPath() OptionalDexJarPath {
381 return OptionalDexJarPath{isSet: false}
382}
383
384// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
385// the given OptionalPath, which may be valid or invalid.
386func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
387 return OptionalDexJarPath{isSet: true, path: path}
388}
389
390// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
391// valid given path. It returns an unset OptionalDexJarPath if the given path is
392// nil.
393func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
394 if path == nil {
395 return makeUnsetDexJarPath()
396 }
397 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
398}
399
Jaewoong Jung26342642021-03-17 15:56:23 -0700400// Module contains the properties and members used by all java module types
401type Module struct {
402 android.ModuleBase
403 android.DefaultableModuleBase
404 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800405 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700406
407 // Functionality common to Module and Import.
408 embeddableInModuleAndImport
409
410 properties CommonProperties
411 protoProperties android.ProtoProperties
412 deviceProperties DeviceProperties
413
Jooyung Han01d80d82022-01-08 12:16:32 +0900414 overridableDeviceProperties OverridableDeviceProperties
415
Jaewoong Jung26342642021-03-17 15:56:23 -0700416 // jar file containing header classes including static library dependencies, suitable for
417 // inserting into the bootclasspath/classpath of another compile
418 headerJarFile android.Path
419
420 // jar file containing implementation classes including static library dependencies but no
421 // resources
422 implementationJarFile android.Path
423
424 // jar file containing only resources including from static library dependencies
425 resourceJar android.Path
426
427 // args and dependencies to package source files into a srcjar
428 srcJarArgs []string
429 srcJarDeps android.Paths
430
431 // jar file containing implementation classes and resources including static library
432 // dependencies
433 implementationAndResourcesJar android.Path
434
435 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100436 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700437
438 // output file containing uninstrumented classes that will be instrumented by jacoco
439 jacocoReportClassesFile android.Path
440
441 // output file of the module, which may be a classes jar or a dex jar
442 outputFile android.Path
443 extraOutputFiles android.Paths
444
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100445 exportAidlIncludeDirs android.Paths
446 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700447
448 logtagsSrcs android.Paths
449
450 // installed file for binary dependency
451 installFile android.Path
452
Colin Cross3108ce12021-11-10 14:38:50 -0800453 // installed file for hostdex copy
454 hostdexInstallFile android.InstallPath
455
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800456 // list of unique .java and .kt source files
457 uniqueSrcFiles android.Paths
458
459 // list of srcjars that was passed to javac
460 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700461
462 // manifest file to use instead of properties.Manifest
463 overrideManifest android.OptionalPath
464
Jaewoong Jung26342642021-03-17 15:56:23 -0700465 // list of plugins that this java module is exporting
466 exportedPluginJars android.Paths
467
468 // list of plugins that this java module is exporting
469 exportedPluginClasses []string
470
471 // if true, the exported plugins generate API and require disabling turbine.
472 exportedDisableTurbine bool
473
474 // list of source files, collected from srcFiles with unique java and all kt files,
475 // will be used by android.IDEInfo struct
476 expandIDEInfoCompiledSrcs []string
477
478 // expanded Jarjar_rules
479 expandJarjarRules android.Path
480
Jaewoong Jung26342642021-03-17 15:56:23 -0700481 // Extra files generated by the module type to be added as java resources.
482 extraResources android.Paths
483
484 hiddenAPI
485 dexer
486 dexpreopter
487 usesLibrary
488 linter
489
490 // list of the xref extraction files
491 kytheFiles android.Paths
492
493 // Collect the module directory for IDE info in java/jdeps.go.
494 modulePaths []string
495
496 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900497
498 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000499 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000500 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400501
502 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700503}
504
Jiyong Park92315372021-04-02 08:45:46 +0900505func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
506 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900507 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700508 return nil
509 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900510 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000511 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700512 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
513 } else {
514 // Treat stable core platform as stable.
515 return nil
516 }
517 } else {
518 return fmt.Errorf("non stable SDK %v", sdkVersion)
519 }
520}
521
522// checkSdkVersions enforces restrictions around SDK dependencies.
523func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
524 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900525 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900526 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700527 ctx.PropertyErrorf("sdk_version",
528 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
529 }
530 }
531 }
532
533 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
534 // See rank() for details.
535 ctx.VisitDirectDeps(func(module android.Module) {
536 tag := ctx.OtherModuleDependencyTag(module)
537 switch module.(type) {
538 // TODO(satayev): cover other types as well, e.g. imports
539 case *Library, *AndroidLibrary:
540 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400541 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700542 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
543 }
544 }
545 })
546}
547
548func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900549 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700550 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900551 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700552 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000553 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 -0700554 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000555 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 -0700556 }
557
558 }
559}
560
561func (j *Module) addHostProperties() {
562 j.AddProperties(
563 &j.properties,
564 &j.protoProperties,
565 &j.usesLibraryProperties,
566 )
567}
568
569func (j *Module) addHostAndDeviceProperties() {
570 j.addHostProperties()
571 j.AddProperties(
572 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900573 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700574 &j.dexer.dexProperties,
575 &j.dexpreoptProperties,
576 &j.linter.properties,
577 )
578}
579
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000580// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
581// makes it available through the hiddenAPIPropertyInfoProvider.
582func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
583 hiddenAPIInfo := newHiddenAPIPropertyInfo()
584
585 // Populate with flag file paths from the properties.
586 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
587
588 // Populate with package rules from the properties.
589 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
590
591 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
592}
593
Jaewoong Jung26342642021-03-17 15:56:23 -0700594func (j *Module) OutputFiles(tag string) (android.Paths, error) {
595 switch tag {
596 case "":
597 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
598 case android.DefaultDistTag:
599 return android.Paths{j.outputFile}, nil
600 case ".jar":
601 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700602 case ".hjar":
603 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700604 case ".proguard_map":
605 if j.dexer.proguardDictionary.Valid() {
606 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
607 }
608 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
609 default:
610 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
611 }
612}
613
614var _ android.OutputFileProducer = (*Module)(nil)
615
616func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
617 initJavaModule(module, hod, false)
618}
619
620func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
621 initJavaModule(module, hod, true)
622}
623
624func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
625 multilib := android.MultilibCommon
626 if multiTargets {
627 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
628 } else {
629 android.InitAndroidArchModule(module, hod, multilib)
630 }
631 android.InitDefaultableModule(module)
632}
633
634func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
635 return j.properties.Instrument &&
636 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
637 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
638}
639
640func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000641 return j.properties.Supports_static_instrumentation &&
642 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700643 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
644 ctx.Config().UnbundledBuild())
645}
646
647func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
648 // Force enable the instrumentation for java code that is built for APEXes ...
649 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
650 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
651 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
652 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
653 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
654 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
655 return true
656 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
657 return true
658 }
659 }
660 return false
661}
662
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400663func (j *Module) setInstrument(value bool) {
664 j.properties.Instrument = value
665}
666
Jiyong Park92315372021-04-02 08:45:46 +0900667func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
668 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700669}
670
Jiyong Parkf1691d22021-03-29 20:11:58 +0900671func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700672 return proptools.String(j.deviceProperties.System_modules)
673}
674
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000675func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700676 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000677 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700678 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000679 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700680}
681
Spandan Dasa26eda72023-03-02 00:56:06 +0000682func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
683 if j.deviceProperties.Max_sdk_version != nil {
684 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
685 }
686 // Default is PrivateApiLevel
687 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000688}
689
Spandan Dasa26eda72023-03-02 00:56:06 +0000690func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
691 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
692 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
693 }
694 // Default is PrivateApiLevel
695 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000696}
697
Jiyong Parkf1691d22021-03-29 20:11:58 +0900698func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000699 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900700}
701
Spandan Dasca70fc42023-03-01 23:38:49 +0000702func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900703 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000704 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900705 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000706 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700707}
708
709func (j *Module) AvailableFor(what string) bool {
710 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
711 // Exception: for hostdex: true libraries, the platform variant is created
712 // even if it's not marked as available to platform. In that case, the platform
713 // variant is used only for the hostdex and not installed to the device.
714 return true
715 }
716 return j.ApexModuleBase.AvailableFor(what)
717}
718
719func (j *Module) deps(ctx android.BottomUpMutatorContext) {
720 if ctx.Device() {
721 j.linter.deps(ctx)
722
Jiyong Parkf1691d22021-03-29 20:11:58 +0900723 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700724
725 if j.deviceProperties.SyspropPublicStub != "" {
726 // This is a sysprop implementation library that has a corresponding sysprop public
727 // stubs library, and a dependency on it so that dependencies on the implementation can
728 // be forwarded to the public stubs library when necessary.
729 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
730 }
731 }
732
733 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000734
735 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700736 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
737
738 // Add dependency on libraries that provide additional hidden api annotations.
739 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
740
741 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
742 // Require java_sdk_library at inter-partition java dependency to ensure stable
743 // interface between partitions. If inter-partition java_library dependency is detected,
744 // raise build error because java_library doesn't have a stable interface.
745 //
746 // Inputs:
747 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
748 // if true, enable enforcement
749 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
750 // exception list of java_library names to allow inter-partition dependency
751 for idx := range j.properties.Libs {
752 if libDeps[idx] == nil {
753 continue
754 }
755
756 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
757 // java_sdk_library is always allowed at inter-partition dependency.
758 // So, skip check.
759 if _, ok := javaDep.(*SdkLibrary); ok {
760 continue
761 }
762
763 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
764 }
765 }
766 }
767
768 // For library dependencies that are component libraries (like stubs), add the implementation
769 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
770 for _, dep := range libDeps {
771 if dep != nil {
772 if component, ok := dep.(SdkLibraryComponentDependency); ok {
773 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100774 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100775 tag := usesLibReqTag
776 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
777 tag = usesLibOptTag
778 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100779 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700780 }
781 }
782 }
783 }
784
785 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
786 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
787 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
788
789 android.ProtoDeps(ctx, &j.protoProperties)
790 if j.hasSrcExt(".proto") {
791 protoDeps(ctx, &j.protoProperties)
792 }
793
794 if j.hasSrcExt(".kt") {
795 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
796 // Kotlin files
797 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
798 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700799 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700800 }
801
802 // Framework libraries need special handling in static coverage builds: they should not have
803 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
804 // the same jacoco classes coming from different bootclasspath jars.
805 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
806 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
807 j.properties.Instrument = true
808 }
809 } else if j.shouldInstrumentStatic(ctx) {
810 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
811 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700812
813 if j.useCompose() {
814 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
815 "androidx.compose.compiler_compiler-hosted")
816 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700817}
818
819func hasSrcExt(srcs []string, ext string) bool {
820 for _, src := range srcs {
821 if filepath.Ext(src) == ext {
822 return true
823 }
824 }
825
826 return false
827}
828
829func (j *Module) hasSrcExt(ext string) bool {
830 return hasSrcExt(j.properties.Srcs, ext)
831}
832
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100833func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
834 var flags string
835
836 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
837 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
838 flags = "-Wmissing-permission-annotation -Werror"
839 }
840 }
841 return flags
842}
843
Jaewoong Jung26342642021-03-17 15:56:23 -0700844func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000845 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700846
847 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
848 aidlIncludes = append(aidlIncludes,
849 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
850 aidlIncludes = append(aidlIncludes,
851 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
852
853 var flags []string
854 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000855 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700856
857 flags = append(flags, j.deviceProperties.Aidl.Flags...)
858
859 if aidlPreprocess.Valid() {
860 flags = append(flags, "-p"+aidlPreprocess.String())
861 deps = append(deps, aidlPreprocess.Path())
862 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000863 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700864 }
865
866 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000867 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700868 }
869
870 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000871 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 }
873
Sam Delmerico2351eac2022-05-24 17:10:02 +0000874 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700875 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000876 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700877 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000878 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
879 // add flags for dirs containing AIDL srcs that haven't been specified yet
880 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
Zim8774ae12022-08-17 11:46:34 +0100882 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000883 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100884 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700885 flags = append(flags, "-t")
886 }
887
888 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
889 flags = append(flags, "--transaction_names")
890 }
891
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100892 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
893 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
894 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
895 }
896
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000897 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900898 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
899
Jaewoong Jung26342642021-03-17 15:56:23 -0700900 return strings.Join(flags, " "), deps
901}
902
903func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
904
905 var flags javaBuilderFlags
906
907 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900908 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700909
Cole Faust2b1536e2021-06-18 12:25:54 -0700910 epEnabled := j.properties.Errorprone.Enabled
911 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100912 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700913 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
914 }
915
916 errorProneFlags := []string{
917 "-Xplugin:ErrorProne",
918 "${config.ErrorProneChecks}",
919 }
920 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
921
Colin Cross8bf6cad2022-02-28 13:07:03 -0800922 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700923 "'" + strings.Join(errorProneFlags, " ") + "'"
924 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
925 }
926
927 // classpath
928 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
929 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700930 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700931 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
932 flags.processorPath = append(flags.processorPath, deps.processorPath...)
933 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
934
935 flags.processors = append(flags.processors, deps.processorClasses...)
936 flags.processors = android.FirstUniqueStrings(flags.processors)
937
938 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900939 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700940 // Give host-side tools a version of OpenJDK's standard libraries
941 // close to what they're targeting. As of Dec 2017, AOSP is only
942 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
943 //
944 // When building with OpenJDK 8, the following should have no
945 // effect since those jars would be available by default.
946 //
947 // When building with OpenJDK 9 but targeting a version < 1.8,
948 // putting them on the bootclasspath means that:
949 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
950 // b) references to existing APIs are not reinterpreted in an
951 // OpenJDK 9-specific way, eg. calls to subclasses of
952 // java.nio.Buffer as in http://b/70862583
953 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
954 flags.bootClasspath = append(flags.bootClasspath,
955 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
956 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
957 if Bool(j.properties.Use_tools_jar) {
958 flags.bootClasspath = append(flags.bootClasspath,
959 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
960 }
961 }
962
963 // systemModules
964 flags.systemModules = deps.systemModules
965
Jaewoong Jung26342642021-03-17 15:56:23 -0700966 return flags
967}
968
969func (j *Module) collectJavacFlags(
970 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
971 // javac flags.
972 javacFlags := j.properties.Javacflags
973
974 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
975 // For non-host binaries, override the -g flag passed globally to remove
976 // local variable debug info to reduce disk and memory usage.
977 javacFlags = append(javacFlags, "-g:source,lines")
978 }
979 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
980
981 if flags.javaVersion.usesJavaModules() {
982 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
983
984 if j.properties.Patch_module != nil {
985 // Manually specify build directory in case it is not under the repo root.
986 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
987 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200988 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700989
990 // b/150878007
991 //
992 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
993 // execution root for --patch-module. If this javac command line is
994 // invoked within Bazel's execution root working directory, the top
995 // level directories (e.g. libcore/, tools/, frameworks/) are all
996 // symlinks. JDK9 javac does not traverse into symlinks, which causes
997 // --patch-module to fail source file lookups when invoked in the
998 // execution root.
999 //
1000 // Short of patching javac or enumerating *all* directories as possible
1001 // input dirs, manually add the top level dir of the source files to be
1002 // compiled.
1003 topLevelDirs := map[string]bool{}
1004 for _, srcFilePath := range srcFiles {
1005 srcFileParts := strings.Split(srcFilePath.String(), "/")
1006 // Ignore source files that are already in the top level directory
1007 // as well as generated files in the out directory. The out
1008 // directory may be an absolute path, which means srcFileParts[0] is the
1009 // empty string, so check that as well. Note that "out" in Bazel's execution
1010 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1011 // anyway, so it's fine to not apply this workaround for generated
1012 // source files.
1013 if len(srcFileParts) > 1 &&
1014 srcFileParts[0] != "" &&
1015 srcFileParts[0] != "out" {
1016 topLevelDirs[srcFileParts[0]] = true
1017 }
1018 }
Cole Faust18994c72023-02-28 16:02:16 -08001019 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001020
1021 classPath := flags.classpath.FormJavaClassPath("")
1022 if classPath != "" {
1023 patchPaths = append(patchPaths, classPath)
1024 }
1025 javacFlags = append(
1026 javacFlags,
1027 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1028 }
1029 }
1030
1031 if len(javacFlags) > 0 {
1032 // optimization.
1033 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1034 flags.javacFlags = "$javacFlags"
1035 }
1036
1037 return flags
1038}
1039
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001040func (j *Module) AddJSONData(d *map[string]interface{}) {
1041 (&j.ModuleBase).AddJSONData(d)
1042 (*d)["Java"] = map[string]interface{}{
1043 "SourceExtensions": j.sourceExtensions,
1044 }
1045
1046}
1047
Joe Onorato175073c2023-06-01 14:42:59 -07001048func (module *Module) addGeneratedSrcJars(path android.Path) {
1049 module.properties.Generated_srcjars = append(module.properties.Generated_srcjars, path)
1050}
1051
Jaewoong Jung26342642021-03-17 15:56:23 -07001052func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1053 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1054
1055 deps := j.collectDeps(ctx)
1056 flags := j.collectBuilderFlags(ctx, deps)
1057
1058 if flags.javaVersion.usesJavaModules() {
1059 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1060 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001061
Jaewoong Jung26342642021-03-17 15:56:23 -07001062 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001063 j.sourceExtensions = []string{}
1064 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1065 if hasSrcExt(srcFiles.Strings(), ext) {
1066 j.sourceExtensions = append(j.sourceExtensions, ext)
1067 }
1068 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001069 if hasSrcExt(srcFiles.Strings(), ".proto") {
1070 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1071 }
1072
1073 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1074 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1075 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1076 }
1077
Sam Delmerico2351eac2022-05-24 17:10:02 +00001078 aidlSrcs := srcFiles.FilterByExt(".aidl")
1079 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1080
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001081 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001082 srcFiles = j.genSources(ctx, srcFiles, flags)
1083
1084 // Collect javac flags only after computing the full set of srcFiles to
1085 // ensure that the --patch-module lookup paths are complete.
1086 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1087
1088 srcJars := srcFiles.FilterByExt(".srcjar")
1089 srcJars = append(srcJars, deps.srcJars...)
1090 if aaptSrcJar != nil {
1091 srcJars = append(srcJars, aaptSrcJar)
1092 }
Joe Onorato175073c2023-06-01 14:42:59 -07001093 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001094 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001095
1096 if j.properties.Jarjar_rules != nil {
1097 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1098 }
1099
1100 jarName := ctx.ModuleName() + ".jar"
1101
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001102 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001103 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001104 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001105 if _, found := set[v.String()]; !found {
1106 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001107 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001108 }
1109 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001110 var uniqueKtFiles android.Paths
1111 for _, v := range srcFiles.FilterByExt(".kt") {
1112 if _, found := set[v.String()]; !found {
1113 set[v.String()] = true
1114 uniqueKtFiles = append(uniqueKtFiles, v)
1115 }
1116 }
1117
1118 var uniqueSrcFiles android.Paths
1119 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1120 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1121 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001122
Colin Crossb5db4012022-03-28 17:12:39 -07001123 // We don't currently run annotation processors in turbine, which means we can't use turbine
1124 // generated header jars when an annotation processor that generates API is enabled. One
1125 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1126 // is used to run all of the annotation processors.
1127 disableTurbine := deps.disableTurbine
1128
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001129 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001130 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1131
1132 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001133 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001134
1135 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001136 // When using kotlin sources turbine is used to generate annotation processor sources,
1137 // including for annotation processors that generate API, so we can use turbine for
1138 // java sources too.
1139 disableTurbine = false
1140
Jaewoong Jung26342642021-03-17 15:56:23 -07001141 // user defined kotlin flags.
1142 kotlincFlags := j.properties.Kotlincflags
1143 CheckKotlincFlags(ctx, kotlincFlags)
1144
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001145 // Workaround for KT-46512
1146 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001147
1148 // If there are kotlin files, compile them first but pass all the kotlin and java files
1149 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1150 // won't emit any classes for them.
1151 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1152 if ctx.Device() {
1153 kotlincFlags = append(kotlincFlags, "-no-jdk")
1154 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001155
1156 for _, plugin := range deps.kotlinPlugins {
1157 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1158 }
1159 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1160
Jaewoong Jung26342642021-03-17 15:56:23 -07001161 if len(kotlincFlags) > 0 {
1162 // optimization.
1163 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1164 flags.kotlincFlags += "$kotlincFlags"
1165 }
1166
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001167 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001168 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1169
1170 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1171 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1172
1173 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1174 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1175
Isaac Chioua23d9942022-04-06 06:14:38 +00001176 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001177 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001178 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1179 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001180 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001181 srcJars = append(srcJars, kaptSrcJar)
1182 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 // Disable annotation processing in javac, it's already been handled by kapt
1184 flags.processorPath = nil
1185 flags.processors = nil
1186 }
1187
1188 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001189 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001190 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001191 if ctx.Failed() {
1192 return
1193 }
1194
Isaac Chioua23d9942022-04-06 06:14:38 +00001195 // Make javac rule depend on the kotlinc rule
1196 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1197
Jaewoong Jung26342642021-03-17 15:56:23 -07001198 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001199 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1200
Jaewoong Jung26342642021-03-17 15:56:23 -07001201 // Jar kotlin classes into the final jar after javac
1202 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1203 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001204 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001205 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001206 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001207 } else {
1208 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001209 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001210 }
1211 }
1212
1213 jars := append(android.Paths(nil), kotlinJars...)
1214
Jaewoong Jung26342642021-03-17 15:56:23 -07001215 j.compiledSrcJars = srcJars
1216
1217 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001218 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001219 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1221 enableSharding = true
1222 // Formerly, there was a check here that prevented annotation processors
1223 // from being used when sharding was enabled, as some annotation processors
1224 // do not function correctly in sharded environments. It was removed to
1225 // allow for the use of annotation processors that do function correctly
1226 // with sharding enabled. See: b/77284273.
1227 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001228 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001229 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001230 if ctx.Failed() {
1231 return
1232 }
1233 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001234 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001235 hasErrorproneableFiles := false
1236 for _, ext := range j.sourceExtensions {
1237 if ext != ".proto" && ext != ".aidl" {
1238 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1239 // compile, and it's not useful to have warnings on these generated sources.
1240 hasErrorproneableFiles = true
1241 break
1242 }
1243 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001244 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001245 if Bool(j.properties.Errorprone.Enabled) {
1246 // If error-prone is enabled, enable errorprone flags on the regular
1247 // build.
1248 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001249 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001250 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1251 // a new jar file just for compiling with the errorprone compiler to.
1252 // This is because we don't want to cause the java files to get completely
1253 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1254 // We also don't want to run this if errorprone is enabled by default for
1255 // this module, or else we could have duplicated errorprone messages.
1256 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001257 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001258
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001259 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001260 "errorprone", "errorprone")
1261
Jaewoong Jung26342642021-03-17 15:56:23 -07001262 extraJarDeps = append(extraJarDeps, errorprone)
1263 }
1264
1265 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001266 if headerJarFileWithoutDepsOrJarjar != nil {
1267 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1268 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001269 shardSize := int(*(j.properties.Javac_shard_size))
1270 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001271 if len(uniqueJavaFiles) > 0 {
1272 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001273 for idx, shardSrc := range shardSrcs {
1274 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1275 nil, flags, extraJarDeps)
1276 jars = append(jars, classes)
1277 }
1278 }
1279 if len(srcJars) > 0 {
1280 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1281 nil, srcJars, flags, extraJarDeps)
1282 jars = append(jars, classes)
1283 }
1284 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001285 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001286 jars = append(jars, classes)
1287 }
1288 if ctx.Failed() {
1289 return
1290 }
1291 }
1292
1293 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1294
1295 var includeSrcJar android.WritablePath
1296 if Bool(j.properties.Include_srcs) {
1297 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1298 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1299 }
1300
1301 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1302 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1303 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1304 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1305
1306 var resArgs []string
1307 var resDeps android.Paths
1308
1309 resArgs = append(resArgs, dirArgs...)
1310 resDeps = append(resDeps, dirDeps...)
1311
1312 resArgs = append(resArgs, fileArgs...)
1313 resDeps = append(resDeps, fileDeps...)
1314
1315 resArgs = append(resArgs, extraArgs...)
1316 resDeps = append(resDeps, extraDeps...)
1317
1318 if len(resArgs) > 0 {
1319 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1320 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1321 j.resourceJar = resourceJar
1322 if ctx.Failed() {
1323 return
1324 }
1325 }
1326
1327 var resourceJars android.Paths
1328 if j.resourceJar != nil {
1329 resourceJars = append(resourceJars, j.resourceJar)
1330 }
1331 if Bool(j.properties.Include_srcs) {
1332 resourceJars = append(resourceJars, includeSrcJar)
1333 }
1334 resourceJars = append(resourceJars, deps.staticResourceJars...)
1335
1336 if len(resourceJars) > 1 {
1337 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1338 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1339 false, nil, nil)
1340 j.resourceJar = combinedJar
1341 } else if len(resourceJars) == 1 {
1342 j.resourceJar = resourceJars[0]
1343 }
1344
1345 if len(deps.staticJars) > 0 {
1346 jars = append(jars, deps.staticJars...)
1347 }
1348
1349 manifest := j.overrideManifest
1350 if !manifest.Valid() && j.properties.Manifest != nil {
1351 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1352 }
1353
1354 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1355 if len(services) > 0 {
1356 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1357 var zipargs []string
1358 for _, file := range services {
1359 serviceFile := file.String()
1360 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1361 }
1362 rule := zip
1363 args := map[string]string{
1364 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1365 }
1366 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1367 rule = zipRE
1368 args["implicits"] = strings.Join(services.Strings(), ",")
1369 }
1370 ctx.Build(pctx, android.BuildParams{
1371 Rule: rule,
1372 Output: servicesJar,
1373 Implicits: services,
1374 Args: args,
1375 })
1376 jars = append(jars, servicesJar)
1377 }
1378
1379 // Combine the classes built from sources, any manifests, and any static libraries into
1380 // classes.jar. If there is only one input jar this step will be skipped.
1381 var outputFile android.OutputPath
1382
1383 if len(jars) == 1 && !manifest.Valid() {
1384 // Optimization: skip the combine step as there is nothing to do
1385 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1386 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1387 // any if len(jars) == 1.
1388
1389 // Transform the single path to the jar into an OutputPath as that is required by the following
1390 // code.
1391 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1392 // The path contains an embedded OutputPath so reuse that.
1393 outputFile = moduleOutPath.OutputPath
1394 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1395 // The path is an OutputPath so reuse it directly.
1396 outputFile = outputPath
1397 } else {
1398 // The file is not in the out directory so create an OutputPath into which it can be copied
1399 // and which the following code can use to refer to it.
1400 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1401 ctx.Build(pctx, android.BuildParams{
1402 Rule: android.Cp,
1403 Input: jars[0],
1404 Output: combinedJar,
1405 })
1406 outputFile = combinedJar.OutputPath
1407 }
1408 } else {
1409 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1410 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1411 false, nil, nil)
1412 outputFile = combinedJar.OutputPath
1413 }
1414
1415 // jarjar implementation jar if necessary
1416 if j.expandJarjarRules != nil {
1417 // Transform classes.jar into classes-jarjar.jar
1418 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1419 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1420 outputFile = jarjarFile
1421
1422 // jarjar resource jar if necessary
1423 if j.resourceJar != nil {
1424 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1425 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1426 j.resourceJar = resourceJarJarFile
1427 }
1428
1429 if ctx.Failed() {
1430 return
1431 }
1432 }
1433
1434 // Check package restrictions if necessary.
1435 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001436 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001437 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001438
1439 // Create a rule to copy the output jar to another path and add a validate dependency that
1440 // will check that the jar only contains the permitted packages. The new location will become
1441 // the output file of this module.
1442 inputFile := outputFile
1443 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1444 ctx.Build(pctx, android.BuildParams{
1445 Rule: android.Cp,
1446 Input: inputFile,
1447 Output: outputFile,
1448 // Make sure that any dependency on the output file will cause ninja to run the package check
1449 // rule.
1450 Validation: pkgckFile,
1451 })
1452
1453 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001454 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001455
1456 if ctx.Failed() {
1457 return
1458 }
1459 }
1460
1461 j.implementationJarFile = outputFile
1462 if j.headerJarFile == nil {
1463 j.headerJarFile = j.implementationJarFile
1464 }
1465
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001466 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1467 specs := j.jacocoModuleToZipCommand(ctx)
1468 if ctx.Failed() {
1469 return
1470 }
1471
Jaewoong Jung26342642021-03-17 15:56:23 -07001472 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001473 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001474 }
1475
1476 // merge implementation jar with resources if necessary
1477 implementationAndResourcesJar := outputFile
1478 if j.resourceJar != nil {
1479 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1480 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1481 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1482 false, nil, nil)
1483 implementationAndResourcesJar = combinedJar
1484 }
1485
1486 j.implementationAndResourcesJar = implementationAndResourcesJar
1487
1488 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001489 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001490 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1491 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001492 if compileDex == nil {
1493 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001494 }
1495 if j.deviceProperties.Hostdex == nil {
1496 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1497 }
1498 }
1499
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001500 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 if j.hasCode(ctx) {
1502 if j.shouldInstrumentStatic(ctx) {
1503 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1504 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1505 }
1506 // Dex compilation
1507 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001508 params := &compileDexParams{
1509 flags: flags,
1510 sdkVersion: j.SdkVersion(ctx),
1511 minSdkVersion: j.MinSdkVersion(ctx),
1512 classesJar: implementationAndResourcesJar,
1513 jarName: jarName,
1514 }
1515 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001516 if ctx.Failed() {
1517 return
1518 }
1519
Jaewoong Jung26342642021-03-17 15:56:23 -07001520 // merge dex jar with resources if necessary
1521 if j.resourceJar != nil {
1522 jars := android.Paths{dexOutputFile, j.resourceJar}
1523 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1524 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1525 false, nil, nil)
1526 if *j.dexProperties.Uncompress_dex {
1527 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1528 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1529 dexOutputFile = combinedAlignedJar
1530 } else {
1531 dexOutputFile = combinedJar
1532 }
1533 }
1534
Paul Duffin4de94502021-05-16 05:21:16 +01001535 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001536
1537 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001538
1539 // Encode hidden API flags in dex file, if needed.
1540 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1541
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001542 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001543
1544 // Dexpreopting
1545 j.dexpreopt(ctx, dexOutputFile)
1546
1547 outputFile = dexOutputFile
1548 } else {
1549 // There is no code to compile into a dex jar, make sure the resources are propagated
1550 // to the APK if this is an app.
1551 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001552 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001553 }
1554
1555 if ctx.Failed() {
1556 return
1557 }
1558 } else {
1559 outputFile = implementationAndResourcesJar
1560 }
1561
1562 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001563 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1564 if !apiLevel.IsPreview() {
1565 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001566 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001567 // When running metalava, we pass --version-codename. When that value
1568 // is not REL, metalava will add 1 to the --current-version argument.
1569 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1570 // branch) and the codename is REL, except potentially on the most
1571 // recent non-master branch. On that branch, it goes through two other
1572 // phases before it gets to the phase previously described:
1573 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1574 // is not rel. This happens for most of the internal branch's life
1575 // while the branch has been cut but is still under active development.
1576 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1577 // REL. This happens briefly during the release process. During this
1578 // state the code to add --current-version is commented out, and then
1579 // that commenting out is reverted after the codename is set to REL.
1580 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1581 // prior version and the codename is always non-REL.
1582 //
1583 // We need to add one here to match metalava adding 1. Technically
1584 // this means that in the state described in the second bullet point
1585 // above, this number is 1 higher than it should be.
1586 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001587 }
1588 }
1589
1590 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001591 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1592 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001593 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1594 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001595 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001596 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001597 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001598 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001599 j.linter.javaLanguageLevel = flags.javaVersion.String()
1600 j.linter.kotlinLanguageLevel = "1.3"
1601 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1602 j.linter.buildModuleReportZip = true
1603 }
1604 j.linter.lint(ctx)
1605 }
1606
1607 ctx.CheckbuildFile(outputFile)
1608
1609 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1610 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001611 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1612 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001613 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1614 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1615 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1616 AidlIncludeDirs: j.exportAidlIncludeDirs,
1617 SrcJarArgs: j.srcJarArgs,
1618 SrcJarDeps: j.srcJarDeps,
1619 ExportedPlugins: j.exportedPluginJars,
1620 ExportedPluginClasses: j.exportedPluginClasses,
1621 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1622 JacocoReportClassesFile: j.jacocoReportClassesFile,
1623 })
1624
1625 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1626 j.outputFile = outputFile.WithoutRel()
1627}
1628
Colin Crossa1ff7c62021-09-17 14:11:52 -07001629func (j *Module) useCompose() bool {
1630 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1631}
1632
Cole Faust75fffb12021-06-13 15:23:16 -07001633// Returns a copy of the supplied flags, but with all the errorprone-related
1634// fields copied to the regular build's fields.
1635func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1636 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1637
1638 if len(flags.errorProneExtraJavacFlags) > 0 {
1639 if len(flags.javacFlags) > 0 {
1640 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1641 } else {
1642 flags.javacFlags = flags.errorProneExtraJavacFlags
1643 }
1644 }
1645 return flags
1646}
1647
Jaewoong Jung26342642021-03-17 15:56:23 -07001648func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1649 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1650
1651 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1652 if idx >= 0 {
1653 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1654 jarName += strconv.Itoa(idx)
1655 }
1656
1657 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1658 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1659
1660 if ctx.Config().EmitXrefRules() {
1661 extractionFile := android.PathForModuleOut(ctx, kzipName)
1662 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1663 j.kytheFiles = append(j.kytheFiles, extractionFile)
1664 }
1665
1666 return classes
1667}
1668
1669// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1670// since some of these flags may be used internally.
1671func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1672 for _, flag := range flags {
1673 flag = strings.TrimSpace(flag)
1674
1675 if !strings.HasPrefix(flag, "-") {
1676 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1677 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1678 ctx.PropertyErrorf("kotlincflags",
1679 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1680 } else if inList(flag, config.KotlincIllegalFlags) {
1681 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1682 } else if flag == "-include-runtime" {
1683 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1684 } else {
1685 args := strings.Split(flag, " ")
1686 if args[0] == "-kotlin-home" {
1687 ctx.PropertyErrorf("kotlincflags",
1688 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1689 }
1690 }
1691 }
1692}
1693
1694func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1695 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001696 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001697
1698 var jars android.Paths
1699 if len(srcFiles) > 0 || len(srcJars) > 0 {
1700 // Compile java sources into turbine.jar.
1701 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1702 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1703 if ctx.Failed() {
1704 return nil, nil
1705 }
1706 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001707 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001708 }
1709
1710 jars = append(jars, extraJars...)
1711
1712 // Combine any static header libraries into classes-header.jar. If there is only
1713 // one input jar this step will be skipped.
1714 jars = append(jars, deps.staticHeaderJars...)
1715
1716 // we cannot skip the combine step for now if there is only one jar
1717 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1718 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1719 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1720 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001721 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001722
1723 if j.expandJarjarRules != nil {
1724 // Transform classes.jar into classes-jarjar.jar
1725 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001726 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1727 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 if ctx.Failed() {
1729 return nil, nil
1730 }
1731 }
1732
Colin Cross3d56ed52021-11-18 22:23:12 -08001733 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001734}
1735
1736func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001737 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001738
1739 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1740 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1741
1742 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1743
1744 j.jacocoReportClassesFile = jacocoReportClassesFile
1745
1746 return instrumentedJar
1747}
1748
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001749type providesTransitiveHeaderJars struct {
1750 // set of header jars for all transitive libs deps
1751 transitiveLibsHeaderJars *android.DepSet
1752 // set of header jars for all transitive static libs deps
1753 transitiveStaticLibsHeaderJars *android.DepSet
1754}
1755
1756func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
1757 return j.transitiveLibsHeaderJars
1758}
1759
1760func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
1761 return j.transitiveStaticLibsHeaderJars
1762}
1763
1764func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1765 directLibs := android.Paths{}
1766 directStaticLibs := android.Paths{}
1767 transitiveLibs := []*android.DepSet{}
1768 transitiveStaticLibs := []*android.DepSet{}
1769 ctx.VisitDirectDeps(func(module android.Module) {
1770 // don't add deps of the prebuilt version of the same library
1771 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1772 return
1773 }
1774
1775 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1776 if dep.TransitiveLibsHeaderJars != nil {
1777 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1778 }
1779 if dep.TransitiveStaticLibsHeaderJars != nil {
1780 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1781 }
1782
1783 tag := ctx.OtherModuleDependencyTag(module)
1784 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1785 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1786 directLibs = append(directLibs, dep.HeaderJars...)
1787 } else if tag == staticLibTag {
1788 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1789 }
1790 })
1791 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1792 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1793}
1794
Jaewoong Jung26342642021-03-17 15:56:23 -07001795func (j *Module) HeaderJars() android.Paths {
1796 if j.headerJarFile == nil {
1797 return nil
1798 }
1799 return android.Paths{j.headerJarFile}
1800}
1801
1802func (j *Module) ImplementationJars() android.Paths {
1803 if j.implementationJarFile == nil {
1804 return nil
1805 }
1806 return android.Paths{j.implementationJarFile}
1807}
1808
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001809func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001810 return j.dexJarFile
1811}
1812
1813func (j *Module) DexJarInstallPath() android.Path {
1814 return j.installFile
1815}
1816
1817func (j *Module) ImplementationAndResourcesJars() android.Paths {
1818 if j.implementationAndResourcesJar == nil {
1819 return nil
1820 }
1821 return android.Paths{j.implementationAndResourcesJar}
1822}
1823
1824func (j *Module) AidlIncludeDirs() android.Paths {
1825 // exportAidlIncludeDirs is type android.Paths already
1826 return j.exportAidlIncludeDirs
1827}
1828
1829func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1830 return j.classLoaderContexts
1831}
1832
1833// Collect information for opening IDE project files in java/jdeps.go.
1834func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1835 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1836 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1837 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1838 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1839 if j.expandJarjarRules != nil {
1840 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1841 }
1842 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001843 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1844 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001845}
1846
1847func (j *Module) CompilerDeps() []string {
1848 jdeps := []string{}
1849 jdeps = append(jdeps, j.properties.Libs...)
1850 jdeps = append(jdeps, j.properties.Static_libs...)
1851 return jdeps
1852}
1853
1854func (j *Module) hasCode(ctx android.ModuleContext) bool {
1855 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1856 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1857}
1858
1859// Implements android.ApexModule
1860func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1861 return j.depIsInSameApex(ctx, dep)
1862}
1863
1864// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001865func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001866 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001867 minSdkVersion := j.MinSdkVersion(ctx)
1868 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001869 return fmt.Errorf("min_sdk_version is not specified")
1870 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001871 // If the module is compiling against core (via sdk_version), skip comparison check.
1872 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001873 return nil
1874 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001875 if minSdkVersion.GreaterThan(sdkVersion) {
1876 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001877 }
1878 return nil
1879}
1880
1881func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001882 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001883}
1884
Jaewoong Jung26342642021-03-17 15:56:23 -07001885func (j *Module) JacocoReportClassesFile() android.Path {
1886 return j.jacocoReportClassesFile
1887}
1888
1889func (j *Module) IsInstallable() bool {
1890 return Bool(j.properties.Installable)
1891}
1892
1893type sdkLinkType int
1894
1895const (
1896 // TODO(jiyong) rename these for better readability. Make the allowed
1897 // and disallowed link types explicit
1898 // order is important here. See rank()
1899 javaCore sdkLinkType = iota
1900 javaSdk
1901 javaSystem
1902 javaModule
1903 javaSystemServer
1904 javaPlatform
1905)
1906
1907func (lt sdkLinkType) String() string {
1908 switch lt {
1909 case javaCore:
1910 return "core Java API"
1911 case javaSdk:
1912 return "Android API"
1913 case javaSystem:
1914 return "system API"
1915 case javaModule:
1916 return "module API"
1917 case javaSystemServer:
1918 return "system server API"
1919 case javaPlatform:
1920 return "private API"
1921 default:
1922 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1923 }
1924}
1925
1926// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1927// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1928// can't statically depend on modules that use Platform API.
1929func (lt sdkLinkType) rank() int {
1930 return int(lt)
1931}
1932
1933type moduleWithSdkDep interface {
1934 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001935 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001936}
1937
Jiyong Park92315372021-04-02 08:45:46 +09001938func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001939 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001940 case android.SdkCore.DefaultJavaLibraryName(),
1941 "legacy.core.platform.api.stubs",
1942 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001943 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001944 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001945 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001946 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001947 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001948 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001949 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001950 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001951 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001952 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001953 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001954 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001955 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001956 return javaSystem, true
1957 }
1958
1959 if stub, linkType := moduleStubLinkType(name); stub {
1960 return linkType, true
1961 }
1962
Jiyong Park92315372021-04-02 08:45:46 +09001963 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001964 switch ver.Kind {
1965 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001966 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001967 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001968 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001969 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001970 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001971 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001972 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001973 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001974 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001975 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 return javaPlatform, false
1977 }
1978
Jiyong Parkf1691d22021-03-29 20:11:58 +09001979 if !ver.Valid() {
1980 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001981 }
1982 return javaSdk, false
1983}
1984
1985// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1986// this module's. See the comment on rank() for details and an example.
1987func (j *Module) checkSdkLinkType(
1988 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1989 if ctx.Host() {
1990 return
1991 }
1992
Jiyong Park92315372021-04-02 08:45:46 +09001993 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001994 if stubs {
1995 return
1996 }
Jiyong Park92315372021-04-02 08:45:46 +09001997 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001998
1999 if myLinkType.rank() < depLinkType.rank() {
2000 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2001 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2002 "property of the source or target module so that target module is built "+
2003 "with the same or smaller API set when compared to the source.",
2004 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2005 }
2006}
2007
2008func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2009 var deps deps
2010
2011 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002012 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002013 if sdkDep.invalidVersion {
2014 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2015 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2016 } else if sdkDep.useFiles {
2017 // sdkDep.jar is actually equivalent to turbine header.jar.
2018 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002019 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002020 deps.aidlPreprocess = sdkDep.aidl
2021 } else {
2022 deps.aidlPreprocess = sdkDep.aidl
2023 }
2024 }
2025
Jiyong Park92315372021-04-02 08:45:46 +09002026 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002027
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002028 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002029 ctx.VisitDirectDeps(func(module android.Module) {
2030 otherName := ctx.OtherModuleName(module)
2031 tag := ctx.OtherModuleDependencyTag(module)
2032
2033 if IsJniDepTag(tag) {
2034 // Handled by AndroidApp.collectAppDeps
2035 return
2036 }
2037 if tag == certificateTag {
2038 // Handled by AndroidApp.collectAppDeps
2039 return
2040 }
2041
2042 if dep, ok := module.(SdkLibraryDependency); ok {
2043 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002044 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002045 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2046 deps.classpath = append(deps.classpath, depHeaderJars...)
2047 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002048 case staticLibTag:
2049 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2050 }
2051 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2052 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2053 if sdkLinkType != javaPlatform &&
2054 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2055 // dep is a sysprop implementation library, but this module is not linking against
2056 // the platform, so it gets the sysprop public stubs library instead. Replace
2057 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2058 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2059 dep = syspropDep.JavaInfo
2060 }
2061 switch tag {
2062 case bootClasspathTag:
2063 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002064 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002065 if _, ok := module.(*Plugin); ok {
2066 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2067 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002068 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002069 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002070 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2071 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2072 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2073 case java9LibTag:
2074 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2075 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002076 if _, ok := module.(*Plugin); ok {
2077 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2078 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002079 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2080 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2081 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2082 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2083 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2084 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2085 // Turbine doesn't run annotation processors, so any module that uses an
2086 // annotation processor that generates API is incompatible with the turbine
2087 // optimization.
2088 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2089 case pluginTag:
2090 if plugin, ok := module.(*Plugin); ok {
2091 if plugin.pluginProperties.Processor_class != nil {
2092 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2093 } else {
2094 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2095 }
2096 // Turbine doesn't run annotation processors, so any module that uses an
2097 // annotation processor that generates API is incompatible with the turbine
2098 // optimization.
2099 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2100 } else {
2101 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2102 }
2103 case errorpronePluginTag:
2104 if _, ok := module.(*Plugin); ok {
2105 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2106 } else {
2107 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2108 }
2109 case exportedPluginTag:
2110 if plugin, ok := module.(*Plugin); ok {
2111 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2112 if plugin.pluginProperties.Processor_class != nil {
2113 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2114 }
2115 // Turbine doesn't run annotation processors, so any module that uses an
2116 // annotation processor that generates API is incompatible with the turbine
2117 // optimization.
2118 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2119 } else {
2120 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2121 }
2122 case kotlinStdlibTag:
2123 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2124 case kotlinAnnotationsTag:
2125 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002126 case kotlinPluginTag:
2127 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002128 case syspropPublicStubDepTag:
2129 // This is a sysprop implementation library, forward the JavaInfoProvider from
2130 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2131 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2132 JavaInfo: dep,
2133 })
2134 }
2135 } else if dep, ok := module.(android.SourceFileProducer); ok {
2136 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002137 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002138 checkProducesJars(ctx, dep)
2139 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002140 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002141 case staticLibTag:
2142 checkProducesJars(ctx, dep)
2143 deps.classpath = append(deps.classpath, dep.Srcs()...)
2144 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2145 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2146 }
2147 } else {
2148 switch tag {
2149 case bootClasspathTag:
2150 // If a system modules dependency has been added to the bootclasspath
2151 // then add its libs to the bootclasspath.
2152 sm := module.(SystemModulesProvider)
2153 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2154
2155 case systemModulesTag:
2156 if deps.systemModules != nil {
2157 panic("Found two system module dependencies")
2158 }
2159 sm := module.(SystemModulesProvider)
2160 outputDir, outputDeps := sm.OutputDirAndDeps()
2161 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002162
2163 case instrumentationForTag:
2164 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 -07002165 }
2166 }
2167
2168 addCLCFromDep(ctx, module, j.classLoaderContexts)
2169 })
2170
2171 return deps
2172}
2173
2174func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2175 deps.processorPath = append(deps.processorPath, pluginJars...)
2176 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2177}
2178
2179// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2180// this interface.
2181type ProvidesUsesLib interface {
2182 ProvidesUsesLib() *string
2183}
2184
2185func (j *Module) ProvidesUsesLib() *string {
2186 return j.usesLibraryProperties.Provides_uses_lib
2187}
satayev1c564cc2021-05-25 19:50:30 +01002188
2189type ModuleWithStem interface {
2190 Stem() string
2191}
2192
2193var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002194
2195func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2196 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002197 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002198 if lib, ok := ctx.Module().(*Library); ok {
2199 javaLibraryBp2Build(ctx, lib)
2200 }
2201 case "java_binary_host":
2202 if binary, ok := ctx.Module().(*Binary); ok {
2203 javaBinaryHostBp2Build(ctx, binary)
2204 }
Zi Wang65b36722023-05-23 15:18:33 -07002205 case "java_test_host":
2206 if testHost, ok := ctx.Module().(*TestHost); ok {
2207 javaTestHostBp2Build(ctx, testHost)
2208 }
Chris Parsons39a16972023-06-08 14:28:51 +00002209 default:
2210 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002211 }
Wei Libafb6d62021-12-10 03:14:59 -08002212}