blob: fdc164e116472f5445707d48d08e0a900f59a7dd [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
Chris Parsons39a16972023-06-08 14:28:51 +000023 "android/soong/ui/metrics/bp2build_metrics_proto"
Jihoon Kang1bfb6f22023-07-01 00:13:47 +000024
Jaewoong Jung26342642021-03-17 15:56:23 -070025 "github.com/google/blueprint/pathtools"
26 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
29 "android/soong/dexpreopt"
30 "android/soong/java/config"
31)
32
33// This file contains the definition and the implementation of the base module that most
34// source-based Java module structs embed.
35
36// TODO:
37// Autogenerated files:
38// Renderscript
39// Post-jar passes:
40// Proguard
41// Rmtypedefs
42// DroidDoc
43// Findbugs
44
45// Properties that are common to most Java modules, i.e. whether it's a host or device module.
46type CommonProperties struct {
47 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
48 // or .aidl files.
49 Srcs []string `android:"path,arch_variant"`
50
51 // list Kotlin of source files containing Kotlin code that should be treated as common code in
52 // a codebase that supports Kotlin multiplatform. See
53 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
54 Common_srcs []string `android:"path,arch_variant"`
55
56 // list of source files that should not be used to build the Java module.
57 // This is most useful in the arch/multilib variants to remove non-common files
58 Exclude_srcs []string `android:"path,arch_variant"`
59
60 // list of directories containing Java resources
61 Java_resource_dirs []string `android:"arch_variant"`
62
63 // list of directories that should be excluded from java_resource_dirs
64 Exclude_java_resource_dirs []string `android:"arch_variant"`
65
66 // list of files to use as Java resources
67 Java_resources []string `android:"path,arch_variant"`
68
69 // list of files that should be excluded from java_resources and java_resource_dirs
70 Exclude_java_resources []string `android:"path,arch_variant"`
71
72 // list of module-specific flags that will be used for javac compiles
73 Javacflags []string `android:"arch_variant"`
74
75 // list of module-specific flags that will be used for kotlinc compiles
76 Kotlincflags []string `android:"arch_variant"`
77
78 // list of java libraries that will be in the classpath
79 Libs []string `android:"arch_variant"`
80
81 // list of java libraries that will be compiled into the resulting jar
82 Static_libs []string `android:"arch_variant"`
83
Jihoon Kang381c2fa2023-06-01 22:17:32 +000084 // list of java libraries that should not be used to build this module
85 Exclude_static_libs []string `android:"arch_variant"`
86
Jaewoong Jung26342642021-03-17 15:56:23 -070087 // manifest file to be included in resulting jar
88 Manifest *string `android:"path"`
89
90 // if not blank, run jarjar using the specified rules file
91 Jarjar_rules *string `android:"path,arch_variant"`
92
93 // If not blank, set the java version passed to javac as -source and -target
94 Java_version *string
95
96 // If set to true, allow this module to be dexed and installed on devices. Has no
97 // effect on host modules, which are always considered installable.
98 Installable *bool
99
100 // If set to true, include sources used to compile the module in to the final jar
101 Include_srcs *bool
102
103 // If not empty, classes are restricted to the specified packages and their sub-packages.
104 // This restriction is checked after applying jarjar rules and including static libs.
105 Permitted_packages []string
106
107 // List of modules to use as annotation processors
108 Plugins []string
109
110 // List of modules to export to libraries that directly depend on this library as annotation
111 // processors. Note that if the plugins set generates_api: true this will disable the turbine
112 // optimization on modules that depend on this module, which will reduce parallelism and cause
113 // more recompilation.
114 Exported_plugins []string
115
116 // The number of Java source entries each Javac instance can process
117 Javac_shard_size *int64
118
119 // Add host jdk tools.jar to bootclasspath
120 Use_tools_jar *bool
121
122 Openjdk9 struct {
123 // List of source files that should only be used when passing -source 1.9 or higher
124 Srcs []string `android:"path"`
125
126 // List of javac flags that should only be used when passing -source 1.9 or higher
127 Javacflags []string
128 }
129
130 // When compiling language level 9+ .java code in packages that are part of
131 // a system module, patch_module names the module that your sources and
132 // dependencies should be patched into. The Android runtime currently
133 // doesn't implement the JEP 261 module system so this option is only
134 // supported at compile time. It should only be needed to compile tests in
135 // packages that exist in libcore and which are inconvenient to move
136 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400137 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700138
139 Jacoco struct {
140 // List of classes to include for instrumentation with jacoco to collect coverage
141 // information at runtime when building with coverage enabled. If unset defaults to all
142 // classes.
143 // Supports '*' as the last character of an entry in the list as a wildcard match.
144 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
145 // it matches classes in the package that have the class name as a prefix.
146 Include_filter []string
147
148 // List of classes to exclude from instrumentation with jacoco to collect coverage
149 // information at runtime when building with coverage enabled. Overrides classes selected
150 // by the include_filter property.
151 // Supports '*' as the last character of an entry in the list as a wildcard match.
152 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
153 // it matches classes in the package that have the class name as a prefix.
154 Exclude_filter []string
155 }
156
157 Errorprone struct {
158 // List of javac flags that should only be used when running errorprone.
159 Javacflags []string
160
161 // List of java_plugin modules that provide extra errorprone checks.
162 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700163
Cole Faust2b1536e2021-06-18 12:25:54 -0700164 // This property can be in 3 states. When set to true, errorprone will
165 // be run during the regular build. When set to false, errorprone will
166 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
167 // environment variable is true. Setting this to false will improve build
168 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700169 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700170 }
171
172 Proto struct {
173 // List of extra options that will be passed to the proto generator.
174 Output_params []string
175 }
176
Sam Delmericoc7593722022-08-31 15:57:52 -0400177 // If true, then jacocoagent is automatically added as a libs dependency so that
178 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000180 // If true, then the module supports statically including the jacocoagent
181 // into the library.
182 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700183
184 // List of files to include in the META-INF/services folder of the resulting jar.
185 Services []string `android:"path,arch_variant"`
186
187 // If true, package the kotlin stdlib into the jar. Defaults to true.
188 Static_kotlin_stdlib *bool `android:"arch_variant"`
189
190 // A list of java_library instances that provide additional hiddenapi annotations for the library.
191 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700192
193 // Additional srcJars tacked in by GeneratedJavaLibraryModule
194 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000195
196 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400197 Headers_only *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700198}
199
200// Properties that are specific to device modules. Host module factories should not add these when
201// constructing a new module.
202type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000203 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000204 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000206 // 1) numerical API level, "current", "none", or "core_platform"
207 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
208 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
209 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700210 Sdk_version *string
211
212 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000213 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700214 Min_sdk_version *string
215
satayev0a420e72021-11-29 17:25:52 +0000216 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
217 // Defaults to empty string "". See sdk_version for possible values.
218 Max_sdk_version *string
219
William Loh5a082f92022-05-17 20:21:50 +0000220 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
221 // Defaults to empty string "". See sdk_version for possible values.
222 Replace_max_sdk_version_placeholder *string
223
Jaewoong Jung26342642021-03-17 15:56:23 -0700224 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000225 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700226 Target_sdk_version *string
227
228 // Whether to compile against the platform APIs instead of an SDK.
229 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000230 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700231 Platform_apis *bool
232
233 Aidl struct {
234 // Top level directories to pass to aidl tool
235 Include_dirs []string
236
237 // Directories rooted at the Android.bp file to pass to aidl tool
238 Local_include_dirs []string
239
240 // directories that should be added as include directories for any aidl sources of modules
241 // that depend on this module, as well as to aidl for this module.
242 Export_include_dirs []string
243
244 // whether to generate traces (for systrace) for this interface
245 Generate_traces *bool
246
247 // whether to generate Binder#GetTransaction name method.
248 Generate_get_transaction_name *bool
249
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100250 // whether all interfaces should be annotated with required permissions.
251 Enforce_permissions *bool
252
253 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
254 Enforce_permissions_exceptions []string `android:"path"`
255
Jaewoong Jung26342642021-03-17 15:56:23 -0700256 // list of flags that will be passed to the AIDL compiler
257 Flags []string
258 }
259
260 // If true, export a copy of the module as a -hostdex module for host testing.
261 Hostdex *bool
262
263 Target struct {
264 Hostdex struct {
265 // Additional required dependencies to add to -hostdex modules.
266 Required []string
267 }
268 }
269
270 // When targeting 1.9 and above, override the modules to use with --system,
271 // otherwise provides defaults libraries to add to the bootclasspath.
272 System_modules *string
273
Jaewoong Jung26342642021-03-17 15:56:23 -0700274 IsSDKLibrary bool `blueprint:"mutated"`
275
276 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
277 // Defaults to false.
278 V4_signature *bool
279
280 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
281 // public stubs library.
282 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000283
284 HiddenAPIPackageProperties
285 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700286}
287
Jooyung Han01d80d82022-01-08 12:16:32 +0900288// Device properties that can be overridden by overriding module (e.g. override_android_app)
289type OverridableDeviceProperties struct {
290 // set the name of the output. If not set, `name` is used.
291 // To override a module with this property set, overriding module might need to set this as well.
292 // Otherwise, both the overridden and the overriding modules will have the same output name, which
293 // can cause the duplicate output error.
294 Stem *string
295}
296
Jaewoong Jung26342642021-03-17 15:56:23 -0700297// Functionality common to Module and Import
298//
299// It is embedded in Module so its functionality can be used by methods in Module
300// but it is currently only initialized by Import and Library.
301type embeddableInModuleAndImport struct {
302
303 // Functionality related to this being used as a component of a java_sdk_library.
304 EmbeddableSdkLibraryComponent
305}
306
Paul Duffin71b33cc2021-06-23 11:39:47 +0100307func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
308 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700309}
310
311// Module/Import's DepIsInSameApex(...) delegates to this method.
312//
313// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
314// the one provided by ApexModuleBase.
315func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
316 // dependencies other than the static linkage are all considered crossing APEX boundary
317 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
318 return true
319 }
320 return false
321}
322
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100323// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
324// or an invalid path describing the reason it is invalid.
325//
326// It is unset if a dex jar isn't applicable, i.e. no build rule has been
327// requested to create one.
328//
329// If a dex jar has been requested to be built then it is set, and it may be
330// either a valid android.Path, or invalid with a reason message. The latter
331// happens if the source that should produce the dex file isn't able to.
332//
333// E.g. it is invalid with a reason message if there is a prebuilt APEX that
334// could produce the dex jar through a deapexer module, but the APEX isn't
335// installable so doing so wouldn't be safe.
336type OptionalDexJarPath struct {
337 isSet bool
338 path android.OptionalPath
339}
340
341// IsSet returns true if a path has been set, either invalid or valid.
342func (o OptionalDexJarPath) IsSet() bool {
343 return o.isSet
344}
345
346// Valid returns true if there is a path that is valid.
347func (o OptionalDexJarPath) Valid() bool {
348 return o.isSet && o.path.Valid()
349}
350
351// Path returns the valid path, or panics if it's either not set or is invalid.
352func (o OptionalDexJarPath) Path() android.Path {
353 if !o.isSet {
354 panic("path isn't set")
355 }
356 return o.path.Path()
357}
358
359// PathOrNil returns the path if it's set and valid, or else nil.
360func (o OptionalDexJarPath) PathOrNil() android.Path {
361 if o.Valid() {
362 return o.Path()
363 }
364 return nil
365}
366
367// InvalidReason returns the reason for an invalid path, which is never "". It
368// returns "" for an unset or valid path.
369func (o OptionalDexJarPath) InvalidReason() string {
370 if !o.isSet {
371 return ""
372 }
373 return o.path.InvalidReason()
374}
375
376func (o OptionalDexJarPath) String() string {
377 if !o.isSet {
378 return "<unset>"
379 }
380 return o.path.String()
381}
382
383// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
384func makeUnsetDexJarPath() OptionalDexJarPath {
385 return OptionalDexJarPath{isSet: false}
386}
387
388// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
389// the given OptionalPath, which may be valid or invalid.
390func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
391 return OptionalDexJarPath{isSet: true, path: path}
392}
393
394// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
395// valid given path. It returns an unset OptionalDexJarPath if the given path is
396// nil.
397func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
398 if path == nil {
399 return makeUnsetDexJarPath()
400 }
401 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
402}
403
Jaewoong Jung26342642021-03-17 15:56:23 -0700404// Module contains the properties and members used by all java module types
405type Module struct {
406 android.ModuleBase
407 android.DefaultableModuleBase
408 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800409 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700410
411 // Functionality common to Module and Import.
412 embeddableInModuleAndImport
413
414 properties CommonProperties
415 protoProperties android.ProtoProperties
416 deviceProperties DeviceProperties
417
Jooyung Han01d80d82022-01-08 12:16:32 +0900418 overridableDeviceProperties OverridableDeviceProperties
419
Jaewoong Jung26342642021-03-17 15:56:23 -0700420 // jar file containing header classes including static library dependencies, suitable for
421 // inserting into the bootclasspath/classpath of another compile
422 headerJarFile android.Path
423
424 // jar file containing implementation classes including static library dependencies but no
425 // resources
426 implementationJarFile android.Path
427
428 // jar file containing only resources including from static library dependencies
429 resourceJar android.Path
430
431 // args and dependencies to package source files into a srcjar
432 srcJarArgs []string
433 srcJarDeps android.Paths
434
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000435 // the source files of this module and all its static dependencies
436 transitiveSrcFiles *android.DepSet[android.Path]
437
Jaewoong Jung26342642021-03-17 15:56:23 -0700438 // jar file containing implementation classes and resources including static library
439 // dependencies
440 implementationAndResourcesJar android.Path
441
442 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100443 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700444
445 // output file containing uninstrumented classes that will be instrumented by jacoco
446 jacocoReportClassesFile android.Path
447
448 // output file of the module, which may be a classes jar or a dex jar
449 outputFile android.Path
450 extraOutputFiles android.Paths
451
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100452 exportAidlIncludeDirs android.Paths
453 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700454
455 logtagsSrcs android.Paths
456
457 // installed file for binary dependency
458 installFile android.Path
459
Colin Cross3108ce12021-11-10 14:38:50 -0800460 // installed file for hostdex copy
461 hostdexInstallFile android.InstallPath
462
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800463 // list of unique .java and .kt source files
464 uniqueSrcFiles android.Paths
465
466 // list of srcjars that was passed to javac
467 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700468
469 // manifest file to use instead of properties.Manifest
470 overrideManifest android.OptionalPath
471
Jaewoong Jung26342642021-03-17 15:56:23 -0700472 // list of plugins that this java module is exporting
473 exportedPluginJars android.Paths
474
475 // list of plugins that this java module is exporting
476 exportedPluginClasses []string
477
478 // if true, the exported plugins generate API and require disabling turbine.
479 exportedDisableTurbine bool
480
481 // list of source files, collected from srcFiles with unique java and all kt files,
482 // will be used by android.IDEInfo struct
483 expandIDEInfoCompiledSrcs []string
484
485 // expanded Jarjar_rules
486 expandJarjarRules android.Path
487
Jaewoong Jung26342642021-03-17 15:56:23 -0700488 // Extra files generated by the module type to be added as java resources.
489 extraResources android.Paths
490
491 hiddenAPI
492 dexer
493 dexpreopter
494 usesLibrary
495 linter
496
497 // list of the xref extraction files
498 kytheFiles android.Paths
499
Jaewoong Jung26342642021-03-17 15:56:23 -0700500 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900501
502 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000503 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000504 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400505
506 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000507
508 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000509
510 // output file name based on Stem property.
511 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
512 // or the module should override Stem().
513 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700514
515 // Aconfig "cache files" that went directly into this module. Transitive ones are
516 // tracked via JavaInfo.TransitiveAconfigFiles
517 // TODO: Extract to something standalone to propagate tags via GeneratedJavaLibraryModule
518 aconfigIntermediates android.Paths
519
520 // Aconfig files for all transitive deps. Also exposed via JavaInfo
521 transitiveAconfigFiles *android.DepSet[android.Path]
Jaewoong Jung26342642021-03-17 15:56:23 -0700522}
523
Jiyong Park92315372021-04-02 08:45:46 +0900524func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
525 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900526 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700527 return nil
528 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900529 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000530 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700531 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
532 } else {
533 // Treat stable core platform as stable.
534 return nil
535 }
536 } else {
537 return fmt.Errorf("non stable SDK %v", sdkVersion)
538 }
539}
540
541// checkSdkVersions enforces restrictions around SDK dependencies.
542func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
543 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900544 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900545 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700546 ctx.PropertyErrorf("sdk_version",
547 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
548 }
549 }
550 }
551
552 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
553 // See rank() for details.
554 ctx.VisitDirectDeps(func(module android.Module) {
555 tag := ctx.OtherModuleDependencyTag(module)
556 switch module.(type) {
557 // TODO(satayev): cover other types as well, e.g. imports
558 case *Library, *AndroidLibrary:
559 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400560 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700561 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
562 }
563 }
564 })
565}
566
567func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900568 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700569 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900570 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700571 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000572 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 -0700573 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000574 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 -0700575 }
576
577 }
578}
579
Mark Whitea15790a2023-08-22 21:28:11 +0000580func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
581 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400582 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000583 installable := proptools.Bool(j.properties.Installable)
584
585 if headersOnly && installable {
586 ctx.PropertyErrorf("headers_only", "This module has conflicting settings. headers_only is true which, which means this module doesn't generate an implementation jar. However installable is set to true.")
587 }
588 }
589}
590
Jaewoong Jung26342642021-03-17 15:56:23 -0700591func (j *Module) addHostProperties() {
592 j.AddProperties(
593 &j.properties,
594 &j.protoProperties,
595 &j.usesLibraryProperties,
596 )
597}
598
599func (j *Module) addHostAndDeviceProperties() {
600 j.addHostProperties()
601 j.AddProperties(
602 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900603 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700604 &j.dexer.dexProperties,
605 &j.dexpreoptProperties,
606 &j.linter.properties,
607 )
608}
609
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000610// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
611// makes it available through the hiddenAPIPropertyInfoProvider.
612func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
613 hiddenAPIInfo := newHiddenAPIPropertyInfo()
614
615 // Populate with flag file paths from the properties.
616 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
617
618 // Populate with package rules from the properties.
619 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
620
621 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
622}
623
Jaewoong Jung26342642021-03-17 15:56:23 -0700624func (j *Module) OutputFiles(tag string) (android.Paths, error) {
625 switch tag {
626 case "":
627 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
628 case android.DefaultDistTag:
629 return android.Paths{j.outputFile}, nil
630 case ".jar":
631 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700632 case ".hjar":
633 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700634 case ".proguard_map":
635 if j.dexer.proguardDictionary.Valid() {
636 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
637 }
638 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700639 case ".generated_srcjars":
640 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000641 case ".lint":
642 if j.linter.outputs.xml != nil {
643 return android.Paths{j.linter.outputs.xml}, nil
644 }
645 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700646 default:
647 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
648 }
649}
650
651var _ android.OutputFileProducer = (*Module)(nil)
652
653func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
654 initJavaModule(module, hod, false)
655}
656
657func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
658 initJavaModule(module, hod, true)
659}
660
661func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
662 multilib := android.MultilibCommon
663 if multiTargets {
664 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
665 } else {
666 android.InitAndroidArchModule(module, hod, multilib)
667 }
668 android.InitDefaultableModule(module)
669}
670
671func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
672 return j.properties.Instrument &&
673 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
674 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
675}
676
677func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000678 return j.properties.Supports_static_instrumentation &&
679 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700680 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
681 ctx.Config().UnbundledBuild())
682}
683
684func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
685 // Force enable the instrumentation for java code that is built for APEXes ...
686 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
687 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
688 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
689 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
690 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
691 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
692 return true
693 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
694 return true
695 }
696 }
697 return false
698}
699
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400700func (j *Module) setInstrument(value bool) {
701 j.properties.Instrument = value
702}
703
Jiyong Park92315372021-04-02 08:45:46 +0900704func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
705 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700706}
707
Jiyong Parkf1691d22021-03-29 20:11:58 +0900708func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700709 return proptools.String(j.deviceProperties.System_modules)
710}
711
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000712func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700713 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000714 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700715 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000716 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700717}
718
Yu Liuf2b94012023-09-19 15:09:10 -0700719func (j *Module) GetDeviceProperties() *DeviceProperties {
720 return &j.deviceProperties
721}
722
Spandan Dasa26eda72023-03-02 00:56:06 +0000723func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
724 if j.deviceProperties.Max_sdk_version != nil {
725 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
726 }
727 // Default is PrivateApiLevel
728 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000729}
730
Spandan Dasa26eda72023-03-02 00:56:06 +0000731func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
732 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
733 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
734 }
735 // Default is PrivateApiLevel
736 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000737}
738
Jiyong Parkf1691d22021-03-29 20:11:58 +0900739func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000740 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900741}
742
Spandan Dasca70fc42023-03-01 23:38:49 +0000743func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900744 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000745 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900746 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000747 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700748}
749
750func (j *Module) AvailableFor(what string) bool {
751 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
752 // Exception: for hostdex: true libraries, the platform variant is created
753 // even if it's not marked as available to platform. In that case, the platform
754 // variant is used only for the hostdex and not installed to the device.
755 return true
756 }
757 return j.ApexModuleBase.AvailableFor(what)
758}
759
760func (j *Module) deps(ctx android.BottomUpMutatorContext) {
761 if ctx.Device() {
762 j.linter.deps(ctx)
763
Jiyong Parkf1691d22021-03-29 20:11:58 +0900764 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700765
766 if j.deviceProperties.SyspropPublicStub != "" {
767 // This is a sysprop implementation library that has a corresponding sysprop public
768 // stubs library, and a dependency on it so that dependencies on the implementation can
769 // be forwarded to the public stubs library when necessary.
770 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
771 }
772 }
773
774 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000775
776 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700777 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
778
779 // Add dependency on libraries that provide additional hidden api annotations.
780 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
781
782 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
783 // Require java_sdk_library at inter-partition java dependency to ensure stable
784 // interface between partitions. If inter-partition java_library dependency is detected,
785 // raise build error because java_library doesn't have a stable interface.
786 //
787 // Inputs:
788 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
789 // if true, enable enforcement
790 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
791 // exception list of java_library names to allow inter-partition dependency
792 for idx := range j.properties.Libs {
793 if libDeps[idx] == nil {
794 continue
795 }
796
797 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
798 // java_sdk_library is always allowed at inter-partition dependency.
799 // So, skip check.
800 if _, ok := javaDep.(*SdkLibrary); ok {
801 continue
802 }
803
804 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
805 }
806 }
807 }
808
809 // For library dependencies that are component libraries (like stubs), add the implementation
810 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
811 for _, dep := range libDeps {
812 if dep != nil {
813 if component, ok := dep.(SdkLibraryComponentDependency); ok {
814 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100815 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100816 tag := usesLibReqTag
817 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
818 tag = usesLibOptTag
819 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100820 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700821 }
822 }
823 }
824 }
825
826 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
827 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
828 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
829
830 android.ProtoDeps(ctx, &j.protoProperties)
831 if j.hasSrcExt(".proto") {
832 protoDeps(ctx, &j.protoProperties)
833 }
834
835 if j.hasSrcExt(".kt") {
836 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
837 // Kotlin files
838 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
839 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700840 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700841 }
842
843 // Framework libraries need special handling in static coverage builds: they should not have
844 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
845 // the same jacoco classes coming from different bootclasspath jars.
846 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
847 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
848 j.properties.Instrument = true
849 }
850 } else if j.shouldInstrumentStatic(ctx) {
851 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
852 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700853
854 if j.useCompose() {
855 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
856 "androidx.compose.compiler_compiler-hosted")
857 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700858}
859
860func hasSrcExt(srcs []string, ext string) bool {
861 for _, src := range srcs {
862 if filepath.Ext(src) == ext {
863 return true
864 }
865 }
866
867 return false
868}
869
870func (j *Module) hasSrcExt(ext string) bool {
871 return hasSrcExt(j.properties.Srcs, ext)
872}
873
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100874func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
875 var flags string
876
877 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
878 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
879 flags = "-Wmissing-permission-annotation -Werror"
880 }
881 }
882 return flags
883}
884
Jaewoong Jung26342642021-03-17 15:56:23 -0700885func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000886 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700887
888 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
889 aidlIncludes = append(aidlIncludes,
890 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
891 aidlIncludes = append(aidlIncludes,
892 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
893
894 var flags []string
895 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000896 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700897
898 flags = append(flags, j.deviceProperties.Aidl.Flags...)
899
900 if aidlPreprocess.Valid() {
901 flags = append(flags, "-p"+aidlPreprocess.String())
902 deps = append(deps, aidlPreprocess.Path())
903 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000904 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700905 }
906
907 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000908 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700909 }
910
911 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000912 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700913 }
914
Sam Delmerico2351eac2022-05-24 17:10:02 +0000915 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700916 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000917 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700918 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000919 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
920 // add flags for dirs containing AIDL srcs that haven't been specified yet
921 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700922
Zim8774ae12022-08-17 11:46:34 +0100923 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000924 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100925 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700926 flags = append(flags, "-t")
927 }
928
929 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
930 flags = append(flags, "--transaction_names")
931 }
932
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100933 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
934 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
935 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
936 }
937
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000938 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900939 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
940
Jaewoong Jung26342642021-03-17 15:56:23 -0700941 return strings.Join(flags, " "), deps
942}
943
944func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
945
946 var flags javaBuilderFlags
947
948 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900949 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700950
Cole Faust2b1536e2021-06-18 12:25:54 -0700951 epEnabled := j.properties.Errorprone.Enabled
952 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100953 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700954 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
955 }
956
957 errorProneFlags := []string{
958 "-Xplugin:ErrorProne",
959 "${config.ErrorProneChecks}",
960 }
961 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
962
Colin Cross8bf6cad2022-02-28 13:07:03 -0800963 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700964 "'" + strings.Join(errorProneFlags, " ") + "'"
965 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
966 }
967
968 // classpath
969 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
970 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700971 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700972 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
973 flags.processorPath = append(flags.processorPath, deps.processorPath...)
974 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
975
976 flags.processors = append(flags.processors, deps.processorClasses...)
977 flags.processors = android.FirstUniqueStrings(flags.processors)
978
979 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900980 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700981 // Give host-side tools a version of OpenJDK's standard libraries
982 // close to what they're targeting. As of Dec 2017, AOSP is only
983 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
984 //
985 // When building with OpenJDK 8, the following should have no
986 // effect since those jars would be available by default.
987 //
988 // When building with OpenJDK 9 but targeting a version < 1.8,
989 // putting them on the bootclasspath means that:
990 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
991 // b) references to existing APIs are not reinterpreted in an
992 // OpenJDK 9-specific way, eg. calls to subclasses of
993 // java.nio.Buffer as in http://b/70862583
994 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
995 flags.bootClasspath = append(flags.bootClasspath,
996 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
997 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
998 if Bool(j.properties.Use_tools_jar) {
999 flags.bootClasspath = append(flags.bootClasspath,
1000 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1001 }
1002 }
1003
1004 // systemModules
1005 flags.systemModules = deps.systemModules
1006
Jaewoong Jung26342642021-03-17 15:56:23 -07001007 return flags
1008}
1009
1010func (j *Module) collectJavacFlags(
1011 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1012 // javac flags.
1013 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001014 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001015
Mythri Alle4b9f6182023-10-25 15:17:11 +00001016 needsDebugInfo = false
1017 for _, flag := range javacFlags {
1018 if strings.HasPrefix(flag, "-g") {
1019 needsDebugInfo = true
1020 }
1021 }
1022
1023 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001024 // For non-host binaries, override the -g flag passed globally to remove
1025 // local variable debug info to reduce disk and memory usage.
1026 javacFlags = append(javacFlags, "-g:source,lines")
1027 }
1028 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1029
1030 if flags.javaVersion.usesJavaModules() {
1031 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001032 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1033 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1034 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1035 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001036
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001037 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001038 if j.properties.Patch_module != nil {
1039 // Manually specify build directory in case it is not under the repo root.
1040 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1041 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001042 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001043
1044 // b/150878007
1045 //
1046 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1047 // execution root for --patch-module. If this javac command line is
1048 // invoked within Bazel's execution root working directory, the top
1049 // level directories (e.g. libcore/, tools/, frameworks/) are all
1050 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1051 // --patch-module to fail source file lookups when invoked in the
1052 // execution root.
1053 //
1054 // Short of patching javac or enumerating *all* directories as possible
1055 // input dirs, manually add the top level dir of the source files to be
1056 // compiled.
1057 topLevelDirs := map[string]bool{}
1058 for _, srcFilePath := range srcFiles {
1059 srcFileParts := strings.Split(srcFilePath.String(), "/")
1060 // Ignore source files that are already in the top level directory
1061 // as well as generated files in the out directory. The out
1062 // directory may be an absolute path, which means srcFileParts[0] is the
1063 // empty string, so check that as well. Note that "out" in Bazel's execution
1064 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1065 // anyway, so it's fine to not apply this workaround for generated
1066 // source files.
1067 if len(srcFileParts) > 1 &&
1068 srcFileParts[0] != "" &&
1069 srcFileParts[0] != "out" {
1070 topLevelDirs[srcFileParts[0]] = true
1071 }
1072 }
Cole Faust18994c72023-02-28 16:02:16 -08001073 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001074
1075 classPath := flags.classpath.FormJavaClassPath("")
1076 if classPath != "" {
1077 patchPaths = append(patchPaths, classPath)
1078 }
1079 javacFlags = append(
1080 javacFlags,
1081 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1082 }
1083 }
1084
1085 if len(javacFlags) > 0 {
1086 // optimization.
1087 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1088 flags.javacFlags = "$javacFlags"
1089 }
1090
1091 return flags
1092}
1093
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001094func (j *Module) AddJSONData(d *map[string]interface{}) {
1095 (&j.ModuleBase).AddJSONData(d)
1096 (*d)["Java"] = map[string]interface{}{
1097 "SourceExtensions": j.sourceExtensions,
1098 }
1099
1100}
1101
usta0391ca42023-09-19 15:51:59 -04001102func (j *Module) addGeneratedSrcJars(path android.Path) {
1103 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001104}
1105
Colin Cross4eae06d2023-06-20 22:40:02 -07001106func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1108
1109 deps := j.collectDeps(ctx)
1110 flags := j.collectBuilderFlags(ctx, deps)
1111
1112 if flags.javaVersion.usesJavaModules() {
1113 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001114 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1115 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1116 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001117 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001118
Jaewoong Jung26342642021-03-17 15:56:23 -07001119 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001120 j.sourceExtensions = []string{}
1121 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1122 if hasSrcExt(srcFiles.Strings(), ext) {
1123 j.sourceExtensions = append(j.sourceExtensions, ext)
1124 }
1125 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 if hasSrcExt(srcFiles.Strings(), ".proto") {
1127 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1128 }
1129
1130 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1131 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1132 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1133 }
1134
Sam Delmerico2351eac2022-05-24 17:10:02 +00001135 aidlSrcs := srcFiles.FilterByExt(".aidl")
1136 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1137
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001138 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001139 srcFiles = j.genSources(ctx, srcFiles, flags)
1140
1141 // Collect javac flags only after computing the full set of srcFiles to
1142 // ensure that the --patch-module lookup paths are complete.
1143 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1144
1145 srcJars := srcFiles.FilterByExt(".srcjar")
1146 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001147 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001148 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001149 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001150
1151 if j.properties.Jarjar_rules != nil {
1152 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1153 }
1154
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001155 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001156
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001157 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001158 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001159 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 if _, found := set[v.String()]; !found {
1161 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001162 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 }
1164 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001165 var uniqueKtFiles android.Paths
1166 for _, v := range srcFiles.FilterByExt(".kt") {
1167 if _, found := set[v.String()]; !found {
1168 set[v.String()] = true
1169 uniqueKtFiles = append(uniqueKtFiles, v)
1170 }
1171 }
1172
1173 var uniqueSrcFiles android.Paths
1174 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1175 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1176 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001177
Colin Crossb5db4012022-03-28 17:12:39 -07001178 // We don't currently run annotation processors in turbine, which means we can't use turbine
1179 // generated header jars when an annotation processor that generates API is enabled. One
1180 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1181 // is used to run all of the annotation processors.
1182 disableTurbine := deps.disableTurbine
1183
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001184 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001185 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1186
1187 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001188 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001189
Colin Cross4eae06d2023-06-20 22:40:02 -07001190 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1191 // any dependencies so that it can override any non-final R classes from dependencies with the
1192 // final R classes from the app.
1193 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1194
Mark Whitea15790a2023-08-22 21:28:11 +00001195 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001196 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001197 if srcFiles.HasExt(".kt") {
1198 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1199 }
1200 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1201 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1202 }
1203
1204 _, j.headerJarFile =
1205 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1206 extraCombinedJars)
1207 if ctx.Failed() {
1208 return
1209 }
1210
1211 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1212 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1213 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1214 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1215 AidlIncludeDirs: j.exportAidlIncludeDirs,
1216 ExportedPlugins: j.exportedPluginJars,
1217 ExportedPluginClasses: j.exportedPluginClasses,
1218 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1219 })
1220
1221 j.outputFile = j.headerJarFile
1222 return
1223 }
1224
Jaewoong Jung26342642021-03-17 15:56:23 -07001225 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001226 // When using kotlin sources turbine is used to generate annotation processor sources,
1227 // including for annotation processors that generate API, so we can use turbine for
1228 // java sources too.
1229 disableTurbine = false
1230
Jaewoong Jung26342642021-03-17 15:56:23 -07001231 // user defined kotlin flags.
1232 kotlincFlags := j.properties.Kotlincflags
1233 CheckKotlincFlags(ctx, kotlincFlags)
1234
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001235 // Workaround for KT-46512
1236 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001237
1238 // If there are kotlin files, compile them first but pass all the kotlin and java files
1239 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1240 // won't emit any classes for them.
1241 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1242 if ctx.Device() {
1243 kotlincFlags = append(kotlincFlags, "-no-jdk")
1244 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001245
1246 for _, plugin := range deps.kotlinPlugins {
1247 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1248 }
1249 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1250
Jaewoong Jung26342642021-03-17 15:56:23 -07001251 if len(kotlincFlags) > 0 {
1252 // optimization.
1253 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1254 flags.kotlincFlags += "$kotlincFlags"
1255 }
1256
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001257 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001258 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1259
1260 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1261 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1262
1263 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1264 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1265
Isaac Chioua23d9942022-04-06 06:14:38 +00001266 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001267 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001268 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1269 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001270 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001271 srcJars = append(srcJars, kaptSrcJar)
1272 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001273 // Disable annotation processing in javac, it's already been handled by kapt
1274 flags.processorPath = nil
1275 flags.processors = nil
1276 }
1277
1278 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001279 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001280 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001281 if ctx.Failed() {
1282 return
1283 }
1284
Isaac Chioua23d9942022-04-06 06:14:38 +00001285 // Make javac rule depend on the kotlinc rule
1286 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1287
Jaewoong Jung26342642021-03-17 15:56:23 -07001288 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001289 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1290
Jaewoong Jung26342642021-03-17 15:56:23 -07001291 // Jar kotlin classes into the final jar after javac
1292 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1293 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001294 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001295 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001296 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001297 } else {
1298 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001299 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001300 }
1301 }
1302
1303 jars := append(android.Paths(nil), kotlinJars...)
1304
Jaewoong Jung26342642021-03-17 15:56:23 -07001305 j.compiledSrcJars = srcJars
1306
1307 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001308 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001309 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001310 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1311 enableSharding = true
1312 // Formerly, there was a check here that prevented annotation processors
1313 // from being used when sharding was enabled, as some annotation processors
1314 // do not function correctly in sharded environments. It was removed to
1315 // allow for the use of annotation processors that do function correctly
1316 // with sharding enabled. See: b/77284273.
1317 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001318 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001319 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001320 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001321 if ctx.Failed() {
1322 return
1323 }
1324 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001325 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001326 hasErrorproneableFiles := false
1327 for _, ext := range j.sourceExtensions {
1328 if ext != ".proto" && ext != ".aidl" {
1329 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1330 // compile, and it's not useful to have warnings on these generated sources.
1331 hasErrorproneableFiles = true
1332 break
1333 }
1334 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001335 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001336 if Bool(j.properties.Errorprone.Enabled) {
1337 // If error-prone is enabled, enable errorprone flags on the regular
1338 // build.
1339 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001340 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001341 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1342 // a new jar file just for compiling with the errorprone compiler to.
1343 // This is because we don't want to cause the java files to get completely
1344 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1345 // We also don't want to run this if errorprone is enabled by default for
1346 // this module, or else we could have duplicated errorprone messages.
1347 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001348 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001349 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001350
Vadim Spivak3c496f02023-06-08 06:14:59 +00001351 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001352 "errorprone", "errorprone")
1353
Jaewoong Jung26342642021-03-17 15:56:23 -07001354 extraJarDeps = append(extraJarDeps, errorprone)
1355 }
1356
1357 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001358 if headerJarFileWithoutDepsOrJarjar != nil {
1359 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1360 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001361 shardSize := int(*(j.properties.Javac_shard_size))
1362 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001363 if len(uniqueJavaFiles) > 0 {
1364 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001365 for idx, shardSrc := range shardSrcs {
1366 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1367 nil, flags, extraJarDeps)
1368 jars = append(jars, classes)
1369 }
1370 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001371 // Assume approximately 5 sources per srcjar.
1372 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1373 // of 5.8 sources per srcjar, but a median of 1, a standard deviation of 10, and a max of 48 source files.
Jaewoong Jung26342642021-03-17 15:56:23 -07001374 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001375 startIdx := len(shardSrcs)
1376 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1377 for idx, shardSrcJars := range shardSrcJarsList {
1378 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1379 nil, shardSrcJars, flags, extraJarDeps)
1380 jars = append(jars, classes)
1381 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001382 }
1383 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001384 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001385 jars = append(jars, classes)
1386 }
1387 if ctx.Failed() {
1388 return
1389 }
1390 }
1391
1392 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1393
1394 var includeSrcJar android.WritablePath
1395 if Bool(j.properties.Include_srcs) {
1396 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1397 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1398 }
1399
1400 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1401 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1402 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1403 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1404
1405 var resArgs []string
1406 var resDeps android.Paths
1407
1408 resArgs = append(resArgs, dirArgs...)
1409 resDeps = append(resDeps, dirDeps...)
1410
1411 resArgs = append(resArgs, fileArgs...)
1412 resDeps = append(resDeps, fileDeps...)
1413
1414 resArgs = append(resArgs, extraArgs...)
1415 resDeps = append(resDeps, extraDeps...)
1416
1417 if len(resArgs) > 0 {
1418 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1419 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1420 j.resourceJar = resourceJar
1421 if ctx.Failed() {
1422 return
1423 }
1424 }
1425
1426 var resourceJars android.Paths
1427 if j.resourceJar != nil {
1428 resourceJars = append(resourceJars, j.resourceJar)
1429 }
1430 if Bool(j.properties.Include_srcs) {
1431 resourceJars = append(resourceJars, includeSrcJar)
1432 }
1433 resourceJars = append(resourceJars, deps.staticResourceJars...)
1434
1435 if len(resourceJars) > 1 {
1436 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1437 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1438 false, nil, nil)
1439 j.resourceJar = combinedJar
1440 } else if len(resourceJars) == 1 {
1441 j.resourceJar = resourceJars[0]
1442 }
1443
1444 if len(deps.staticJars) > 0 {
1445 jars = append(jars, deps.staticJars...)
1446 }
1447
1448 manifest := j.overrideManifest
1449 if !manifest.Valid() && j.properties.Manifest != nil {
1450 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1451 }
1452
1453 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1454 if len(services) > 0 {
1455 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1456 var zipargs []string
1457 for _, file := range services {
1458 serviceFile := file.String()
1459 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1460 }
1461 rule := zip
1462 args := map[string]string{
1463 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1464 }
1465 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1466 rule = zipRE
1467 args["implicits"] = strings.Join(services.Strings(), ",")
1468 }
1469 ctx.Build(pctx, android.BuildParams{
1470 Rule: rule,
1471 Output: servicesJar,
1472 Implicits: services,
1473 Args: args,
1474 })
1475 jars = append(jars, servicesJar)
1476 }
1477
Colin Cross4eae06d2023-06-20 22:40:02 -07001478 jars = append(android.CopyOf(extraCombinedJars), jars...)
1479
Jaewoong Jung26342642021-03-17 15:56:23 -07001480 // Combine the classes built from sources, any manifests, and any static libraries into
1481 // classes.jar. If there is only one input jar this step will be skipped.
1482 var outputFile android.OutputPath
1483
1484 if len(jars) == 1 && !manifest.Valid() {
1485 // Optimization: skip the combine step as there is nothing to do
1486 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1487 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1488 // any if len(jars) == 1.
1489
Jihoon Kang1147b312023-06-08 23:25:57 +00001490 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1491 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1492 // either with .from-source or .from-text suffix.
1493 // outputFile should be agnostic to the build configuration,
1494 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1495 // to the copy rules.
1496 stub, _ := moduleStubLinkType(ctx.ModuleName())
1497
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 // Transform the single path to the jar into an OutputPath as that is required by the following
1499 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001500 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 // The path contains an embedded OutputPath so reuse that.
1502 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001503 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 // The path is an OutputPath so reuse it directly.
1505 outputFile = outputPath
1506 } else {
1507 // The file is not in the out directory so create an OutputPath into which it can be copied
1508 // and which the following code can use to refer to it.
1509 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1510 ctx.Build(pctx, android.BuildParams{
1511 Rule: android.Cp,
1512 Input: jars[0],
1513 Output: combinedJar,
1514 })
1515 outputFile = combinedJar.OutputPath
1516 }
1517 } else {
1518 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1519 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1520 false, nil, nil)
1521 outputFile = combinedJar.OutputPath
1522 }
1523
1524 // jarjar implementation jar if necessary
1525 if j.expandJarjarRules != nil {
1526 // Transform classes.jar into classes-jarjar.jar
1527 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1528 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1529 outputFile = jarjarFile
1530
1531 // jarjar resource jar if necessary
1532 if j.resourceJar != nil {
1533 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1534 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1535 j.resourceJar = resourceJarJarFile
1536 }
1537
1538 if ctx.Failed() {
1539 return
1540 }
1541 }
1542
1543 // Check package restrictions if necessary.
1544 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001545 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001546 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001547
1548 // Create a rule to copy the output jar to another path and add a validate dependency that
1549 // will check that the jar only contains the permitted packages. The new location will become
1550 // the output file of this module.
1551 inputFile := outputFile
1552 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1553 ctx.Build(pctx, android.BuildParams{
1554 Rule: android.Cp,
1555 Input: inputFile,
1556 Output: outputFile,
1557 // Make sure that any dependency on the output file will cause ninja to run the package check
1558 // rule.
1559 Validation: pkgckFile,
1560 })
1561
1562 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001563 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001564
1565 if ctx.Failed() {
1566 return
1567 }
1568 }
1569
1570 j.implementationJarFile = outputFile
1571 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001572 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1573 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1574 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1575 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1576 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1577 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1578 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001579 }
1580
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001581 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1582 specs := j.jacocoModuleToZipCommand(ctx)
1583 if ctx.Failed() {
1584 return
1585 }
1586
Jaewoong Jung26342642021-03-17 15:56:23 -07001587 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001588 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 }
1590
1591 // merge implementation jar with resources if necessary
1592 implementationAndResourcesJar := outputFile
1593 if j.resourceJar != nil {
1594 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1595 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1596 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1597 false, nil, nil)
1598 implementationAndResourcesJar = combinedJar
1599 }
1600
1601 j.implementationAndResourcesJar = implementationAndResourcesJar
1602
1603 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001604 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001605 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1606 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001607 if compileDex == nil {
1608 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001609 }
1610 if j.deviceProperties.Hostdex == nil {
1611 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1612 }
1613 }
1614
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001615 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001616 if j.hasCode(ctx) {
1617 if j.shouldInstrumentStatic(ctx) {
1618 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1619 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1620 }
1621 // Dex compilation
1622 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001623 params := &compileDexParams{
1624 flags: flags,
1625 sdkVersion: j.SdkVersion(ctx),
1626 minSdkVersion: j.MinSdkVersion(ctx),
1627 classesJar: implementationAndResourcesJar,
1628 jarName: jarName,
1629 }
1630 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001631 if ctx.Failed() {
1632 return
1633 }
1634
Jaewoong Jung26342642021-03-17 15:56:23 -07001635 // merge dex jar with resources if necessary
1636 if j.resourceJar != nil {
1637 jars := android.Paths{dexOutputFile, j.resourceJar}
1638 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1639 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1640 false, nil, nil)
1641 if *j.dexProperties.Uncompress_dex {
1642 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001643 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001644 dexOutputFile = combinedAlignedJar
1645 } else {
1646 dexOutputFile = combinedJar
1647 }
1648 }
1649
Paul Duffin4de94502021-05-16 05:21:16 +01001650 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001651
1652 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001653
1654 // Encode hidden API flags in dex file, if needed.
1655 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1656
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001657 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001658
1659 // Dexpreopting
1660 j.dexpreopt(ctx, dexOutputFile)
1661
1662 outputFile = dexOutputFile
1663 } else {
1664 // There is no code to compile into a dex jar, make sure the resources are propagated
1665 // to the APK if this is an app.
1666 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001667 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001668 }
1669
1670 if ctx.Failed() {
1671 return
1672 }
1673 } else {
1674 outputFile = implementationAndResourcesJar
1675 }
1676
1677 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001678 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1679 if !apiLevel.IsPreview() {
1680 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001681 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001682 // When running metalava, we pass --version-codename. When that value
1683 // is not REL, metalava will add 1 to the --current-version argument.
1684 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1685 // branch) and the codename is REL, except potentially on the most
1686 // recent non-master branch. On that branch, it goes through two other
1687 // phases before it gets to the phase previously described:
1688 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1689 // is not rel. This happens for most of the internal branch's life
1690 // while the branch has been cut but is still under active development.
1691 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1692 // REL. This happens briefly during the release process. During this
1693 // state the code to add --current-version is commented out, and then
1694 // that commenting out is reverted after the codename is set to REL.
1695 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1696 // prior version and the codename is always non-REL.
1697 //
1698 // We need to add one here to match metalava adding 1. Technically
1699 // this means that in the state described in the second bullet point
1700 // above, this number is 1 higher than it should be.
1701 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001702 }
1703 }
1704
1705 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001706 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1707 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001708 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1709 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001710 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001711 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001712 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001713 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001714 j.linter.javaLanguageLevel = flags.javaVersion.String()
1715 j.linter.kotlinLanguageLevel = "1.3"
1716 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1717 j.linter.buildModuleReportZip = true
1718 }
1719 j.linter.lint(ctx)
1720 }
1721
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001722 j.collectTransitiveSrcFiles(ctx, srcFiles)
1723
Jaewoong Jung26342642021-03-17 15:56:23 -07001724 ctx.CheckbuildFile(outputFile)
1725
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001726 j.collectTransitiveAconfigFiles(ctx)
1727
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1729 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001730 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1731 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001732 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1733 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1734 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1735 AidlIncludeDirs: j.exportAidlIncludeDirs,
1736 SrcJarArgs: j.srcJarArgs,
1737 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001738 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001739 ExportedPlugins: j.exportedPluginJars,
1740 ExportedPluginClasses: j.exportedPluginClasses,
1741 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1742 JacocoReportClassesFile: j.jacocoReportClassesFile,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001743 TransitiveAconfigFiles: j.transitiveAconfigFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001744 })
1745
1746 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1747 j.outputFile = outputFile.WithoutRel()
1748}
1749
Colin Crossa1ff7c62021-09-17 14:11:52 -07001750func (j *Module) useCompose() bool {
1751 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1752}
1753
Sam Delmerico95d70942023-08-02 18:00:35 -04001754func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1755 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1756 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1757
1758 ctx.VisitDirectDeps(func(m android.Module) {
1759 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1760 depTag := ctx.OtherModuleDependencyTag(m)
1761
1762 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1763 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1764 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1765 }
1766
1767 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1768 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1769 }
1770 })
1771
1772 directUnconditionalExportedFlags := android.Paths{}
1773 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1774 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1775 if exportUnconditionally {
1776 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1777 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1778 directUnconditionalExportedFlags = proguardFlagsForThisModule
1779 }
1780
1781 return ProguardSpecInfo{
1782 Export_proguard_flags_files: exportUnconditionally,
1783 ProguardFlagsFiles: android.NewDepSet[android.Path](
1784 android.POSTORDER,
1785 proguardFlagsForThisModule,
1786 transitiveProguardFlags,
1787 ),
1788 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1789 android.POSTORDER,
1790 directUnconditionalExportedFlags,
1791 transitiveUnconditionalExportedFlags,
1792 ),
1793 }
1794
1795}
1796
Cole Faust75fffb12021-06-13 15:23:16 -07001797// Returns a copy of the supplied flags, but with all the errorprone-related
1798// fields copied to the regular build's fields.
1799func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1800 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1801
1802 if len(flags.errorProneExtraJavacFlags) > 0 {
1803 if len(flags.javacFlags) > 0 {
1804 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1805 } else {
1806 flags.javacFlags = flags.errorProneExtraJavacFlags
1807 }
1808 }
1809 return flags
1810}
1811
Jaewoong Jung26342642021-03-17 15:56:23 -07001812func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1813 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1814
1815 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001816 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 if idx >= 0 {
1818 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001819 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001820 jarName += strconv.Itoa(idx)
1821 }
1822
1823 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001824 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001825
1826 if ctx.Config().EmitXrefRules() {
1827 extractionFile := android.PathForModuleOut(ctx, kzipName)
1828 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1829 j.kytheFiles = append(j.kytheFiles, extractionFile)
1830 }
1831
Vadim Spivak3c496f02023-06-08 06:14:59 +00001832 if len(flags.processorPath) > 0 {
1833 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1834 }
1835
Jaewoong Jung26342642021-03-17 15:56:23 -07001836 return classes
1837}
1838
1839// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1840// since some of these flags may be used internally.
1841func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1842 for _, flag := range flags {
1843 flag = strings.TrimSpace(flag)
1844
1845 if !strings.HasPrefix(flag, "-") {
1846 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1847 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1848 ctx.PropertyErrorf("kotlincflags",
1849 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1850 } else if inList(flag, config.KotlincIllegalFlags) {
1851 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1852 } else if flag == "-include-runtime" {
1853 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1854 } else {
1855 args := strings.Split(flag, " ")
1856 if args[0] == "-kotlin-home" {
1857 ctx.PropertyErrorf("kotlincflags",
1858 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1859 }
1860 }
1861 }
1862}
1863
1864func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1865 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001866 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001867
1868 var jars android.Paths
1869 if len(srcFiles) > 0 || len(srcJars) > 0 {
1870 // Compile java sources into turbine.jar.
1871 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1872 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1873 if ctx.Failed() {
1874 return nil, nil
1875 }
1876 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001877 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001878 }
1879
1880 jars = append(jars, extraJars...)
1881
1882 // Combine any static header libraries into classes-header.jar. If there is only
1883 // one input jar this step will be skipped.
1884 jars = append(jars, deps.staticHeaderJars...)
1885
1886 // we cannot skip the combine step for now if there is only one jar
1887 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1888 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1889 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1890 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001891 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001892
1893 if j.expandJarjarRules != nil {
1894 // Transform classes.jar into classes-jarjar.jar
1895 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001896 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1897 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001898 if ctx.Failed() {
1899 return nil, nil
1900 }
1901 }
1902
Colin Cross3d56ed52021-11-18 22:23:12 -08001903 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001904}
1905
1906func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001907 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001908
1909 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1910 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1911
1912 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1913
1914 j.jacocoReportClassesFile = jacocoReportClassesFile
1915
1916 return instrumentedJar
1917}
1918
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001919type providesTransitiveHeaderJars struct {
1920 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001921 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001922 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001923 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001924}
1925
Colin Crossc85750b2022-04-21 12:50:51 -07001926func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001927 return j.transitiveLibsHeaderJars
1928}
1929
Colin Crossc85750b2022-04-21 12:50:51 -07001930func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001931 return j.transitiveStaticLibsHeaderJars
1932}
1933
1934func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1935 directLibs := android.Paths{}
1936 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001937 transitiveLibs := []*android.DepSet[android.Path]{}
1938 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001939 ctx.VisitDirectDeps(func(module android.Module) {
1940 // don't add deps of the prebuilt version of the same library
1941 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1942 return
1943 }
1944
1945 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001946 tag := ctx.OtherModuleDependencyTag(module)
1947 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1948 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1949 directLibs = append(directLibs, dep.HeaderJars...)
1950 } else if tag == staticLibTag {
1951 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001952 } else {
1953 // Don't propagate transitive libs for other kinds of dependencies.
1954 return
1955 }
1956
1957 if dep.TransitiveLibsHeaderJars != nil {
1958 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1959 }
1960 if dep.TransitiveStaticLibsHeaderJars != nil {
1961 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001962 }
1963 })
1964 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1965 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1966}
1967
Jaewoong Jung26342642021-03-17 15:56:23 -07001968func (j *Module) HeaderJars() android.Paths {
1969 if j.headerJarFile == nil {
1970 return nil
1971 }
1972 return android.Paths{j.headerJarFile}
1973}
1974
1975func (j *Module) ImplementationJars() android.Paths {
1976 if j.implementationJarFile == nil {
1977 return nil
1978 }
1979 return android.Paths{j.implementationJarFile}
1980}
1981
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001982func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001983 return j.dexJarFile
1984}
1985
1986func (j *Module) DexJarInstallPath() android.Path {
1987 return j.installFile
1988}
1989
1990func (j *Module) ImplementationAndResourcesJars() android.Paths {
1991 if j.implementationAndResourcesJar == nil {
1992 return nil
1993 }
1994 return android.Paths{j.implementationAndResourcesJar}
1995}
1996
1997func (j *Module) AidlIncludeDirs() android.Paths {
1998 // exportAidlIncludeDirs is type android.Paths already
1999 return j.exportAidlIncludeDirs
2000}
2001
2002func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2003 return j.classLoaderContexts
2004}
2005
2006// Collect information for opening IDE project files in java/jdeps.go.
2007func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
2008 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2009 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2010 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2011 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
2012 if j.expandJarjarRules != nil {
2013 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
2014 }
Yikef6282022022-04-13 20:41:01 +08002015 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2016 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002017 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002018}
2019
2020func (j *Module) CompilerDeps() []string {
2021 jdeps := []string{}
2022 jdeps = append(jdeps, j.properties.Libs...)
2023 jdeps = append(jdeps, j.properties.Static_libs...)
2024 return jdeps
2025}
2026
2027func (j *Module) hasCode(ctx android.ModuleContext) bool {
2028 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2029 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2030}
2031
2032// Implements android.ApexModule
2033func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2034 return j.depIsInSameApex(ctx, dep)
2035}
2036
2037// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002038func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002039 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002040 minSdkVersion := j.MinSdkVersion(ctx)
2041 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002042 return fmt.Errorf("min_sdk_version is not specified")
2043 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002044 // If the module is compiling against core (via sdk_version), skip comparison check.
2045 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002046 return nil
2047 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002048 if minSdkVersion.GreaterThan(sdkVersion) {
2049 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002050 }
2051 return nil
2052}
2053
2054func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002055 if j.stem == "" {
2056 panic("Stem() called before stem property was set")
2057 }
2058 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002059}
2060
Jaewoong Jung26342642021-03-17 15:56:23 -07002061func (j *Module) JacocoReportClassesFile() android.Path {
2062 return j.jacocoReportClassesFile
2063}
2064
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002065func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2066 var fromDeps []*android.DepSet[android.Path]
2067 ctx.VisitDirectDeps(func(module android.Module) {
2068 tag := ctx.OtherModuleDependencyTag(module)
2069 if tag == staticLibTag {
2070 depInfo := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2071 if depInfo.TransitiveSrcFiles != nil {
2072 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2073 }
2074 }
2075 })
2076
2077 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2078}
2079
Jaewoong Jung26342642021-03-17 15:56:23 -07002080func (j *Module) IsInstallable() bool {
2081 return Bool(j.properties.Installable)
2082}
2083
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002084func (j *Module) collectTransitiveAconfigFiles(ctx android.ModuleContext) {
2085 // Aconfig files from this module
2086 mine := j.aconfigIntermediates
2087
2088 // Aconfig files from transitive dependencies
2089 fromDeps := []*android.DepSet[android.Path]{}
2090 ctx.VisitDirectDeps(func(module android.Module) {
2091 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2092 if dep.TransitiveAconfigFiles != nil {
2093 fromDeps = append(fromDeps, dep.TransitiveAconfigFiles)
2094 }
2095 })
2096
2097 // DepSet containing aconfig files myself and from dependencies
2098 j.transitiveAconfigFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2099}
2100
2101func (j *Module) AddAconfigIntermediate(path android.Path) {
2102 j.aconfigIntermediates = append(j.aconfigIntermediates, path)
2103}
2104
2105func (j *Module) getTransitiveAconfigFiles() *android.DepSet[android.Path] {
2106 if j.transitiveAconfigFiles == nil {
2107 panic(fmt.Errorf("java.Moduile: getTransitiveAconfigFiles called before collectTransitiveAconfigFiles module=%s", j.Name()))
2108 }
2109 return j.transitiveAconfigFiles
2110}
2111
Jaewoong Jung26342642021-03-17 15:56:23 -07002112type sdkLinkType int
2113
2114const (
2115 // TODO(jiyong) rename these for better readability. Make the allowed
2116 // and disallowed link types explicit
2117 // order is important here. See rank()
2118 javaCore sdkLinkType = iota
2119 javaSdk
2120 javaSystem
2121 javaModule
2122 javaSystemServer
2123 javaPlatform
2124)
2125
2126func (lt sdkLinkType) String() string {
2127 switch lt {
2128 case javaCore:
2129 return "core Java API"
2130 case javaSdk:
2131 return "Android API"
2132 case javaSystem:
2133 return "system API"
2134 case javaModule:
2135 return "module API"
2136 case javaSystemServer:
2137 return "system server API"
2138 case javaPlatform:
2139 return "private API"
2140 default:
2141 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2142 }
2143}
2144
2145// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2146// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2147// can't statically depend on modules that use Platform API.
2148func (lt sdkLinkType) rank() int {
2149 return int(lt)
2150}
2151
2152type moduleWithSdkDep interface {
2153 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002154 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002155}
2156
Jiyong Park92315372021-04-02 08:45:46 +09002157func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002158 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002159 case android.SdkCore.DefaultJavaLibraryName(),
2160 "legacy.core.platform.api.stubs",
2161 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002162 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002163 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002164 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002165 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002166 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002167 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002168 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002169 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002170 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002171 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002172 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002173 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002174 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002175 return javaSystem, true
2176 }
2177
2178 if stub, linkType := moduleStubLinkType(name); stub {
2179 return linkType, true
2180 }
2181
Jiyong Park92315372021-04-02 08:45:46 +09002182 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002183 switch ver.Kind {
2184 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002185 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002186 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002187 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002188 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002189 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002190 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002191 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002192 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002193 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002194 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002195 return javaPlatform, false
2196 }
2197
Jiyong Parkf1691d22021-03-29 20:11:58 +09002198 if !ver.Valid() {
2199 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002200 }
2201 return javaSdk, false
2202}
2203
2204// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2205// this module's. See the comment on rank() for details and an example.
2206func (j *Module) checkSdkLinkType(
2207 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2208 if ctx.Host() {
2209 return
2210 }
2211
Jiyong Park92315372021-04-02 08:45:46 +09002212 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002213 if stubs {
2214 return
2215 }
Jiyong Park92315372021-04-02 08:45:46 +09002216 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002217
2218 if myLinkType.rank() < depLinkType.rank() {
2219 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2220 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2221 "property of the source or target module so that target module is built "+
2222 "with the same or smaller API set when compared to the source.",
2223 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2224 }
2225}
2226
2227func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2228 var deps deps
2229
2230 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002231 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002232 if sdkDep.invalidVersion {
2233 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2234 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2235 } else if sdkDep.useFiles {
2236 // sdkDep.jar is actually equivalent to turbine header.jar.
2237 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002238 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002239 deps.aidlPreprocess = sdkDep.aidl
2240 } else {
2241 deps.aidlPreprocess = sdkDep.aidl
2242 }
2243 }
2244
Jiyong Park92315372021-04-02 08:45:46 +09002245 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002246
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002247 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002248 ctx.VisitDirectDeps(func(module android.Module) {
2249 otherName := ctx.OtherModuleName(module)
2250 tag := ctx.OtherModuleDependencyTag(module)
2251
2252 if IsJniDepTag(tag) {
2253 // Handled by AndroidApp.collectAppDeps
2254 return
2255 }
2256 if tag == certificateTag {
2257 // Handled by AndroidApp.collectAppDeps
2258 return
2259 }
2260
2261 if dep, ok := module.(SdkLibraryDependency); ok {
2262 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002263 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002264 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2265 deps.classpath = append(deps.classpath, depHeaderJars...)
2266 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002267 case staticLibTag:
2268 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2269 }
2270 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2271 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2272 if sdkLinkType != javaPlatform &&
2273 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2274 // dep is a sysprop implementation library, but this module is not linking against
2275 // the platform, so it gets the sysprop public stubs library instead. Replace
2276 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2277 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2278 dep = syspropDep.JavaInfo
2279 }
2280 switch tag {
2281 case bootClasspathTag:
2282 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002283 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002284 if _, ok := module.(*Plugin); ok {
2285 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2286 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002287 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002288 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002289 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2290 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2291 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2292 case java9LibTag:
2293 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2294 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002295 if _, ok := module.(*Plugin); ok {
2296 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2297 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002298 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2299 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2300 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2301 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2302 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2303 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2304 // Turbine doesn't run annotation processors, so any module that uses an
2305 // annotation processor that generates API is incompatible with the turbine
2306 // optimization.
2307 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2308 case pluginTag:
2309 if plugin, ok := module.(*Plugin); ok {
2310 if plugin.pluginProperties.Processor_class != nil {
2311 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2312 } else {
2313 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2314 }
2315 // Turbine doesn't run annotation processors, so any module that uses an
2316 // annotation processor that generates API is incompatible with the turbine
2317 // optimization.
2318 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2319 } else {
2320 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2321 }
2322 case errorpronePluginTag:
2323 if _, ok := module.(*Plugin); ok {
2324 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2325 } else {
2326 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2327 }
2328 case exportedPluginTag:
2329 if plugin, ok := module.(*Plugin); ok {
2330 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2331 if plugin.pluginProperties.Processor_class != nil {
2332 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2333 }
2334 // Turbine doesn't run annotation processors, so any module that uses an
2335 // annotation processor that generates API is incompatible with the turbine
2336 // optimization.
2337 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2338 } else {
2339 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2340 }
2341 case kotlinStdlibTag:
2342 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2343 case kotlinAnnotationsTag:
2344 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002345 case kotlinPluginTag:
2346 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002347 case syspropPublicStubDepTag:
2348 // This is a sysprop implementation library, forward the JavaInfoProvider from
2349 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2350 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2351 JavaInfo: dep,
2352 })
2353 }
2354 } else if dep, ok := module.(android.SourceFileProducer); ok {
2355 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002356 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002357 checkProducesJars(ctx, dep)
2358 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002359 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002360 case staticLibTag:
2361 checkProducesJars(ctx, dep)
2362 deps.classpath = append(deps.classpath, dep.Srcs()...)
2363 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2364 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2365 }
2366 } else {
2367 switch tag {
2368 case bootClasspathTag:
2369 // If a system modules dependency has been added to the bootclasspath
2370 // then add its libs to the bootclasspath.
2371 sm := module.(SystemModulesProvider)
2372 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2373
2374 case systemModulesTag:
2375 if deps.systemModules != nil {
2376 panic("Found two system module dependencies")
2377 }
2378 sm := module.(SystemModulesProvider)
2379 outputDir, outputDeps := sm.OutputDirAndDeps()
2380 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002381
2382 case instrumentationForTag:
2383 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 -07002384 }
2385 }
2386
2387 addCLCFromDep(ctx, module, j.classLoaderContexts)
2388 })
2389
2390 return deps
2391}
2392
2393func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2394 deps.processorPath = append(deps.processorPath, pluginJars...)
2395 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2396}
2397
2398// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2399// this interface.
2400type ProvidesUsesLib interface {
2401 ProvidesUsesLib() *string
2402}
2403
2404func (j *Module) ProvidesUsesLib() *string {
2405 return j.usesLibraryProperties.Provides_uses_lib
2406}
satayev1c564cc2021-05-25 19:50:30 +01002407
2408type ModuleWithStem interface {
2409 Stem() string
2410}
2411
2412var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002413
Chris Parsons637458d2023-09-19 20:09:00 +00002414func (j *Module) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Wei Libafb6d62021-12-10 03:14:59 -08002415 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002416 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002417 if lib, ok := ctx.Module().(*Library); ok {
2418 javaLibraryBp2Build(ctx, lib)
2419 }
2420 case "java_binary_host":
2421 if binary, ok := ctx.Module().(*Binary); ok {
2422 javaBinaryHostBp2Build(ctx, binary)
2423 }
Zi Wang65b36722023-05-23 15:18:33 -07002424 case "java_test_host":
2425 if testHost, ok := ctx.Module().(*TestHost); ok {
2426 javaTestHostBp2Build(ctx, testHost)
2427 }
Chris Parsons39a16972023-06-08 14:28:51 +00002428 default:
2429 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002430 }
Wei Libafb6d62021-12-10 03:14:59 -08002431}