blob: ed61e12edf78da95ad4a916b04d8f7bbb0e29791 [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
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
Jihoon Kang381c2fa2023-06-01 22:17:32 +000082 // list of java libraries that should not be used to build this module
83 Exclude_static_libs []string `android:"arch_variant"`
84
Jaewoong Jung26342642021-03-17 15:56:23 -070085 // manifest file to be included in resulting jar
86 Manifest *string `android:"path"`
87
88 // if not blank, run jarjar using the specified rules file
89 Jarjar_rules *string `android:"path,arch_variant"`
90
91 // If not blank, set the java version passed to javac as -source and -target
92 Java_version *string
93
94 // If set to true, allow this module to be dexed and installed on devices. Has no
95 // effect on host modules, which are always considered installable.
96 Installable *bool
97
98 // If set to true, include sources used to compile the module in to the final jar
99 Include_srcs *bool
100
101 // If not empty, classes are restricted to the specified packages and their sub-packages.
102 // This restriction is checked after applying jarjar rules and including static libs.
103 Permitted_packages []string
104
105 // List of modules to use as annotation processors
106 Plugins []string
107
108 // List of modules to export to libraries that directly depend on this library as annotation
109 // processors. Note that if the plugins set generates_api: true this will disable the turbine
110 // optimization on modules that depend on this module, which will reduce parallelism and cause
111 // more recompilation.
112 Exported_plugins []string
113
114 // The number of Java source entries each Javac instance can process
115 Javac_shard_size *int64
116
117 // Add host jdk tools.jar to bootclasspath
118 Use_tools_jar *bool
119
120 Openjdk9 struct {
121 // List of source files that should only be used when passing -source 1.9 or higher
122 Srcs []string `android:"path"`
123
124 // List of javac flags that should only be used when passing -source 1.9 or higher
125 Javacflags []string
126 }
127
128 // When compiling language level 9+ .java code in packages that are part of
129 // a system module, patch_module names the module that your sources and
130 // dependencies should be patched into. The Android runtime currently
131 // doesn't implement the JEP 261 module system so this option is only
132 // supported at compile time. It should only be needed to compile tests in
133 // packages that exist in libcore and which are inconvenient to move
134 // elsewhere.
135 Patch_module *string `android:"arch_variant"`
136
137 Jacoco struct {
138 // List of classes to include for instrumentation with jacoco to collect coverage
139 // information at runtime when building with coverage enabled. If unset defaults to all
140 // classes.
141 // Supports '*' as the last character of an entry in the list as a wildcard match.
142 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
143 // it matches classes in the package that have the class name as a prefix.
144 Include_filter []string
145
146 // List of classes to exclude from instrumentation with jacoco to collect coverage
147 // information at runtime when building with coverage enabled. Overrides classes selected
148 // by the include_filter property.
149 // Supports '*' as the last character of an entry in the list as a wildcard match.
150 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
151 // it matches classes in the package that have the class name as a prefix.
152 Exclude_filter []string
153 }
154
155 Errorprone struct {
156 // List of javac flags that should only be used when running errorprone.
157 Javacflags []string
158
159 // List of java_plugin modules that provide extra errorprone checks.
160 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700161
Cole Faust2b1536e2021-06-18 12:25:54 -0700162 // This property can be in 3 states. When set to true, errorprone will
163 // be run during the regular build. When set to false, errorprone will
164 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
165 // environment variable is true. Setting this to false will improve build
166 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700167 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700168 }
169
170 Proto struct {
171 // List of extra options that will be passed to the proto generator.
172 Output_params []string
173 }
174
Sam Delmericoc7593722022-08-31 15:57:52 -0400175 // If true, then jacocoagent is automatically added as a libs dependency so that
176 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700177 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000178 // If true, then the module supports statically including the jacocoagent
179 // into the library.
180 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700181
182 // List of files to include in the META-INF/services folder of the resulting jar.
183 Services []string `android:"path,arch_variant"`
184
185 // If true, package the kotlin stdlib into the jar. Defaults to true.
186 Static_kotlin_stdlib *bool `android:"arch_variant"`
187
188 // A list of java_library instances that provide additional hiddenapi annotations for the library.
189 Hiddenapi_additional_annotations []string
190}
191
192// Properties that are specific to device modules. Host module factories should not add these when
193// constructing a new module.
194type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000195 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000196 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000197 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000198 // 1) numerical API level, "current", "none", or "core_platform"
199 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
200 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
201 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700202 Sdk_version *string
203
204 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Min_sdk_version *string
207
satayev0a420e72021-11-29 17:25:52 +0000208 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
209 // Defaults to empty string "". See sdk_version for possible values.
210 Max_sdk_version *string
211
William Loh5a082f92022-05-17 20:21:50 +0000212 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
213 // Defaults to empty string "". See sdk_version for possible values.
214 Replace_max_sdk_version_placeholder *string
215
Jaewoong Jung26342642021-03-17 15:56:23 -0700216 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000217 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700218 Target_sdk_version *string
219
220 // Whether to compile against the platform APIs instead of an SDK.
221 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000222 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700223 Platform_apis *bool
224
225 Aidl struct {
226 // Top level directories to pass to aidl tool
227 Include_dirs []string
228
229 // Directories rooted at the Android.bp file to pass to aidl tool
230 Local_include_dirs []string
231
232 // directories that should be added as include directories for any aidl sources of modules
233 // that depend on this module, as well as to aidl for this module.
234 Export_include_dirs []string
235
236 // whether to generate traces (for systrace) for this interface
237 Generate_traces *bool
238
239 // whether to generate Binder#GetTransaction name method.
240 Generate_get_transaction_name *bool
241
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100242 // whether all interfaces should be annotated with required permissions.
243 Enforce_permissions *bool
244
245 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
246 Enforce_permissions_exceptions []string `android:"path"`
247
Jaewoong Jung26342642021-03-17 15:56:23 -0700248 // list of flags that will be passed to the AIDL compiler
249 Flags []string
250 }
251
252 // If true, export a copy of the module as a -hostdex module for host testing.
253 Hostdex *bool
254
255 Target struct {
256 Hostdex struct {
257 // Additional required dependencies to add to -hostdex modules.
258 Required []string
259 }
260 }
261
262 // When targeting 1.9 and above, override the modules to use with --system,
263 // otherwise provides defaults libraries to add to the bootclasspath.
264 System_modules *string
265
Jaewoong Jung26342642021-03-17 15:56:23 -0700266 IsSDKLibrary bool `blueprint:"mutated"`
267
268 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
269 // Defaults to false.
270 V4_signature *bool
271
272 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
273 // public stubs library.
274 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000275
276 HiddenAPIPackageProperties
277 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700278}
279
Jooyung Han01d80d82022-01-08 12:16:32 +0900280// Device properties that can be overridden by overriding module (e.g. override_android_app)
281type OverridableDeviceProperties struct {
282 // set the name of the output. If not set, `name` is used.
283 // To override a module with this property set, overriding module might need to set this as well.
284 // Otherwise, both the overridden and the overriding modules will have the same output name, which
285 // can cause the duplicate output error.
286 Stem *string
287}
288
Jaewoong Jung26342642021-03-17 15:56:23 -0700289// Functionality common to Module and Import
290//
291// It is embedded in Module so its functionality can be used by methods in Module
292// but it is currently only initialized by Import and Library.
293type embeddableInModuleAndImport struct {
294
295 // Functionality related to this being used as a component of a java_sdk_library.
296 EmbeddableSdkLibraryComponent
297}
298
Paul Duffin71b33cc2021-06-23 11:39:47 +0100299func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
300 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700301}
302
303// Module/Import's DepIsInSameApex(...) delegates to this method.
304//
305// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
306// the one provided by ApexModuleBase.
307func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
308 // dependencies other than the static linkage are all considered crossing APEX boundary
309 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
310 return true
311 }
312 return false
313}
314
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100315// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
316// or an invalid path describing the reason it is invalid.
317//
318// It is unset if a dex jar isn't applicable, i.e. no build rule has been
319// requested to create one.
320//
321// If a dex jar has been requested to be built then it is set, and it may be
322// either a valid android.Path, or invalid with a reason message. The latter
323// happens if the source that should produce the dex file isn't able to.
324//
325// E.g. it is invalid with a reason message if there is a prebuilt APEX that
326// could produce the dex jar through a deapexer module, but the APEX isn't
327// installable so doing so wouldn't be safe.
328type OptionalDexJarPath struct {
329 isSet bool
330 path android.OptionalPath
331}
332
333// IsSet returns true if a path has been set, either invalid or valid.
334func (o OptionalDexJarPath) IsSet() bool {
335 return o.isSet
336}
337
338// Valid returns true if there is a path that is valid.
339func (o OptionalDexJarPath) Valid() bool {
340 return o.isSet && o.path.Valid()
341}
342
343// Path returns the valid path, or panics if it's either not set or is invalid.
344func (o OptionalDexJarPath) Path() android.Path {
345 if !o.isSet {
346 panic("path isn't set")
347 }
348 return o.path.Path()
349}
350
351// PathOrNil returns the path if it's set and valid, or else nil.
352func (o OptionalDexJarPath) PathOrNil() android.Path {
353 if o.Valid() {
354 return o.Path()
355 }
356 return nil
357}
358
359// InvalidReason returns the reason for an invalid path, which is never "". It
360// returns "" for an unset or valid path.
361func (o OptionalDexJarPath) InvalidReason() string {
362 if !o.isSet {
363 return ""
364 }
365 return o.path.InvalidReason()
366}
367
368func (o OptionalDexJarPath) String() string {
369 if !o.isSet {
370 return "<unset>"
371 }
372 return o.path.String()
373}
374
375// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
376func makeUnsetDexJarPath() OptionalDexJarPath {
377 return OptionalDexJarPath{isSet: false}
378}
379
380// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
381// the given OptionalPath, which may be valid or invalid.
382func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
383 return OptionalDexJarPath{isSet: true, path: path}
384}
385
386// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
387// valid given path. It returns an unset OptionalDexJarPath if the given path is
388// nil.
389func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
390 if path == nil {
391 return makeUnsetDexJarPath()
392 }
393 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
394}
395
Jaewoong Jung26342642021-03-17 15:56:23 -0700396// Module contains the properties and members used by all java module types
397type Module struct {
398 android.ModuleBase
399 android.DefaultableModuleBase
400 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800401 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700402
403 // Functionality common to Module and Import.
404 embeddableInModuleAndImport
405
406 properties CommonProperties
407 protoProperties android.ProtoProperties
408 deviceProperties DeviceProperties
409
Jooyung Han01d80d82022-01-08 12:16:32 +0900410 overridableDeviceProperties OverridableDeviceProperties
411
Jaewoong Jung26342642021-03-17 15:56:23 -0700412 // jar file containing header classes including static library dependencies, suitable for
413 // inserting into the bootclasspath/classpath of another compile
414 headerJarFile android.Path
415
416 // jar file containing implementation classes including static library dependencies but no
417 // resources
418 implementationJarFile android.Path
419
420 // jar file containing only resources including from static library dependencies
421 resourceJar android.Path
422
423 // args and dependencies to package source files into a srcjar
424 srcJarArgs []string
425 srcJarDeps android.Paths
426
427 // jar file containing implementation classes and resources including static library
428 // dependencies
429 implementationAndResourcesJar android.Path
430
431 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100432 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700433
434 // output file containing uninstrumented classes that will be instrumented by jacoco
435 jacocoReportClassesFile android.Path
436
437 // output file of the module, which may be a classes jar or a dex jar
438 outputFile android.Path
439 extraOutputFiles android.Paths
440
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100441 exportAidlIncludeDirs android.Paths
442 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700443
444 logtagsSrcs android.Paths
445
446 // installed file for binary dependency
447 installFile android.Path
448
Colin Cross3108ce12021-11-10 14:38:50 -0800449 // installed file for hostdex copy
450 hostdexInstallFile android.InstallPath
451
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800452 // list of unique .java and .kt source files
453 uniqueSrcFiles android.Paths
454
455 // list of srcjars that was passed to javac
456 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700457
458 // manifest file to use instead of properties.Manifest
459 overrideManifest android.OptionalPath
460
Jaewoong Jung26342642021-03-17 15:56:23 -0700461 // list of plugins that this java module is exporting
462 exportedPluginJars android.Paths
463
464 // list of plugins that this java module is exporting
465 exportedPluginClasses []string
466
467 // if true, the exported plugins generate API and require disabling turbine.
468 exportedDisableTurbine bool
469
470 // list of source files, collected from srcFiles with unique java and all kt files,
471 // will be used by android.IDEInfo struct
472 expandIDEInfoCompiledSrcs []string
473
474 // expanded Jarjar_rules
475 expandJarjarRules android.Path
476
Jaewoong Jung26342642021-03-17 15:56:23 -0700477 // Extra files generated by the module type to be added as java resources.
478 extraResources android.Paths
479
480 hiddenAPI
481 dexer
482 dexpreopter
483 usesLibrary
484 linter
485
486 // list of the xref extraction files
487 kytheFiles android.Paths
488
489 // Collect the module directory for IDE info in java/jdeps.go.
490 modulePaths []string
491
492 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900493
494 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000495 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000496 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400497
498 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700499}
500
Jiyong Park92315372021-04-02 08:45:46 +0900501func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
502 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900503 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700504 return nil
505 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900506 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000507 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700508 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
509 } else {
510 // Treat stable core platform as stable.
511 return nil
512 }
513 } else {
514 return fmt.Errorf("non stable SDK %v", sdkVersion)
515 }
516}
517
518// checkSdkVersions enforces restrictions around SDK dependencies.
519func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
520 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900521 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900522 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700523 ctx.PropertyErrorf("sdk_version",
524 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
525 }
526 }
527 }
528
529 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
530 // See rank() for details.
531 ctx.VisitDirectDeps(func(module android.Module) {
532 tag := ctx.OtherModuleDependencyTag(module)
533 switch module.(type) {
534 // TODO(satayev): cover other types as well, e.g. imports
535 case *Library, *AndroidLibrary:
536 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400537 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700538 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
539 }
540 }
541 })
542}
543
544func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900545 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700546 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900547 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700548 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000549 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 -0700550 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000551 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 -0700552 }
553
554 }
555}
556
557func (j *Module) addHostProperties() {
558 j.AddProperties(
559 &j.properties,
560 &j.protoProperties,
561 &j.usesLibraryProperties,
562 )
563}
564
565func (j *Module) addHostAndDeviceProperties() {
566 j.addHostProperties()
567 j.AddProperties(
568 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900569 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700570 &j.dexer.dexProperties,
571 &j.dexpreoptProperties,
572 &j.linter.properties,
573 )
574}
575
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000576// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
577// makes it available through the hiddenAPIPropertyInfoProvider.
578func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
579 hiddenAPIInfo := newHiddenAPIPropertyInfo()
580
581 // Populate with flag file paths from the properties.
582 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
583
584 // Populate with package rules from the properties.
585 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
586
587 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
588}
589
Jaewoong Jung26342642021-03-17 15:56:23 -0700590func (j *Module) OutputFiles(tag string) (android.Paths, error) {
591 switch tag {
592 case "":
593 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
594 case android.DefaultDistTag:
595 return android.Paths{j.outputFile}, nil
596 case ".jar":
597 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700598 case ".hjar":
599 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700600 case ".proguard_map":
601 if j.dexer.proguardDictionary.Valid() {
602 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
603 }
604 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
605 default:
606 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
607 }
608}
609
610var _ android.OutputFileProducer = (*Module)(nil)
611
612func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
613 initJavaModule(module, hod, false)
614}
615
616func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
617 initJavaModule(module, hod, true)
618}
619
620func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
621 multilib := android.MultilibCommon
622 if multiTargets {
623 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
624 } else {
625 android.InitAndroidArchModule(module, hod, multilib)
626 }
627 android.InitDefaultableModule(module)
628}
629
630func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
631 return j.properties.Instrument &&
632 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
633 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
634}
635
636func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000637 return j.properties.Supports_static_instrumentation &&
638 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700639 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
640 ctx.Config().UnbundledBuild())
641}
642
643func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
644 // Force enable the instrumentation for java code that is built for APEXes ...
645 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
646 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
647 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
648 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
649 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
650 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
651 return true
652 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
653 return true
654 }
655 }
656 return false
657}
658
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400659func (j *Module) setInstrument(value bool) {
660 j.properties.Instrument = value
661}
662
Jiyong Park92315372021-04-02 08:45:46 +0900663func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
664 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700665}
666
Jiyong Parkf1691d22021-03-29 20:11:58 +0900667func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700668 return proptools.String(j.deviceProperties.System_modules)
669}
670
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000671func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700672 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000673 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700674 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000675 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700676}
677
Spandan Dasa26eda72023-03-02 00:56:06 +0000678func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
679 if j.deviceProperties.Max_sdk_version != nil {
680 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
681 }
682 // Default is PrivateApiLevel
683 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000684}
685
Spandan Dasa26eda72023-03-02 00:56:06 +0000686func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
687 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
688 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
689 }
690 // Default is PrivateApiLevel
691 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000692}
693
Jiyong Parkf1691d22021-03-29 20:11:58 +0900694func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000695 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900696}
697
Spandan Dasca70fc42023-03-01 23:38:49 +0000698func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900699 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000700 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900701 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000702 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700703}
704
705func (j *Module) AvailableFor(what string) bool {
706 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
707 // Exception: for hostdex: true libraries, the platform variant is created
708 // even if it's not marked as available to platform. In that case, the platform
709 // variant is used only for the hostdex and not installed to the device.
710 return true
711 }
712 return j.ApexModuleBase.AvailableFor(what)
713}
714
715func (j *Module) deps(ctx android.BottomUpMutatorContext) {
716 if ctx.Device() {
717 j.linter.deps(ctx)
718
Jiyong Parkf1691d22021-03-29 20:11:58 +0900719 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700720
721 if j.deviceProperties.SyspropPublicStub != "" {
722 // This is a sysprop implementation library that has a corresponding sysprop public
723 // stubs library, and a dependency on it so that dependencies on the implementation can
724 // be forwarded to the public stubs library when necessary.
725 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
726 }
727 }
728
729 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000730
731 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700732 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
733
734 // Add dependency on libraries that provide additional hidden api annotations.
735 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
736
737 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
738 // Require java_sdk_library at inter-partition java dependency to ensure stable
739 // interface between partitions. If inter-partition java_library dependency is detected,
740 // raise build error because java_library doesn't have a stable interface.
741 //
742 // Inputs:
743 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
744 // if true, enable enforcement
745 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
746 // exception list of java_library names to allow inter-partition dependency
747 for idx := range j.properties.Libs {
748 if libDeps[idx] == nil {
749 continue
750 }
751
752 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
753 // java_sdk_library is always allowed at inter-partition dependency.
754 // So, skip check.
755 if _, ok := javaDep.(*SdkLibrary); ok {
756 continue
757 }
758
759 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
760 }
761 }
762 }
763
764 // For library dependencies that are component libraries (like stubs), add the implementation
765 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
766 for _, dep := range libDeps {
767 if dep != nil {
768 if component, ok := dep.(SdkLibraryComponentDependency); ok {
769 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100770 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100771 tag := usesLibReqTag
772 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
773 tag = usesLibOptTag
774 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100775 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700776 }
777 }
778 }
779 }
780
781 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
782 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
783 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
784
785 android.ProtoDeps(ctx, &j.protoProperties)
786 if j.hasSrcExt(".proto") {
787 protoDeps(ctx, &j.protoProperties)
788 }
789
790 if j.hasSrcExt(".kt") {
791 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
792 // Kotlin files
793 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
794 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700795 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700796 }
797
798 // Framework libraries need special handling in static coverage builds: they should not have
799 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
800 // the same jacoco classes coming from different bootclasspath jars.
801 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
802 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
803 j.properties.Instrument = true
804 }
805 } else if j.shouldInstrumentStatic(ctx) {
806 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
807 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700808
809 if j.useCompose() {
810 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
811 "androidx.compose.compiler_compiler-hosted")
812 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700813}
814
815func hasSrcExt(srcs []string, ext string) bool {
816 for _, src := range srcs {
817 if filepath.Ext(src) == ext {
818 return true
819 }
820 }
821
822 return false
823}
824
825func (j *Module) hasSrcExt(ext string) bool {
826 return hasSrcExt(j.properties.Srcs, ext)
827}
828
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100829func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
830 var flags string
831
832 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
833 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
834 flags = "-Wmissing-permission-annotation -Werror"
835 }
836 }
837 return flags
838}
839
Jaewoong Jung26342642021-03-17 15:56:23 -0700840func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000841 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700842
843 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
844 aidlIncludes = append(aidlIncludes,
845 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
846 aidlIncludes = append(aidlIncludes,
847 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
848
849 var flags []string
850 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000851 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700852
853 flags = append(flags, j.deviceProperties.Aidl.Flags...)
854
855 if aidlPreprocess.Valid() {
856 flags = append(flags, "-p"+aidlPreprocess.String())
857 deps = append(deps, aidlPreprocess.Path())
858 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000859 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700860 }
861
862 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000863 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700864 }
865
866 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000867 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700868 }
869
Sam Delmerico2351eac2022-05-24 17:10:02 +0000870 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700871 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000872 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700873 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000874 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
875 // add flags for dirs containing AIDL srcs that haven't been specified yet
876 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700877
Zim8774ae12022-08-17 11:46:34 +0100878 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000879 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100880 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700881 flags = append(flags, "-t")
882 }
883
884 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
885 flags = append(flags, "--transaction_names")
886 }
887
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100888 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
889 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
890 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
891 }
892
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000893 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900894 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
895
Jaewoong Jung26342642021-03-17 15:56:23 -0700896 return strings.Join(flags, " "), deps
897}
898
899func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
900
901 var flags javaBuilderFlags
902
903 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900904 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700905
Cole Faust2b1536e2021-06-18 12:25:54 -0700906 epEnabled := j.properties.Errorprone.Enabled
907 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100908 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700909 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
910 }
911
912 errorProneFlags := []string{
913 "-Xplugin:ErrorProne",
914 "${config.ErrorProneChecks}",
915 }
916 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
917
Colin Cross8bf6cad2022-02-28 13:07:03 -0800918 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700919 "'" + strings.Join(errorProneFlags, " ") + "'"
920 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
921 }
922
923 // classpath
924 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
925 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700926 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700927 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
928 flags.processorPath = append(flags.processorPath, deps.processorPath...)
929 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
930
931 flags.processors = append(flags.processors, deps.processorClasses...)
932 flags.processors = android.FirstUniqueStrings(flags.processors)
933
934 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900935 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700936 // Give host-side tools a version of OpenJDK's standard libraries
937 // close to what they're targeting. As of Dec 2017, AOSP is only
938 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
939 //
940 // When building with OpenJDK 8, the following should have no
941 // effect since those jars would be available by default.
942 //
943 // When building with OpenJDK 9 but targeting a version < 1.8,
944 // putting them on the bootclasspath means that:
945 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
946 // b) references to existing APIs are not reinterpreted in an
947 // OpenJDK 9-specific way, eg. calls to subclasses of
948 // java.nio.Buffer as in http://b/70862583
949 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
950 flags.bootClasspath = append(flags.bootClasspath,
951 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
952 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
953 if Bool(j.properties.Use_tools_jar) {
954 flags.bootClasspath = append(flags.bootClasspath,
955 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
956 }
957 }
958
959 // systemModules
960 flags.systemModules = deps.systemModules
961
Jaewoong Jung26342642021-03-17 15:56:23 -0700962 return flags
963}
964
965func (j *Module) collectJavacFlags(
966 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
967 // javac flags.
968 javacFlags := j.properties.Javacflags
969
970 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
971 // For non-host binaries, override the -g flag passed globally to remove
972 // local variable debug info to reduce disk and memory usage.
973 javacFlags = append(javacFlags, "-g:source,lines")
974 }
975 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
976
977 if flags.javaVersion.usesJavaModules() {
978 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
979
980 if j.properties.Patch_module != nil {
981 // Manually specify build directory in case it is not under the repo root.
982 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
983 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200984 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700985
986 // b/150878007
987 //
988 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
989 // execution root for --patch-module. If this javac command line is
990 // invoked within Bazel's execution root working directory, the top
991 // level directories (e.g. libcore/, tools/, frameworks/) are all
992 // symlinks. JDK9 javac does not traverse into symlinks, which causes
993 // --patch-module to fail source file lookups when invoked in the
994 // execution root.
995 //
996 // Short of patching javac or enumerating *all* directories as possible
997 // input dirs, manually add the top level dir of the source files to be
998 // compiled.
999 topLevelDirs := map[string]bool{}
1000 for _, srcFilePath := range srcFiles {
1001 srcFileParts := strings.Split(srcFilePath.String(), "/")
1002 // Ignore source files that are already in the top level directory
1003 // as well as generated files in the out directory. The out
1004 // directory may be an absolute path, which means srcFileParts[0] is the
1005 // empty string, so check that as well. Note that "out" in Bazel's execution
1006 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1007 // anyway, so it's fine to not apply this workaround for generated
1008 // source files.
1009 if len(srcFileParts) > 1 &&
1010 srcFileParts[0] != "" &&
1011 srcFileParts[0] != "out" {
1012 topLevelDirs[srcFileParts[0]] = true
1013 }
1014 }
Cole Faust18994c72023-02-28 16:02:16 -08001015 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001016
1017 classPath := flags.classpath.FormJavaClassPath("")
1018 if classPath != "" {
1019 patchPaths = append(patchPaths, classPath)
1020 }
1021 javacFlags = append(
1022 javacFlags,
1023 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1024 }
1025 }
1026
1027 if len(javacFlags) > 0 {
1028 // optimization.
1029 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1030 flags.javacFlags = "$javacFlags"
1031 }
1032
1033 return flags
1034}
1035
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001036func (j *Module) AddJSONData(d *map[string]interface{}) {
1037 (&j.ModuleBase).AddJSONData(d)
1038 (*d)["Java"] = map[string]interface{}{
1039 "SourceExtensions": j.sourceExtensions,
1040 }
1041
1042}
1043
Jaewoong Jung26342642021-03-17 15:56:23 -07001044func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1045 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1046
1047 deps := j.collectDeps(ctx)
1048 flags := j.collectBuilderFlags(ctx, deps)
1049
1050 if flags.javaVersion.usesJavaModules() {
1051 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1052 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001053
Jaewoong Jung26342642021-03-17 15:56:23 -07001054 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001055 j.sourceExtensions = []string{}
1056 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1057 if hasSrcExt(srcFiles.Strings(), ext) {
1058 j.sourceExtensions = append(j.sourceExtensions, ext)
1059 }
1060 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001061 if hasSrcExt(srcFiles.Strings(), ".proto") {
1062 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1063 }
1064
1065 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1066 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1067 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1068 }
1069
Sam Delmerico2351eac2022-05-24 17:10:02 +00001070 aidlSrcs := srcFiles.FilterByExt(".aidl")
1071 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1072
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001073 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001074 srcFiles = j.genSources(ctx, srcFiles, flags)
1075
1076 // Collect javac flags only after computing the full set of srcFiles to
1077 // ensure that the --patch-module lookup paths are complete.
1078 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1079
1080 srcJars := srcFiles.FilterByExt(".srcjar")
1081 srcJars = append(srcJars, deps.srcJars...)
1082 if aaptSrcJar != nil {
1083 srcJars = append(srcJars, aaptSrcJar)
1084 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001085 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001086
1087 if j.properties.Jarjar_rules != nil {
1088 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1089 }
1090
1091 jarName := ctx.ModuleName() + ".jar"
1092
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001093 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001094 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001095 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001096 if _, found := set[v.String()]; !found {
1097 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001098 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001099 }
1100 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001101 var uniqueKtFiles android.Paths
1102 for _, v := range srcFiles.FilterByExt(".kt") {
1103 if _, found := set[v.String()]; !found {
1104 set[v.String()] = true
1105 uniqueKtFiles = append(uniqueKtFiles, v)
1106 }
1107 }
1108
1109 var uniqueSrcFiles android.Paths
1110 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1111 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1112 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001113
Colin Crossb5db4012022-03-28 17:12:39 -07001114 // We don't currently run annotation processors in turbine, which means we can't use turbine
1115 // generated header jars when an annotation processor that generates API is enabled. One
1116 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1117 // is used to run all of the annotation processors.
1118 disableTurbine := deps.disableTurbine
1119
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001120 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001121 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1122
1123 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001124 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001125
1126 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001127 // When using kotlin sources turbine is used to generate annotation processor sources,
1128 // including for annotation processors that generate API, so we can use turbine for
1129 // java sources too.
1130 disableTurbine = false
1131
Jaewoong Jung26342642021-03-17 15:56:23 -07001132 // user defined kotlin flags.
1133 kotlincFlags := j.properties.Kotlincflags
1134 CheckKotlincFlags(ctx, kotlincFlags)
1135
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001136 // Workaround for KT-46512
1137 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001138
1139 // If there are kotlin files, compile them first but pass all the kotlin and java files
1140 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1141 // won't emit any classes for them.
1142 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1143 if ctx.Device() {
1144 kotlincFlags = append(kotlincFlags, "-no-jdk")
1145 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001146
1147 for _, plugin := range deps.kotlinPlugins {
1148 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1149 }
1150 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1151
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 if len(kotlincFlags) > 0 {
1153 // optimization.
1154 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1155 flags.kotlincFlags += "$kotlincFlags"
1156 }
1157
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001158 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1160
1161 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1162 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1163
1164 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1165 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1166
Isaac Chioua23d9942022-04-06 06:14:38 +00001167 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001168 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001169 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1170 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001171 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001172 srcJars = append(srcJars, kaptSrcJar)
1173 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001174 // Disable annotation processing in javac, it's already been handled by kapt
1175 flags.processorPath = nil
1176 flags.processors = nil
1177 }
1178
1179 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001180 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001181 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001182 if ctx.Failed() {
1183 return
1184 }
1185
Isaac Chioua23d9942022-04-06 06:14:38 +00001186 // Make javac rule depend on the kotlinc rule
1187 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1188
Jaewoong Jung26342642021-03-17 15:56:23 -07001189 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001190 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1191
Jaewoong Jung26342642021-03-17 15:56:23 -07001192 // Jar kotlin classes into the final jar after javac
1193 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1194 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001195 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001196 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001197 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001198 } else {
1199 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001200 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001201 }
1202 }
1203
1204 jars := append(android.Paths(nil), kotlinJars...)
1205
Jaewoong Jung26342642021-03-17 15:56:23 -07001206 j.compiledSrcJars = srcJars
1207
1208 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001209 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001210 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001211 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1212 enableSharding = true
1213 // Formerly, there was a check here that prevented annotation processors
1214 // from being used when sharding was enabled, as some annotation processors
1215 // do not function correctly in sharded environments. It was removed to
1216 // allow for the use of annotation processors that do function correctly
1217 // with sharding enabled. See: b/77284273.
1218 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001219 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001220 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001221 if ctx.Failed() {
1222 return
1223 }
1224 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001225 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001226 hasErrorproneableFiles := false
1227 for _, ext := range j.sourceExtensions {
1228 if ext != ".proto" && ext != ".aidl" {
1229 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1230 // compile, and it's not useful to have warnings on these generated sources.
1231 hasErrorproneableFiles = true
1232 break
1233 }
1234 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001235 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001236 if Bool(j.properties.Errorprone.Enabled) {
1237 // If error-prone is enabled, enable errorprone flags on the regular
1238 // build.
1239 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001240 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001241 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1242 // a new jar file just for compiling with the errorprone compiler to.
1243 // This is because we don't want to cause the java files to get completely
1244 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1245 // We also don't want to run this if errorprone is enabled by default for
1246 // this module, or else we could have duplicated errorprone messages.
1247 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001248 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001249
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001250 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001251 "errorprone", "errorprone")
1252
Jaewoong Jung26342642021-03-17 15:56:23 -07001253 extraJarDeps = append(extraJarDeps, errorprone)
1254 }
1255
1256 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001257 if headerJarFileWithoutDepsOrJarjar != nil {
1258 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1259 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001260 shardSize := int(*(j.properties.Javac_shard_size))
1261 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001262 if len(uniqueJavaFiles) > 0 {
1263 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 for idx, shardSrc := range shardSrcs {
1265 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1266 nil, flags, extraJarDeps)
1267 jars = append(jars, classes)
1268 }
1269 }
1270 if len(srcJars) > 0 {
1271 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1272 nil, srcJars, flags, extraJarDeps)
1273 jars = append(jars, classes)
1274 }
1275 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001276 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001277 jars = append(jars, classes)
1278 }
1279 if ctx.Failed() {
1280 return
1281 }
1282 }
1283
1284 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1285
1286 var includeSrcJar android.WritablePath
1287 if Bool(j.properties.Include_srcs) {
1288 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1289 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1290 }
1291
1292 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1293 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1294 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1295 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1296
1297 var resArgs []string
1298 var resDeps android.Paths
1299
1300 resArgs = append(resArgs, dirArgs...)
1301 resDeps = append(resDeps, dirDeps...)
1302
1303 resArgs = append(resArgs, fileArgs...)
1304 resDeps = append(resDeps, fileDeps...)
1305
1306 resArgs = append(resArgs, extraArgs...)
1307 resDeps = append(resDeps, extraDeps...)
1308
1309 if len(resArgs) > 0 {
1310 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1311 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1312 j.resourceJar = resourceJar
1313 if ctx.Failed() {
1314 return
1315 }
1316 }
1317
1318 var resourceJars android.Paths
1319 if j.resourceJar != nil {
1320 resourceJars = append(resourceJars, j.resourceJar)
1321 }
1322 if Bool(j.properties.Include_srcs) {
1323 resourceJars = append(resourceJars, includeSrcJar)
1324 }
1325 resourceJars = append(resourceJars, deps.staticResourceJars...)
1326
1327 if len(resourceJars) > 1 {
1328 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1329 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1330 false, nil, nil)
1331 j.resourceJar = combinedJar
1332 } else if len(resourceJars) == 1 {
1333 j.resourceJar = resourceJars[0]
1334 }
1335
1336 if len(deps.staticJars) > 0 {
1337 jars = append(jars, deps.staticJars...)
1338 }
1339
1340 manifest := j.overrideManifest
1341 if !manifest.Valid() && j.properties.Manifest != nil {
1342 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1343 }
1344
1345 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1346 if len(services) > 0 {
1347 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1348 var zipargs []string
1349 for _, file := range services {
1350 serviceFile := file.String()
1351 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1352 }
1353 rule := zip
1354 args := map[string]string{
1355 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1356 }
1357 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1358 rule = zipRE
1359 args["implicits"] = strings.Join(services.Strings(), ",")
1360 }
1361 ctx.Build(pctx, android.BuildParams{
1362 Rule: rule,
1363 Output: servicesJar,
1364 Implicits: services,
1365 Args: args,
1366 })
1367 jars = append(jars, servicesJar)
1368 }
1369
1370 // Combine the classes built from sources, any manifests, and any static libraries into
1371 // classes.jar. If there is only one input jar this step will be skipped.
1372 var outputFile android.OutputPath
1373
1374 if len(jars) == 1 && !manifest.Valid() {
1375 // Optimization: skip the combine step as there is nothing to do
1376 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1377 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1378 // any if len(jars) == 1.
1379
1380 // Transform the single path to the jar into an OutputPath as that is required by the following
1381 // code.
1382 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1383 // The path contains an embedded OutputPath so reuse that.
1384 outputFile = moduleOutPath.OutputPath
1385 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1386 // The path is an OutputPath so reuse it directly.
1387 outputFile = outputPath
1388 } else {
1389 // The file is not in the out directory so create an OutputPath into which it can be copied
1390 // and which the following code can use to refer to it.
1391 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1392 ctx.Build(pctx, android.BuildParams{
1393 Rule: android.Cp,
1394 Input: jars[0],
1395 Output: combinedJar,
1396 })
1397 outputFile = combinedJar.OutputPath
1398 }
1399 } else {
1400 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1401 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1402 false, nil, nil)
1403 outputFile = combinedJar.OutputPath
1404 }
1405
1406 // jarjar implementation jar if necessary
1407 if j.expandJarjarRules != nil {
1408 // Transform classes.jar into classes-jarjar.jar
1409 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1410 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1411 outputFile = jarjarFile
1412
1413 // jarjar resource jar if necessary
1414 if j.resourceJar != nil {
1415 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1416 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1417 j.resourceJar = resourceJarJarFile
1418 }
1419
1420 if ctx.Failed() {
1421 return
1422 }
1423 }
1424
1425 // Check package restrictions if necessary.
1426 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001427 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001428 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001429
1430 // Create a rule to copy the output jar to another path and add a validate dependency that
1431 // will check that the jar only contains the permitted packages. The new location will become
1432 // the output file of this module.
1433 inputFile := outputFile
1434 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1435 ctx.Build(pctx, android.BuildParams{
1436 Rule: android.Cp,
1437 Input: inputFile,
1438 Output: outputFile,
1439 // Make sure that any dependency on the output file will cause ninja to run the package check
1440 // rule.
1441 Validation: pkgckFile,
1442 })
1443
1444 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001445 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001446
1447 if ctx.Failed() {
1448 return
1449 }
1450 }
1451
1452 j.implementationJarFile = outputFile
1453 if j.headerJarFile == nil {
1454 j.headerJarFile = j.implementationJarFile
1455 }
1456
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001457 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1458 specs := j.jacocoModuleToZipCommand(ctx)
1459 if ctx.Failed() {
1460 return
1461 }
1462
Jaewoong Jung26342642021-03-17 15:56:23 -07001463 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001464 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 }
1466
1467 // merge implementation jar with resources if necessary
1468 implementationAndResourcesJar := outputFile
1469 if j.resourceJar != nil {
1470 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1471 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1472 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1473 false, nil, nil)
1474 implementationAndResourcesJar = combinedJar
1475 }
1476
1477 j.implementationAndResourcesJar = implementationAndResourcesJar
1478
1479 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001480 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001481 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1482 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001483 if compileDex == nil {
1484 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 }
1486 if j.deviceProperties.Hostdex == nil {
1487 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1488 }
1489 }
1490
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001491 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001492 if j.hasCode(ctx) {
1493 if j.shouldInstrumentStatic(ctx) {
1494 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1495 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1496 }
1497 // Dex compilation
1498 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001499 params := &compileDexParams{
1500 flags: flags,
1501 sdkVersion: j.SdkVersion(ctx),
1502 minSdkVersion: j.MinSdkVersion(ctx),
1503 classesJar: implementationAndResourcesJar,
1504 jarName: jarName,
1505 }
1506 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001507 if ctx.Failed() {
1508 return
1509 }
1510
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 // merge dex jar with resources if necessary
1512 if j.resourceJar != nil {
1513 jars := android.Paths{dexOutputFile, j.resourceJar}
1514 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1515 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1516 false, nil, nil)
1517 if *j.dexProperties.Uncompress_dex {
1518 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1519 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1520 dexOutputFile = combinedAlignedJar
1521 } else {
1522 dexOutputFile = combinedJar
1523 }
1524 }
1525
Paul Duffin4de94502021-05-16 05:21:16 +01001526 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001527
1528 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001529
1530 // Encode hidden API flags in dex file, if needed.
1531 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1532
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001533 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001534
1535 // Dexpreopting
1536 j.dexpreopt(ctx, dexOutputFile)
1537
1538 outputFile = dexOutputFile
1539 } else {
1540 // There is no code to compile into a dex jar, make sure the resources are propagated
1541 // to the APK if this is an app.
1542 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001543 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001544 }
1545
1546 if ctx.Failed() {
1547 return
1548 }
1549 } else {
1550 outputFile = implementationAndResourcesJar
1551 }
1552
1553 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001554 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1555 if !apiLevel.IsPreview() {
1556 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001557 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001558 // When running metalava, we pass --version-codename. When that value
1559 // is not REL, metalava will add 1 to the --current-version argument.
1560 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1561 // branch) and the codename is REL, except potentially on the most
1562 // recent non-master branch. On that branch, it goes through two other
1563 // phases before it gets to the phase previously described:
1564 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1565 // is not rel. This happens for most of the internal branch's life
1566 // while the branch has been cut but is still under active development.
1567 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1568 // REL. This happens briefly during the release process. During this
1569 // state the code to add --current-version is commented out, and then
1570 // that commenting out is reverted after the codename is set to REL.
1571 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1572 // prior version and the codename is always non-REL.
1573 //
1574 // We need to add one here to match metalava adding 1. Technically
1575 // this means that in the state described in the second bullet point
1576 // above, this number is 1 higher than it should be.
1577 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001578 }
1579 }
1580
1581 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001582 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1583 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001584 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1585 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001586 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001587 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001588 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001589 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001590 j.linter.javaLanguageLevel = flags.javaVersion.String()
1591 j.linter.kotlinLanguageLevel = "1.3"
1592 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1593 j.linter.buildModuleReportZip = true
1594 }
1595 j.linter.lint(ctx)
1596 }
1597
1598 ctx.CheckbuildFile(outputFile)
1599
1600 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1601 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001602 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1603 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001604 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1605 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1606 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1607 AidlIncludeDirs: j.exportAidlIncludeDirs,
1608 SrcJarArgs: j.srcJarArgs,
1609 SrcJarDeps: j.srcJarDeps,
1610 ExportedPlugins: j.exportedPluginJars,
1611 ExportedPluginClasses: j.exportedPluginClasses,
1612 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1613 JacocoReportClassesFile: j.jacocoReportClassesFile,
1614 })
1615
1616 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1617 j.outputFile = outputFile.WithoutRel()
1618}
1619
Colin Crossa1ff7c62021-09-17 14:11:52 -07001620func (j *Module) useCompose() bool {
1621 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1622}
1623
Cole Faust75fffb12021-06-13 15:23:16 -07001624// Returns a copy of the supplied flags, but with all the errorprone-related
1625// fields copied to the regular build's fields.
1626func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1627 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1628
1629 if len(flags.errorProneExtraJavacFlags) > 0 {
1630 if len(flags.javacFlags) > 0 {
1631 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1632 } else {
1633 flags.javacFlags = flags.errorProneExtraJavacFlags
1634 }
1635 }
1636 return flags
1637}
1638
Jaewoong Jung26342642021-03-17 15:56:23 -07001639func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1640 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1641
1642 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1643 if idx >= 0 {
1644 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1645 jarName += strconv.Itoa(idx)
1646 }
1647
1648 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1649 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1650
1651 if ctx.Config().EmitXrefRules() {
1652 extractionFile := android.PathForModuleOut(ctx, kzipName)
1653 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1654 j.kytheFiles = append(j.kytheFiles, extractionFile)
1655 }
1656
1657 return classes
1658}
1659
1660// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1661// since some of these flags may be used internally.
1662func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1663 for _, flag := range flags {
1664 flag = strings.TrimSpace(flag)
1665
1666 if !strings.HasPrefix(flag, "-") {
1667 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1668 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1669 ctx.PropertyErrorf("kotlincflags",
1670 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1671 } else if inList(flag, config.KotlincIllegalFlags) {
1672 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1673 } else if flag == "-include-runtime" {
1674 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1675 } else {
1676 args := strings.Split(flag, " ")
1677 if args[0] == "-kotlin-home" {
1678 ctx.PropertyErrorf("kotlincflags",
1679 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1680 }
1681 }
1682 }
1683}
1684
1685func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1686 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001687 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001688
1689 var jars android.Paths
1690 if len(srcFiles) > 0 || len(srcJars) > 0 {
1691 // Compile java sources into turbine.jar.
1692 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1693 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1694 if ctx.Failed() {
1695 return nil, nil
1696 }
1697 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001698 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001699 }
1700
1701 jars = append(jars, extraJars...)
1702
1703 // Combine any static header libraries into classes-header.jar. If there is only
1704 // one input jar this step will be skipped.
1705 jars = append(jars, deps.staticHeaderJars...)
1706
1707 // we cannot skip the combine step for now if there is only one jar
1708 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1709 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1710 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1711 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001712 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001713
1714 if j.expandJarjarRules != nil {
1715 // Transform classes.jar into classes-jarjar.jar
1716 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001717 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1718 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001719 if ctx.Failed() {
1720 return nil, nil
1721 }
1722 }
1723
Colin Cross3d56ed52021-11-18 22:23:12 -08001724 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001725}
1726
1727func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001728 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001729
1730 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1731 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1732
1733 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1734
1735 j.jacocoReportClassesFile = jacocoReportClassesFile
1736
1737 return instrumentedJar
1738}
1739
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001740type providesTransitiveHeaderJars struct {
1741 // set of header jars for all transitive libs deps
1742 transitiveLibsHeaderJars *android.DepSet
1743 // set of header jars for all transitive static libs deps
1744 transitiveStaticLibsHeaderJars *android.DepSet
1745}
1746
1747func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
1748 return j.transitiveLibsHeaderJars
1749}
1750
1751func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
1752 return j.transitiveStaticLibsHeaderJars
1753}
1754
1755func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1756 directLibs := android.Paths{}
1757 directStaticLibs := android.Paths{}
1758 transitiveLibs := []*android.DepSet{}
1759 transitiveStaticLibs := []*android.DepSet{}
1760 ctx.VisitDirectDeps(func(module android.Module) {
1761 // don't add deps of the prebuilt version of the same library
1762 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1763 return
1764 }
1765
1766 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1767 if dep.TransitiveLibsHeaderJars != nil {
1768 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1769 }
1770 if dep.TransitiveStaticLibsHeaderJars != nil {
1771 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1772 }
1773
1774 tag := ctx.OtherModuleDependencyTag(module)
1775 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1776 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1777 directLibs = append(directLibs, dep.HeaderJars...)
1778 } else if tag == staticLibTag {
1779 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1780 }
1781 })
1782 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1783 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1784}
1785
Jaewoong Jung26342642021-03-17 15:56:23 -07001786func (j *Module) HeaderJars() android.Paths {
1787 if j.headerJarFile == nil {
1788 return nil
1789 }
1790 return android.Paths{j.headerJarFile}
1791}
1792
1793func (j *Module) ImplementationJars() android.Paths {
1794 if j.implementationJarFile == nil {
1795 return nil
1796 }
1797 return android.Paths{j.implementationJarFile}
1798}
1799
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001800func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001801 return j.dexJarFile
1802}
1803
1804func (j *Module) DexJarInstallPath() android.Path {
1805 return j.installFile
1806}
1807
1808func (j *Module) ImplementationAndResourcesJars() android.Paths {
1809 if j.implementationAndResourcesJar == nil {
1810 return nil
1811 }
1812 return android.Paths{j.implementationAndResourcesJar}
1813}
1814
1815func (j *Module) AidlIncludeDirs() android.Paths {
1816 // exportAidlIncludeDirs is type android.Paths already
1817 return j.exportAidlIncludeDirs
1818}
1819
1820func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1821 return j.classLoaderContexts
1822}
1823
1824// Collect information for opening IDE project files in java/jdeps.go.
1825func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1826 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1827 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1828 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1829 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1830 if j.expandJarjarRules != nil {
1831 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1832 }
1833 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001834 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1835 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001836}
1837
1838func (j *Module) CompilerDeps() []string {
1839 jdeps := []string{}
1840 jdeps = append(jdeps, j.properties.Libs...)
1841 jdeps = append(jdeps, j.properties.Static_libs...)
1842 return jdeps
1843}
1844
1845func (j *Module) hasCode(ctx android.ModuleContext) bool {
1846 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1847 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1848}
1849
1850// Implements android.ApexModule
1851func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1852 return j.depIsInSameApex(ctx, dep)
1853}
1854
1855// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001856func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001857 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001858 minSdkVersion := j.MinSdkVersion(ctx)
1859 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001860 return fmt.Errorf("min_sdk_version is not specified")
1861 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001862 // If the module is compiling against core (via sdk_version), skip comparison check.
1863 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001864 return nil
1865 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001866 if minSdkVersion.GreaterThan(sdkVersion) {
1867 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001868 }
1869 return nil
1870}
1871
1872func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001873 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001874}
1875
Jaewoong Jung26342642021-03-17 15:56:23 -07001876func (j *Module) JacocoReportClassesFile() android.Path {
1877 return j.jacocoReportClassesFile
1878}
1879
1880func (j *Module) IsInstallable() bool {
1881 return Bool(j.properties.Installable)
1882}
1883
1884type sdkLinkType int
1885
1886const (
1887 // TODO(jiyong) rename these for better readability. Make the allowed
1888 // and disallowed link types explicit
1889 // order is important here. See rank()
1890 javaCore sdkLinkType = iota
1891 javaSdk
1892 javaSystem
1893 javaModule
1894 javaSystemServer
1895 javaPlatform
1896)
1897
1898func (lt sdkLinkType) String() string {
1899 switch lt {
1900 case javaCore:
1901 return "core Java API"
1902 case javaSdk:
1903 return "Android API"
1904 case javaSystem:
1905 return "system API"
1906 case javaModule:
1907 return "module API"
1908 case javaSystemServer:
1909 return "system server API"
1910 case javaPlatform:
1911 return "private API"
1912 default:
1913 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1914 }
1915}
1916
1917// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1918// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1919// can't statically depend on modules that use Platform API.
1920func (lt sdkLinkType) rank() int {
1921 return int(lt)
1922}
1923
1924type moduleWithSdkDep interface {
1925 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001926 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001927}
1928
Jiyong Park92315372021-04-02 08:45:46 +09001929func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001930 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001931 case android.SdkCore.DefaultJavaLibraryName(),
1932 "legacy.core.platform.api.stubs",
1933 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001934 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001935 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001936 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001937 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001938 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001939 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001940 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001941 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001942 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001943 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001944 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001945 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001946 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001947 return javaSystem, true
1948 }
1949
1950 if stub, linkType := moduleStubLinkType(name); stub {
1951 return linkType, true
1952 }
1953
Jiyong Park92315372021-04-02 08:45:46 +09001954 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001955 switch ver.Kind {
1956 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001957 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001958 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001959 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001960 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001961 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001962 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001963 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001964 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001965 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001966 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001967 return javaPlatform, false
1968 }
1969
Jiyong Parkf1691d22021-03-29 20:11:58 +09001970 if !ver.Valid() {
1971 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001972 }
1973 return javaSdk, false
1974}
1975
1976// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1977// this module's. See the comment on rank() for details and an example.
1978func (j *Module) checkSdkLinkType(
1979 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1980 if ctx.Host() {
1981 return
1982 }
1983
Jiyong Park92315372021-04-02 08:45:46 +09001984 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001985 if stubs {
1986 return
1987 }
Jiyong Park92315372021-04-02 08:45:46 +09001988 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001989
1990 if myLinkType.rank() < depLinkType.rank() {
1991 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1992 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1993 "property of the source or target module so that target module is built "+
1994 "with the same or smaller API set when compared to the source.",
1995 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1996 }
1997}
1998
1999func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2000 var deps deps
2001
2002 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002003 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002004 if sdkDep.invalidVersion {
2005 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2006 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2007 } else if sdkDep.useFiles {
2008 // sdkDep.jar is actually equivalent to turbine header.jar.
2009 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002010 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002011 deps.aidlPreprocess = sdkDep.aidl
2012 } else {
2013 deps.aidlPreprocess = sdkDep.aidl
2014 }
2015 }
2016
Jiyong Park92315372021-04-02 08:45:46 +09002017 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002018
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002019 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002020 ctx.VisitDirectDeps(func(module android.Module) {
2021 otherName := ctx.OtherModuleName(module)
2022 tag := ctx.OtherModuleDependencyTag(module)
2023
2024 if IsJniDepTag(tag) {
2025 // Handled by AndroidApp.collectAppDeps
2026 return
2027 }
2028 if tag == certificateTag {
2029 // Handled by AndroidApp.collectAppDeps
2030 return
2031 }
2032
2033 if dep, ok := module.(SdkLibraryDependency); ok {
2034 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002035 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002036 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2037 deps.classpath = append(deps.classpath, depHeaderJars...)
2038 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002039 case staticLibTag:
2040 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2041 }
2042 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2043 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2044 if sdkLinkType != javaPlatform &&
2045 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2046 // dep is a sysprop implementation library, but this module is not linking against
2047 // the platform, so it gets the sysprop public stubs library instead. Replace
2048 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2049 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2050 dep = syspropDep.JavaInfo
2051 }
2052 switch tag {
2053 case bootClasspathTag:
2054 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002055 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002056 if _, ok := module.(*Plugin); ok {
2057 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2058 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002059 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002060 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002061 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2062 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2063 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2064 case java9LibTag:
2065 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2066 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002067 if _, ok := module.(*Plugin); ok {
2068 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2069 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002070 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2071 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2072 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2073 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2074 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2075 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2076 // Turbine doesn't run annotation processors, so any module that uses an
2077 // annotation processor that generates API is incompatible with the turbine
2078 // optimization.
2079 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2080 case pluginTag:
2081 if plugin, ok := module.(*Plugin); ok {
2082 if plugin.pluginProperties.Processor_class != nil {
2083 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2084 } else {
2085 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2086 }
2087 // Turbine doesn't run annotation processors, so any module that uses an
2088 // annotation processor that generates API is incompatible with the turbine
2089 // optimization.
2090 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2091 } else {
2092 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2093 }
2094 case errorpronePluginTag:
2095 if _, ok := module.(*Plugin); ok {
2096 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2097 } else {
2098 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2099 }
2100 case exportedPluginTag:
2101 if plugin, ok := module.(*Plugin); ok {
2102 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2103 if plugin.pluginProperties.Processor_class != nil {
2104 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2105 }
2106 // Turbine doesn't run annotation processors, so any module that uses an
2107 // annotation processor that generates API is incompatible with the turbine
2108 // optimization.
2109 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2110 } else {
2111 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2112 }
2113 case kotlinStdlibTag:
2114 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2115 case kotlinAnnotationsTag:
2116 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002117 case kotlinPluginTag:
2118 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002119 case syspropPublicStubDepTag:
2120 // This is a sysprop implementation library, forward the JavaInfoProvider from
2121 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2122 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2123 JavaInfo: dep,
2124 })
2125 }
2126 } else if dep, ok := module.(android.SourceFileProducer); ok {
2127 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002128 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002129 checkProducesJars(ctx, dep)
2130 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002131 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002132 case staticLibTag:
2133 checkProducesJars(ctx, dep)
2134 deps.classpath = append(deps.classpath, dep.Srcs()...)
2135 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2136 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2137 }
2138 } else {
2139 switch tag {
2140 case bootClasspathTag:
2141 // If a system modules dependency has been added to the bootclasspath
2142 // then add its libs to the bootclasspath.
2143 sm := module.(SystemModulesProvider)
2144 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2145
2146 case systemModulesTag:
2147 if deps.systemModules != nil {
2148 panic("Found two system module dependencies")
2149 }
2150 sm := module.(SystemModulesProvider)
2151 outputDir, outputDeps := sm.OutputDirAndDeps()
2152 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002153
2154 case instrumentationForTag:
2155 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 -07002156 }
2157 }
2158
2159 addCLCFromDep(ctx, module, j.classLoaderContexts)
2160 })
2161
2162 return deps
2163}
2164
2165func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2166 deps.processorPath = append(deps.processorPath, pluginJars...)
2167 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2168}
2169
2170// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2171// this interface.
2172type ProvidesUsesLib interface {
2173 ProvidesUsesLib() *string
2174}
2175
2176func (j *Module) ProvidesUsesLib() *string {
2177 return j.usesLibraryProperties.Provides_uses_lib
2178}
satayev1c564cc2021-05-25 19:50:30 +01002179
2180type ModuleWithStem interface {
2181 Stem() string
2182}
2183
2184var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002185
2186func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2187 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002188 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002189 if lib, ok := ctx.Module().(*Library); ok {
2190 javaLibraryBp2Build(ctx, lib)
2191 }
2192 case "java_binary_host":
2193 if binary, ok := ctx.Module().(*Binary); ok {
2194 javaBinaryHostBp2Build(ctx, binary)
2195 }
Zi Wang65b36722023-05-23 15:18:33 -07002196 case "java_test_host":
2197 if testHost, ok := ctx.Module().(*TestHost); ok {
2198 javaTestHostBp2Build(ctx, testHost)
2199 }
Wei Libafb6d62021-12-10 03:14:59 -08002200 }
Wei Libafb6d62021-12-10 03:14:59 -08002201}