blob: 03198b5506a34887f983bab2ec58750eaef8c770 [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
500 // Collect the module directory for IDE info in java/jdeps.go.
501 modulePaths []string
502
503 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900504
505 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000506 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000507 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400508
509 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000510
511 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000512
513 // output file name based on Stem property.
514 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
515 // or the module should override Stem().
516 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700517
518 // Aconfig "cache files" that went directly into this module. Transitive ones are
519 // tracked via JavaInfo.TransitiveAconfigFiles
520 // TODO: Extract to something standalone to propagate tags via GeneratedJavaLibraryModule
521 aconfigIntermediates android.Paths
522
523 // Aconfig files for all transitive deps. Also exposed via JavaInfo
524 transitiveAconfigFiles *android.DepSet[android.Path]
Jaewoong Jung26342642021-03-17 15:56:23 -0700525}
526
Jiyong Park92315372021-04-02 08:45:46 +0900527func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
528 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900529 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700530 return nil
531 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900532 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000533 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700534 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
535 } else {
536 // Treat stable core platform as stable.
537 return nil
538 }
539 } else {
540 return fmt.Errorf("non stable SDK %v", sdkVersion)
541 }
542}
543
544// checkSdkVersions enforces restrictions around SDK dependencies.
545func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
546 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900547 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900548 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700549 ctx.PropertyErrorf("sdk_version",
550 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
551 }
552 }
553 }
554
555 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
556 // See rank() for details.
557 ctx.VisitDirectDeps(func(module android.Module) {
558 tag := ctx.OtherModuleDependencyTag(module)
559 switch module.(type) {
560 // TODO(satayev): cover other types as well, e.g. imports
561 case *Library, *AndroidLibrary:
562 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400563 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700564 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
565 }
566 }
567 })
568}
569
570func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900571 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700572 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900573 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700574 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000575 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 -0700576 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000577 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 -0700578 }
579
580 }
581}
582
Mark Whitea15790a2023-08-22 21:28:11 +0000583func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
584 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400585 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000586 installable := proptools.Bool(j.properties.Installable)
587
588 if headersOnly && installable {
589 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.")
590 }
591 }
592}
593
Jaewoong Jung26342642021-03-17 15:56:23 -0700594func (j *Module) addHostProperties() {
595 j.AddProperties(
596 &j.properties,
597 &j.protoProperties,
598 &j.usesLibraryProperties,
599 )
600}
601
602func (j *Module) addHostAndDeviceProperties() {
603 j.addHostProperties()
604 j.AddProperties(
605 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900606 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700607 &j.dexer.dexProperties,
608 &j.dexpreoptProperties,
609 &j.linter.properties,
610 )
611}
612
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000613// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
614// makes it available through the hiddenAPIPropertyInfoProvider.
615func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
616 hiddenAPIInfo := newHiddenAPIPropertyInfo()
617
618 // Populate with flag file paths from the properties.
619 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
620
621 // Populate with package rules from the properties.
622 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
623
624 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
625}
626
Jaewoong Jung26342642021-03-17 15:56:23 -0700627func (j *Module) OutputFiles(tag string) (android.Paths, error) {
628 switch tag {
629 case "":
630 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
631 case android.DefaultDistTag:
632 return android.Paths{j.outputFile}, nil
633 case ".jar":
634 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700635 case ".hjar":
636 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700637 case ".proguard_map":
638 if j.dexer.proguardDictionary.Valid() {
639 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
640 }
641 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700642 case ".generated_srcjars":
643 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000644 case ".lint":
645 if j.linter.outputs.xml != nil {
646 return android.Paths{j.linter.outputs.xml}, nil
647 }
648 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700649 default:
650 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
651 }
652}
653
654var _ android.OutputFileProducer = (*Module)(nil)
655
656func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
657 initJavaModule(module, hod, false)
658}
659
660func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
661 initJavaModule(module, hod, true)
662}
663
664func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
665 multilib := android.MultilibCommon
666 if multiTargets {
667 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
668 } else {
669 android.InitAndroidArchModule(module, hod, multilib)
670 }
671 android.InitDefaultableModule(module)
672}
673
674func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
675 return j.properties.Instrument &&
676 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
677 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
678}
679
680func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000681 return j.properties.Supports_static_instrumentation &&
682 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700683 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
684 ctx.Config().UnbundledBuild())
685}
686
687func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
688 // Force enable the instrumentation for java code that is built for APEXes ...
689 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
690 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
691 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
692 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
693 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
694 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
695 return true
696 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
697 return true
698 }
699 }
700 return false
701}
702
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400703func (j *Module) setInstrument(value bool) {
704 j.properties.Instrument = value
705}
706
Jiyong Park92315372021-04-02 08:45:46 +0900707func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
708 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700709}
710
Jiyong Parkf1691d22021-03-29 20:11:58 +0900711func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700712 return proptools.String(j.deviceProperties.System_modules)
713}
714
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000715func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700716 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000717 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700718 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000719 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700720}
721
Yu Liuf2b94012023-09-19 15:09:10 -0700722func (j *Module) GetDeviceProperties() *DeviceProperties {
723 return &j.deviceProperties
724}
725
Spandan Dasa26eda72023-03-02 00:56:06 +0000726func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
727 if j.deviceProperties.Max_sdk_version != nil {
728 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
729 }
730 // Default is PrivateApiLevel
731 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000732}
733
Spandan Dasa26eda72023-03-02 00:56:06 +0000734func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
735 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
736 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
737 }
738 // Default is PrivateApiLevel
739 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000740}
741
Jiyong Parkf1691d22021-03-29 20:11:58 +0900742func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000743 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900744}
745
Spandan Dasca70fc42023-03-01 23:38:49 +0000746func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900747 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000748 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900749 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000750 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700751}
752
753func (j *Module) AvailableFor(what string) bool {
754 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
755 // Exception: for hostdex: true libraries, the platform variant is created
756 // even if it's not marked as available to platform. In that case, the platform
757 // variant is used only for the hostdex and not installed to the device.
758 return true
759 }
760 return j.ApexModuleBase.AvailableFor(what)
761}
762
763func (j *Module) deps(ctx android.BottomUpMutatorContext) {
764 if ctx.Device() {
765 j.linter.deps(ctx)
766
Jiyong Parkf1691d22021-03-29 20:11:58 +0900767 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700768
769 if j.deviceProperties.SyspropPublicStub != "" {
770 // This is a sysprop implementation library that has a corresponding sysprop public
771 // stubs library, and a dependency on it so that dependencies on the implementation can
772 // be forwarded to the public stubs library when necessary.
773 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
774 }
775 }
776
777 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000778
779 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700780 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
781
782 // Add dependency on libraries that provide additional hidden api annotations.
783 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
784
785 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
786 // Require java_sdk_library at inter-partition java dependency to ensure stable
787 // interface between partitions. If inter-partition java_library dependency is detected,
788 // raise build error because java_library doesn't have a stable interface.
789 //
790 // Inputs:
791 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
792 // if true, enable enforcement
793 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
794 // exception list of java_library names to allow inter-partition dependency
795 for idx := range j.properties.Libs {
796 if libDeps[idx] == nil {
797 continue
798 }
799
800 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
801 // java_sdk_library is always allowed at inter-partition dependency.
802 // So, skip check.
803 if _, ok := javaDep.(*SdkLibrary); ok {
804 continue
805 }
806
807 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
808 }
809 }
810 }
811
812 // For library dependencies that are component libraries (like stubs), add the implementation
813 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
814 for _, dep := range libDeps {
815 if dep != nil {
816 if component, ok := dep.(SdkLibraryComponentDependency); ok {
817 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100818 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100819 tag := usesLibReqTag
820 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
821 tag = usesLibOptTag
822 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100823 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700824 }
825 }
826 }
827 }
828
829 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
830 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
831 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
832
833 android.ProtoDeps(ctx, &j.protoProperties)
834 if j.hasSrcExt(".proto") {
835 protoDeps(ctx, &j.protoProperties)
836 }
837
838 if j.hasSrcExt(".kt") {
839 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
840 // Kotlin files
841 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
842 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700843 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700844 }
845
846 // Framework libraries need special handling in static coverage builds: they should not have
847 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
848 // the same jacoco classes coming from different bootclasspath jars.
849 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
850 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
851 j.properties.Instrument = true
852 }
853 } else if j.shouldInstrumentStatic(ctx) {
854 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
855 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700856
857 if j.useCompose() {
858 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
859 "androidx.compose.compiler_compiler-hosted")
860 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700861}
862
863func hasSrcExt(srcs []string, ext string) bool {
864 for _, src := range srcs {
865 if filepath.Ext(src) == ext {
866 return true
867 }
868 }
869
870 return false
871}
872
873func (j *Module) hasSrcExt(ext string) bool {
874 return hasSrcExt(j.properties.Srcs, ext)
875}
876
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100877func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
878 var flags string
879
880 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
881 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
882 flags = "-Wmissing-permission-annotation -Werror"
883 }
884 }
885 return flags
886}
887
Jaewoong Jung26342642021-03-17 15:56:23 -0700888func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000889 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700890
891 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
892 aidlIncludes = append(aidlIncludes,
893 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
894 aidlIncludes = append(aidlIncludes,
895 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
896
897 var flags []string
898 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000899 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700900
901 flags = append(flags, j.deviceProperties.Aidl.Flags...)
902
903 if aidlPreprocess.Valid() {
904 flags = append(flags, "-p"+aidlPreprocess.String())
905 deps = append(deps, aidlPreprocess.Path())
906 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000907 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700908 }
909
910 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000911 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 }
913
914 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000915 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700916 }
917
Sam Delmerico2351eac2022-05-24 17:10:02 +0000918 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700919 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000920 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700921 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000922 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
923 // add flags for dirs containing AIDL srcs that haven't been specified yet
924 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700925
Zim8774ae12022-08-17 11:46:34 +0100926 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000927 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100928 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700929 flags = append(flags, "-t")
930 }
931
932 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
933 flags = append(flags, "--transaction_names")
934 }
935
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100936 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
937 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
938 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
939 }
940
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000941 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900942 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
943
Jaewoong Jung26342642021-03-17 15:56:23 -0700944 return strings.Join(flags, " "), deps
945}
946
947func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
948
949 var flags javaBuilderFlags
950
951 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900952 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700953
Cole Faust2b1536e2021-06-18 12:25:54 -0700954 epEnabled := j.properties.Errorprone.Enabled
955 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100956 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700957 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
958 }
959
960 errorProneFlags := []string{
961 "-Xplugin:ErrorProne",
962 "${config.ErrorProneChecks}",
963 }
964 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
965
Colin Cross8bf6cad2022-02-28 13:07:03 -0800966 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700967 "'" + strings.Join(errorProneFlags, " ") + "'"
968 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
969 }
970
971 // classpath
972 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
973 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700974 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700975 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
976 flags.processorPath = append(flags.processorPath, deps.processorPath...)
977 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
978
979 flags.processors = append(flags.processors, deps.processorClasses...)
980 flags.processors = android.FirstUniqueStrings(flags.processors)
981
982 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900983 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700984 // Give host-side tools a version of OpenJDK's standard libraries
985 // close to what they're targeting. As of Dec 2017, AOSP is only
986 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
987 //
988 // When building with OpenJDK 8, the following should have no
989 // effect since those jars would be available by default.
990 //
991 // When building with OpenJDK 9 but targeting a version < 1.8,
992 // putting them on the bootclasspath means that:
993 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
994 // b) references to existing APIs are not reinterpreted in an
995 // OpenJDK 9-specific way, eg. calls to subclasses of
996 // java.nio.Buffer as in http://b/70862583
997 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
998 flags.bootClasspath = append(flags.bootClasspath,
999 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
1000 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
1001 if Bool(j.properties.Use_tools_jar) {
1002 flags.bootClasspath = append(flags.bootClasspath,
1003 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1004 }
1005 }
1006
1007 // systemModules
1008 flags.systemModules = deps.systemModules
1009
Jaewoong Jung26342642021-03-17 15:56:23 -07001010 return flags
1011}
1012
1013func (j *Module) collectJavacFlags(
1014 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1015 // javac flags.
1016 javacFlags := j.properties.Javacflags
1017
1018 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
1019 // For non-host binaries, override the -g flag passed globally to remove
1020 // local variable debug info to reduce disk and memory usage.
1021 javacFlags = append(javacFlags, "-g:source,lines")
1022 }
1023 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1024
1025 if flags.javaVersion.usesJavaModules() {
1026 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
1027
1028 if j.properties.Patch_module != nil {
1029 // Manually specify build directory in case it is not under the repo root.
1030 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1031 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001032 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001033
1034 // b/150878007
1035 //
1036 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1037 // execution root for --patch-module. If this javac command line is
1038 // invoked within Bazel's execution root working directory, the top
1039 // level directories (e.g. libcore/, tools/, frameworks/) are all
1040 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1041 // --patch-module to fail source file lookups when invoked in the
1042 // execution root.
1043 //
1044 // Short of patching javac or enumerating *all* directories as possible
1045 // input dirs, manually add the top level dir of the source files to be
1046 // compiled.
1047 topLevelDirs := map[string]bool{}
1048 for _, srcFilePath := range srcFiles {
1049 srcFileParts := strings.Split(srcFilePath.String(), "/")
1050 // Ignore source files that are already in the top level directory
1051 // as well as generated files in the out directory. The out
1052 // directory may be an absolute path, which means srcFileParts[0] is the
1053 // empty string, so check that as well. Note that "out" in Bazel's execution
1054 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1055 // anyway, so it's fine to not apply this workaround for generated
1056 // source files.
1057 if len(srcFileParts) > 1 &&
1058 srcFileParts[0] != "" &&
1059 srcFileParts[0] != "out" {
1060 topLevelDirs[srcFileParts[0]] = true
1061 }
1062 }
Cole Faust18994c72023-02-28 16:02:16 -08001063 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001064
1065 classPath := flags.classpath.FormJavaClassPath("")
1066 if classPath != "" {
1067 patchPaths = append(patchPaths, classPath)
1068 }
1069 javacFlags = append(
1070 javacFlags,
1071 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1072 }
1073 }
1074
1075 if len(javacFlags) > 0 {
1076 // optimization.
1077 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1078 flags.javacFlags = "$javacFlags"
1079 }
1080
1081 return flags
1082}
1083
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001084func (j *Module) AddJSONData(d *map[string]interface{}) {
1085 (&j.ModuleBase).AddJSONData(d)
1086 (*d)["Java"] = map[string]interface{}{
1087 "SourceExtensions": j.sourceExtensions,
1088 }
1089
1090}
1091
usta0391ca42023-09-19 15:51:59 -04001092func (j *Module) addGeneratedSrcJars(path android.Path) {
1093 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001094}
1095
Colin Cross4eae06d2023-06-20 22:40:02 -07001096func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001097 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1098
1099 deps := j.collectDeps(ctx)
1100 flags := j.collectBuilderFlags(ctx, deps)
1101
1102 if flags.javaVersion.usesJavaModules() {
1103 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1104 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001105
Jaewoong Jung26342642021-03-17 15:56:23 -07001106 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001107 j.sourceExtensions = []string{}
1108 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1109 if hasSrcExt(srcFiles.Strings(), ext) {
1110 j.sourceExtensions = append(j.sourceExtensions, ext)
1111 }
1112 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001113 if hasSrcExt(srcFiles.Strings(), ".proto") {
1114 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1115 }
1116
1117 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1118 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1119 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1120 }
1121
Sam Delmerico2351eac2022-05-24 17:10:02 +00001122 aidlSrcs := srcFiles.FilterByExt(".aidl")
1123 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1124
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001125 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 srcFiles = j.genSources(ctx, srcFiles, flags)
1127
1128 // Collect javac flags only after computing the full set of srcFiles to
1129 // ensure that the --patch-module lookup paths are complete.
1130 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1131
1132 srcJars := srcFiles.FilterByExt(".srcjar")
1133 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001134 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001135 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001136 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001137
1138 if j.properties.Jarjar_rules != nil {
1139 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1140 }
1141
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001142 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001143
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001144 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001145 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001146 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001147 if _, found := set[v.String()]; !found {
1148 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001149 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001150 }
1151 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001152 var uniqueKtFiles android.Paths
1153 for _, v := range srcFiles.FilterByExt(".kt") {
1154 if _, found := set[v.String()]; !found {
1155 set[v.String()] = true
1156 uniqueKtFiles = append(uniqueKtFiles, v)
1157 }
1158 }
1159
1160 var uniqueSrcFiles android.Paths
1161 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1162 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1163 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001164
Colin Crossb5db4012022-03-28 17:12:39 -07001165 // We don't currently run annotation processors in turbine, which means we can't use turbine
1166 // generated header jars when an annotation processor that generates API is enabled. One
1167 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1168 // is used to run all of the annotation processors.
1169 disableTurbine := deps.disableTurbine
1170
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001171 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001172 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1173
1174 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001175 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001176
Colin Cross4eae06d2023-06-20 22:40:02 -07001177 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1178 // any dependencies so that it can override any non-final R classes from dependencies with the
1179 // final R classes from the app.
1180 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1181
Mark Whitea15790a2023-08-22 21:28:11 +00001182 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001183 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001184 if srcFiles.HasExt(".kt") {
1185 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1186 }
1187 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1188 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1189 }
1190
1191 _, j.headerJarFile =
1192 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1193 extraCombinedJars)
1194 if ctx.Failed() {
1195 return
1196 }
1197
1198 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1199 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1200 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1201 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1202 AidlIncludeDirs: j.exportAidlIncludeDirs,
1203 ExportedPlugins: j.exportedPluginJars,
1204 ExportedPluginClasses: j.exportedPluginClasses,
1205 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1206 })
1207
1208 j.outputFile = j.headerJarFile
1209 return
1210 }
1211
Jaewoong Jung26342642021-03-17 15:56:23 -07001212 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001213 // When using kotlin sources turbine is used to generate annotation processor sources,
1214 // including for annotation processors that generate API, so we can use turbine for
1215 // java sources too.
1216 disableTurbine = false
1217
Jaewoong Jung26342642021-03-17 15:56:23 -07001218 // user defined kotlin flags.
1219 kotlincFlags := j.properties.Kotlincflags
1220 CheckKotlincFlags(ctx, kotlincFlags)
1221
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001222 // Workaround for KT-46512
1223 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001224
1225 // If there are kotlin files, compile them first but pass all the kotlin and java files
1226 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1227 // won't emit any classes for them.
1228 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1229 if ctx.Device() {
1230 kotlincFlags = append(kotlincFlags, "-no-jdk")
1231 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001232
1233 for _, plugin := range deps.kotlinPlugins {
1234 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1235 }
1236 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1237
Jaewoong Jung26342642021-03-17 15:56:23 -07001238 if len(kotlincFlags) > 0 {
1239 // optimization.
1240 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1241 flags.kotlincFlags += "$kotlincFlags"
1242 }
1243
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001244 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001245 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1246
1247 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1248 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1249
1250 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1251 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1252
Isaac Chioua23d9942022-04-06 06:14:38 +00001253 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001254 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001255 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1256 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001257 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001258 srcJars = append(srcJars, kaptSrcJar)
1259 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001260 // Disable annotation processing in javac, it's already been handled by kapt
1261 flags.processorPath = nil
1262 flags.processors = nil
1263 }
1264
1265 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001266 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001267 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001268 if ctx.Failed() {
1269 return
1270 }
1271
Isaac Chioua23d9942022-04-06 06:14:38 +00001272 // Make javac rule depend on the kotlinc rule
1273 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1274
Jaewoong Jung26342642021-03-17 15:56:23 -07001275 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001276 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1277
Jaewoong Jung26342642021-03-17 15:56:23 -07001278 // Jar kotlin classes into the final jar after javac
1279 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1280 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001281 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001282 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001283 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001284 } else {
1285 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001286 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001287 }
1288 }
1289
1290 jars := append(android.Paths(nil), kotlinJars...)
1291
Jaewoong Jung26342642021-03-17 15:56:23 -07001292 j.compiledSrcJars = srcJars
1293
1294 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001295 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001296 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001297 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1298 enableSharding = true
1299 // Formerly, there was a check here that prevented annotation processors
1300 // from being used when sharding was enabled, as some annotation processors
1301 // do not function correctly in sharded environments. It was removed to
1302 // allow for the use of annotation processors that do function correctly
1303 // with sharding enabled. See: b/77284273.
1304 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001305 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001306 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001307 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001308 if ctx.Failed() {
1309 return
1310 }
1311 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001312 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001313 hasErrorproneableFiles := false
1314 for _, ext := range j.sourceExtensions {
1315 if ext != ".proto" && ext != ".aidl" {
1316 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1317 // compile, and it's not useful to have warnings on these generated sources.
1318 hasErrorproneableFiles = true
1319 break
1320 }
1321 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001322 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001323 if Bool(j.properties.Errorprone.Enabled) {
1324 // If error-prone is enabled, enable errorprone flags on the regular
1325 // build.
1326 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001327 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001328 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1329 // a new jar file just for compiling with the errorprone compiler to.
1330 // This is because we don't want to cause the java files to get completely
1331 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1332 // We also don't want to run this if errorprone is enabled by default for
1333 // this module, or else we could have duplicated errorprone messages.
1334 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001335 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001336 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001337
Vadim Spivak3c496f02023-06-08 06:14:59 +00001338 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001339 "errorprone", "errorprone")
1340
Jaewoong Jung26342642021-03-17 15:56:23 -07001341 extraJarDeps = append(extraJarDeps, errorprone)
1342 }
1343
1344 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001345 if headerJarFileWithoutDepsOrJarjar != nil {
1346 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1347 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001348 shardSize := int(*(j.properties.Javac_shard_size))
1349 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001350 if len(uniqueJavaFiles) > 0 {
1351 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001352 for idx, shardSrc := range shardSrcs {
1353 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1354 nil, flags, extraJarDeps)
1355 jars = append(jars, classes)
1356 }
1357 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001358 // Assume approximately 5 sources per srcjar.
1359 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1360 // 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 -07001361 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001362 startIdx := len(shardSrcs)
1363 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1364 for idx, shardSrcJars := range shardSrcJarsList {
1365 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1366 nil, shardSrcJars, flags, extraJarDeps)
1367 jars = append(jars, classes)
1368 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001369 }
1370 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001371 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001372 jars = append(jars, classes)
1373 }
1374 if ctx.Failed() {
1375 return
1376 }
1377 }
1378
1379 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1380
1381 var includeSrcJar android.WritablePath
1382 if Bool(j.properties.Include_srcs) {
1383 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1384 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1385 }
1386
1387 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1388 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1389 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1390 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1391
1392 var resArgs []string
1393 var resDeps android.Paths
1394
1395 resArgs = append(resArgs, dirArgs...)
1396 resDeps = append(resDeps, dirDeps...)
1397
1398 resArgs = append(resArgs, fileArgs...)
1399 resDeps = append(resDeps, fileDeps...)
1400
1401 resArgs = append(resArgs, extraArgs...)
1402 resDeps = append(resDeps, extraDeps...)
1403
1404 if len(resArgs) > 0 {
1405 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1406 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1407 j.resourceJar = resourceJar
1408 if ctx.Failed() {
1409 return
1410 }
1411 }
1412
1413 var resourceJars android.Paths
1414 if j.resourceJar != nil {
1415 resourceJars = append(resourceJars, j.resourceJar)
1416 }
1417 if Bool(j.properties.Include_srcs) {
1418 resourceJars = append(resourceJars, includeSrcJar)
1419 }
1420 resourceJars = append(resourceJars, deps.staticResourceJars...)
1421
1422 if len(resourceJars) > 1 {
1423 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1424 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1425 false, nil, nil)
1426 j.resourceJar = combinedJar
1427 } else if len(resourceJars) == 1 {
1428 j.resourceJar = resourceJars[0]
1429 }
1430
1431 if len(deps.staticJars) > 0 {
1432 jars = append(jars, deps.staticJars...)
1433 }
1434
1435 manifest := j.overrideManifest
1436 if !manifest.Valid() && j.properties.Manifest != nil {
1437 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1438 }
1439
1440 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1441 if len(services) > 0 {
1442 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1443 var zipargs []string
1444 for _, file := range services {
1445 serviceFile := file.String()
1446 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1447 }
1448 rule := zip
1449 args := map[string]string{
1450 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1451 }
1452 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1453 rule = zipRE
1454 args["implicits"] = strings.Join(services.Strings(), ",")
1455 }
1456 ctx.Build(pctx, android.BuildParams{
1457 Rule: rule,
1458 Output: servicesJar,
1459 Implicits: services,
1460 Args: args,
1461 })
1462 jars = append(jars, servicesJar)
1463 }
1464
Colin Cross4eae06d2023-06-20 22:40:02 -07001465 jars = append(android.CopyOf(extraCombinedJars), jars...)
1466
Jaewoong Jung26342642021-03-17 15:56:23 -07001467 // Combine the classes built from sources, any manifests, and any static libraries into
1468 // classes.jar. If there is only one input jar this step will be skipped.
1469 var outputFile android.OutputPath
1470
1471 if len(jars) == 1 && !manifest.Valid() {
1472 // Optimization: skip the combine step as there is nothing to do
1473 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1474 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1475 // any if len(jars) == 1.
1476
Jihoon Kang1147b312023-06-08 23:25:57 +00001477 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1478 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1479 // either with .from-source or .from-text suffix.
1480 // outputFile should be agnostic to the build configuration,
1481 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1482 // to the copy rules.
1483 stub, _ := moduleStubLinkType(ctx.ModuleName())
1484
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 // Transform the single path to the jar into an OutputPath as that is required by the following
1486 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001487 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001488 // The path contains an embedded OutputPath so reuse that.
1489 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001490 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001491 // The path is an OutputPath so reuse it directly.
1492 outputFile = outputPath
1493 } else {
1494 // The file is not in the out directory so create an OutputPath into which it can be copied
1495 // and which the following code can use to refer to it.
1496 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1497 ctx.Build(pctx, android.BuildParams{
1498 Rule: android.Cp,
1499 Input: jars[0],
1500 Output: combinedJar,
1501 })
1502 outputFile = combinedJar.OutputPath
1503 }
1504 } else {
1505 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1506 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1507 false, nil, nil)
1508 outputFile = combinedJar.OutputPath
1509 }
1510
1511 // jarjar implementation jar if necessary
1512 if j.expandJarjarRules != nil {
1513 // Transform classes.jar into classes-jarjar.jar
1514 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1515 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1516 outputFile = jarjarFile
1517
1518 // jarjar resource jar if necessary
1519 if j.resourceJar != nil {
1520 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1521 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1522 j.resourceJar = resourceJarJarFile
1523 }
1524
1525 if ctx.Failed() {
1526 return
1527 }
1528 }
1529
1530 // Check package restrictions if necessary.
1531 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001532 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001533 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001534
1535 // Create a rule to copy the output jar to another path and add a validate dependency that
1536 // will check that the jar only contains the permitted packages. The new location will become
1537 // the output file of this module.
1538 inputFile := outputFile
1539 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1540 ctx.Build(pctx, android.BuildParams{
1541 Rule: android.Cp,
1542 Input: inputFile,
1543 Output: outputFile,
1544 // Make sure that any dependency on the output file will cause ninja to run the package check
1545 // rule.
1546 Validation: pkgckFile,
1547 })
1548
1549 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001550 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001551
1552 if ctx.Failed() {
1553 return
1554 }
1555 }
1556
1557 j.implementationJarFile = outputFile
1558 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001559 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1560 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1561 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1562 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1563 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1564 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1565 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001566 }
1567
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001568 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1569 specs := j.jacocoModuleToZipCommand(ctx)
1570 if ctx.Failed() {
1571 return
1572 }
1573
Jaewoong Jung26342642021-03-17 15:56:23 -07001574 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001575 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001576 }
1577
1578 // merge implementation jar with resources if necessary
1579 implementationAndResourcesJar := outputFile
1580 if j.resourceJar != nil {
1581 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1582 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1583 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1584 false, nil, nil)
1585 implementationAndResourcesJar = combinedJar
1586 }
1587
1588 j.implementationAndResourcesJar = implementationAndResourcesJar
1589
1590 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001591 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001592 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1593 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001594 if compileDex == nil {
1595 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001596 }
1597 if j.deviceProperties.Hostdex == nil {
1598 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1599 }
1600 }
1601
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001602 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 if j.hasCode(ctx) {
1604 if j.shouldInstrumentStatic(ctx) {
1605 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1606 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1607 }
1608 // Dex compilation
1609 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001610 params := &compileDexParams{
1611 flags: flags,
1612 sdkVersion: j.SdkVersion(ctx),
1613 minSdkVersion: j.MinSdkVersion(ctx),
1614 classesJar: implementationAndResourcesJar,
1615 jarName: jarName,
1616 }
1617 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001618 if ctx.Failed() {
1619 return
1620 }
1621
Jaewoong Jung26342642021-03-17 15:56:23 -07001622 // merge dex jar with resources if necessary
1623 if j.resourceJar != nil {
1624 jars := android.Paths{dexOutputFile, j.resourceJar}
1625 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1626 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1627 false, nil, nil)
1628 if *j.dexProperties.Uncompress_dex {
1629 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001630 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001631 dexOutputFile = combinedAlignedJar
1632 } else {
1633 dexOutputFile = combinedJar
1634 }
1635 }
1636
Paul Duffin4de94502021-05-16 05:21:16 +01001637 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001638
1639 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001640
1641 // Encode hidden API flags in dex file, if needed.
1642 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1643
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001644 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001645
1646 // Dexpreopting
1647 j.dexpreopt(ctx, dexOutputFile)
1648
1649 outputFile = dexOutputFile
1650 } else {
1651 // There is no code to compile into a dex jar, make sure the resources are propagated
1652 // to the APK if this is an app.
1653 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001654 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001655 }
1656
1657 if ctx.Failed() {
1658 return
1659 }
1660 } else {
1661 outputFile = implementationAndResourcesJar
1662 }
1663
1664 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001665 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1666 if !apiLevel.IsPreview() {
1667 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001668 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001669 // When running metalava, we pass --version-codename. When that value
1670 // is not REL, metalava will add 1 to the --current-version argument.
1671 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1672 // branch) and the codename is REL, except potentially on the most
1673 // recent non-master branch. On that branch, it goes through two other
1674 // phases before it gets to the phase previously described:
1675 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1676 // is not rel. This happens for most of the internal branch's life
1677 // while the branch has been cut but is still under active development.
1678 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1679 // REL. This happens briefly during the release process. During this
1680 // state the code to add --current-version is commented out, and then
1681 // that commenting out is reverted after the codename is set to REL.
1682 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1683 // prior version and the codename is always non-REL.
1684 //
1685 // We need to add one here to match metalava adding 1. Technically
1686 // this means that in the state described in the second bullet point
1687 // above, this number is 1 higher than it should be.
1688 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001689 }
1690 }
1691
1692 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001693 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1694 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001695 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1696 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001697 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001698 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001699 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001700 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001701 j.linter.javaLanguageLevel = flags.javaVersion.String()
1702 j.linter.kotlinLanguageLevel = "1.3"
1703 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1704 j.linter.buildModuleReportZip = true
1705 }
1706 j.linter.lint(ctx)
1707 }
1708
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001709 j.collectTransitiveSrcFiles(ctx, srcFiles)
1710
Jaewoong Jung26342642021-03-17 15:56:23 -07001711 ctx.CheckbuildFile(outputFile)
1712
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001713 j.collectTransitiveAconfigFiles(ctx)
1714
Jaewoong Jung26342642021-03-17 15:56:23 -07001715 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1716 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001717 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1718 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001719 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1720 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1721 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1722 AidlIncludeDirs: j.exportAidlIncludeDirs,
1723 SrcJarArgs: j.srcJarArgs,
1724 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001725 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001726 ExportedPlugins: j.exportedPluginJars,
1727 ExportedPluginClasses: j.exportedPluginClasses,
1728 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1729 JacocoReportClassesFile: j.jacocoReportClassesFile,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001730 TransitiveAconfigFiles: j.transitiveAconfigFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001731 })
1732
1733 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1734 j.outputFile = outputFile.WithoutRel()
1735}
1736
Colin Crossa1ff7c62021-09-17 14:11:52 -07001737func (j *Module) useCompose() bool {
1738 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1739}
1740
Sam Delmerico95d70942023-08-02 18:00:35 -04001741func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1742 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1743 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1744
1745 ctx.VisitDirectDeps(func(m android.Module) {
1746 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1747 depTag := ctx.OtherModuleDependencyTag(m)
1748
1749 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1750 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1751 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1752 }
1753
1754 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1755 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1756 }
1757 })
1758
1759 directUnconditionalExportedFlags := android.Paths{}
1760 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1761 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1762 if exportUnconditionally {
1763 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1764 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1765 directUnconditionalExportedFlags = proguardFlagsForThisModule
1766 }
1767
1768 return ProguardSpecInfo{
1769 Export_proguard_flags_files: exportUnconditionally,
1770 ProguardFlagsFiles: android.NewDepSet[android.Path](
1771 android.POSTORDER,
1772 proguardFlagsForThisModule,
1773 transitiveProguardFlags,
1774 ),
1775 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1776 android.POSTORDER,
1777 directUnconditionalExportedFlags,
1778 transitiveUnconditionalExportedFlags,
1779 ),
1780 }
1781
1782}
1783
Cole Faust75fffb12021-06-13 15:23:16 -07001784// Returns a copy of the supplied flags, but with all the errorprone-related
1785// fields copied to the regular build's fields.
1786func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1787 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1788
1789 if len(flags.errorProneExtraJavacFlags) > 0 {
1790 if len(flags.javacFlags) > 0 {
1791 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1792 } else {
1793 flags.javacFlags = flags.errorProneExtraJavacFlags
1794 }
1795 }
1796 return flags
1797}
1798
Jaewoong Jung26342642021-03-17 15:56:23 -07001799func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1800 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1801
1802 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001803 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001804 if idx >= 0 {
1805 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001806 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001807 jarName += strconv.Itoa(idx)
1808 }
1809
1810 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001811 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001812
1813 if ctx.Config().EmitXrefRules() {
1814 extractionFile := android.PathForModuleOut(ctx, kzipName)
1815 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1816 j.kytheFiles = append(j.kytheFiles, extractionFile)
1817 }
1818
Vadim Spivak3c496f02023-06-08 06:14:59 +00001819 if len(flags.processorPath) > 0 {
1820 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1821 }
1822
Jaewoong Jung26342642021-03-17 15:56:23 -07001823 return classes
1824}
1825
1826// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1827// since some of these flags may be used internally.
1828func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1829 for _, flag := range flags {
1830 flag = strings.TrimSpace(flag)
1831
1832 if !strings.HasPrefix(flag, "-") {
1833 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1834 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1835 ctx.PropertyErrorf("kotlincflags",
1836 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1837 } else if inList(flag, config.KotlincIllegalFlags) {
1838 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1839 } else if flag == "-include-runtime" {
1840 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1841 } else {
1842 args := strings.Split(flag, " ")
1843 if args[0] == "-kotlin-home" {
1844 ctx.PropertyErrorf("kotlincflags",
1845 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1846 }
1847 }
1848 }
1849}
1850
1851func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1852 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001853 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001854
1855 var jars android.Paths
1856 if len(srcFiles) > 0 || len(srcJars) > 0 {
1857 // Compile java sources into turbine.jar.
1858 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1859 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1860 if ctx.Failed() {
1861 return nil, nil
1862 }
1863 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001864 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001865 }
1866
1867 jars = append(jars, extraJars...)
1868
1869 // Combine any static header libraries into classes-header.jar. If there is only
1870 // one input jar this step will be skipped.
1871 jars = append(jars, deps.staticHeaderJars...)
1872
1873 // we cannot skip the combine step for now if there is only one jar
1874 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1875 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1876 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1877 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001878 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001879
1880 if j.expandJarjarRules != nil {
1881 // Transform classes.jar into classes-jarjar.jar
1882 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001883 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1884 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001885 if ctx.Failed() {
1886 return nil, nil
1887 }
1888 }
1889
Colin Cross3d56ed52021-11-18 22:23:12 -08001890 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001891}
1892
1893func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001894 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001895
1896 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1897 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1898
1899 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1900
1901 j.jacocoReportClassesFile = jacocoReportClassesFile
1902
1903 return instrumentedJar
1904}
1905
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001906type providesTransitiveHeaderJars struct {
1907 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001908 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001909 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001910 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001911}
1912
Colin Crossc85750b2022-04-21 12:50:51 -07001913func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001914 return j.transitiveLibsHeaderJars
1915}
1916
Colin Crossc85750b2022-04-21 12:50:51 -07001917func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001918 return j.transitiveStaticLibsHeaderJars
1919}
1920
1921func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1922 directLibs := android.Paths{}
1923 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001924 transitiveLibs := []*android.DepSet[android.Path]{}
1925 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001926 ctx.VisitDirectDeps(func(module android.Module) {
1927 // don't add deps of the prebuilt version of the same library
1928 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1929 return
1930 }
1931
1932 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1933 if dep.TransitiveLibsHeaderJars != nil {
1934 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1935 }
1936 if dep.TransitiveStaticLibsHeaderJars != nil {
1937 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1938 }
1939
1940 tag := ctx.OtherModuleDependencyTag(module)
1941 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1942 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1943 directLibs = append(directLibs, dep.HeaderJars...)
1944 } else if tag == staticLibTag {
1945 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1946 }
1947 })
1948 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1949 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1950}
1951
Jaewoong Jung26342642021-03-17 15:56:23 -07001952func (j *Module) HeaderJars() android.Paths {
1953 if j.headerJarFile == nil {
1954 return nil
1955 }
1956 return android.Paths{j.headerJarFile}
1957}
1958
1959func (j *Module) ImplementationJars() android.Paths {
1960 if j.implementationJarFile == nil {
1961 return nil
1962 }
1963 return android.Paths{j.implementationJarFile}
1964}
1965
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001966func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001967 return j.dexJarFile
1968}
1969
1970func (j *Module) DexJarInstallPath() android.Path {
1971 return j.installFile
1972}
1973
1974func (j *Module) ImplementationAndResourcesJars() android.Paths {
1975 if j.implementationAndResourcesJar == nil {
1976 return nil
1977 }
1978 return android.Paths{j.implementationAndResourcesJar}
1979}
1980
1981func (j *Module) AidlIncludeDirs() android.Paths {
1982 // exportAidlIncludeDirs is type android.Paths already
1983 return j.exportAidlIncludeDirs
1984}
1985
1986func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1987 return j.classLoaderContexts
1988}
1989
1990// Collect information for opening IDE project files in java/jdeps.go.
1991func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1992 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1993 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1994 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1995 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1996 if j.expandJarjarRules != nil {
1997 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1998 }
1999 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08002000 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2001 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002002 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002003}
2004
2005func (j *Module) CompilerDeps() []string {
2006 jdeps := []string{}
2007 jdeps = append(jdeps, j.properties.Libs...)
2008 jdeps = append(jdeps, j.properties.Static_libs...)
2009 return jdeps
2010}
2011
2012func (j *Module) hasCode(ctx android.ModuleContext) bool {
2013 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2014 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2015}
2016
2017// Implements android.ApexModule
2018func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2019 return j.depIsInSameApex(ctx, dep)
2020}
2021
2022// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002023func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002024 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002025 minSdkVersion := j.MinSdkVersion(ctx)
2026 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002027 return fmt.Errorf("min_sdk_version is not specified")
2028 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002029 // If the module is compiling against core (via sdk_version), skip comparison check.
2030 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002031 return nil
2032 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002033 if minSdkVersion.GreaterThan(sdkVersion) {
2034 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002035 }
2036 return nil
2037}
2038
2039func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002040 if j.stem == "" {
2041 panic("Stem() called before stem property was set")
2042 }
2043 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002044}
2045
Jaewoong Jung26342642021-03-17 15:56:23 -07002046func (j *Module) JacocoReportClassesFile() android.Path {
2047 return j.jacocoReportClassesFile
2048}
2049
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002050func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2051 var fromDeps []*android.DepSet[android.Path]
2052 ctx.VisitDirectDeps(func(module android.Module) {
2053 tag := ctx.OtherModuleDependencyTag(module)
2054 if tag == staticLibTag {
2055 depInfo := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2056 if depInfo.TransitiveSrcFiles != nil {
2057 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2058 }
2059 }
2060 })
2061
2062 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2063}
2064
Jaewoong Jung26342642021-03-17 15:56:23 -07002065func (j *Module) IsInstallable() bool {
2066 return Bool(j.properties.Installable)
2067}
2068
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002069func (j *Module) collectTransitiveAconfigFiles(ctx android.ModuleContext) {
2070 // Aconfig files from this module
2071 mine := j.aconfigIntermediates
2072
2073 // Aconfig files from transitive dependencies
2074 fromDeps := []*android.DepSet[android.Path]{}
2075 ctx.VisitDirectDeps(func(module android.Module) {
2076 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2077 if dep.TransitiveAconfigFiles != nil {
2078 fromDeps = append(fromDeps, dep.TransitiveAconfigFiles)
2079 }
2080 })
2081
2082 // DepSet containing aconfig files myself and from dependencies
2083 j.transitiveAconfigFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2084}
2085
2086func (j *Module) AddAconfigIntermediate(path android.Path) {
2087 j.aconfigIntermediates = append(j.aconfigIntermediates, path)
2088}
2089
2090func (j *Module) getTransitiveAconfigFiles() *android.DepSet[android.Path] {
2091 if j.transitiveAconfigFiles == nil {
2092 panic(fmt.Errorf("java.Moduile: getTransitiveAconfigFiles called before collectTransitiveAconfigFiles module=%s", j.Name()))
2093 }
2094 return j.transitiveAconfigFiles
2095}
2096
Jaewoong Jung26342642021-03-17 15:56:23 -07002097type sdkLinkType int
2098
2099const (
2100 // TODO(jiyong) rename these for better readability. Make the allowed
2101 // and disallowed link types explicit
2102 // order is important here. See rank()
2103 javaCore sdkLinkType = iota
2104 javaSdk
2105 javaSystem
2106 javaModule
2107 javaSystemServer
2108 javaPlatform
2109)
2110
2111func (lt sdkLinkType) String() string {
2112 switch lt {
2113 case javaCore:
2114 return "core Java API"
2115 case javaSdk:
2116 return "Android API"
2117 case javaSystem:
2118 return "system API"
2119 case javaModule:
2120 return "module API"
2121 case javaSystemServer:
2122 return "system server API"
2123 case javaPlatform:
2124 return "private API"
2125 default:
2126 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2127 }
2128}
2129
2130// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2131// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2132// can't statically depend on modules that use Platform API.
2133func (lt sdkLinkType) rank() int {
2134 return int(lt)
2135}
2136
2137type moduleWithSdkDep interface {
2138 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002139 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002140}
2141
Jiyong Park92315372021-04-02 08:45:46 +09002142func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002143 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002144 case android.SdkCore.DefaultJavaLibraryName(),
2145 "legacy.core.platform.api.stubs",
2146 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002147 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002148 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002149 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002150 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002151 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002152 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002153 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002154 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002155 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002156 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002157 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002158 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002159 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002160 return javaSystem, true
2161 }
2162
2163 if stub, linkType := moduleStubLinkType(name); stub {
2164 return linkType, true
2165 }
2166
Jiyong Park92315372021-04-02 08:45:46 +09002167 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002168 switch ver.Kind {
2169 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002170 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002171 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002172 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002173 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002174 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002175 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002176 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002177 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002178 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002179 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002180 return javaPlatform, false
2181 }
2182
Jiyong Parkf1691d22021-03-29 20:11:58 +09002183 if !ver.Valid() {
2184 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002185 }
2186 return javaSdk, false
2187}
2188
2189// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2190// this module's. See the comment on rank() for details and an example.
2191func (j *Module) checkSdkLinkType(
2192 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2193 if ctx.Host() {
2194 return
2195 }
2196
Jiyong Park92315372021-04-02 08:45:46 +09002197 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002198 if stubs {
2199 return
2200 }
Jiyong Park92315372021-04-02 08:45:46 +09002201 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002202
2203 if myLinkType.rank() < depLinkType.rank() {
2204 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2205 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2206 "property of the source or target module so that target module is built "+
2207 "with the same or smaller API set when compared to the source.",
2208 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2209 }
2210}
2211
2212func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2213 var deps deps
2214
2215 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002216 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002217 if sdkDep.invalidVersion {
2218 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2219 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2220 } else if sdkDep.useFiles {
2221 // sdkDep.jar is actually equivalent to turbine header.jar.
2222 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002223 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002224 deps.aidlPreprocess = sdkDep.aidl
2225 } else {
2226 deps.aidlPreprocess = sdkDep.aidl
2227 }
2228 }
2229
Jiyong Park92315372021-04-02 08:45:46 +09002230 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002231
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002232 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002233 ctx.VisitDirectDeps(func(module android.Module) {
2234 otherName := ctx.OtherModuleName(module)
2235 tag := ctx.OtherModuleDependencyTag(module)
2236
2237 if IsJniDepTag(tag) {
2238 // Handled by AndroidApp.collectAppDeps
2239 return
2240 }
2241 if tag == certificateTag {
2242 // Handled by AndroidApp.collectAppDeps
2243 return
2244 }
2245
2246 if dep, ok := module.(SdkLibraryDependency); ok {
2247 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002248 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002249 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2250 deps.classpath = append(deps.classpath, depHeaderJars...)
2251 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002252 case staticLibTag:
2253 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2254 }
2255 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2256 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2257 if sdkLinkType != javaPlatform &&
2258 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2259 // dep is a sysprop implementation library, but this module is not linking against
2260 // the platform, so it gets the sysprop public stubs library instead. Replace
2261 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2262 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2263 dep = syspropDep.JavaInfo
2264 }
2265 switch tag {
2266 case bootClasspathTag:
2267 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002268 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002269 if _, ok := module.(*Plugin); ok {
2270 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2271 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002272 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002273 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002274 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2275 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2276 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2277 case java9LibTag:
2278 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2279 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002280 if _, ok := module.(*Plugin); ok {
2281 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2282 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002283 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2284 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2285 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2286 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2287 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2288 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2289 // Turbine doesn't run annotation processors, so any module that uses an
2290 // annotation processor that generates API is incompatible with the turbine
2291 // optimization.
2292 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2293 case pluginTag:
2294 if plugin, ok := module.(*Plugin); ok {
2295 if plugin.pluginProperties.Processor_class != nil {
2296 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2297 } else {
2298 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2299 }
2300 // Turbine doesn't run annotation processors, so any module that uses an
2301 // annotation processor that generates API is incompatible with the turbine
2302 // optimization.
2303 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2304 } else {
2305 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2306 }
2307 case errorpronePluginTag:
2308 if _, ok := module.(*Plugin); ok {
2309 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2310 } else {
2311 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2312 }
2313 case exportedPluginTag:
2314 if plugin, ok := module.(*Plugin); ok {
2315 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2316 if plugin.pluginProperties.Processor_class != nil {
2317 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2318 }
2319 // Turbine doesn't run annotation processors, so any module that uses an
2320 // annotation processor that generates API is incompatible with the turbine
2321 // optimization.
2322 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2323 } else {
2324 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2325 }
2326 case kotlinStdlibTag:
2327 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2328 case kotlinAnnotationsTag:
2329 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002330 case kotlinPluginTag:
2331 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002332 case syspropPublicStubDepTag:
2333 // This is a sysprop implementation library, forward the JavaInfoProvider from
2334 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2335 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2336 JavaInfo: dep,
2337 })
2338 }
2339 } else if dep, ok := module.(android.SourceFileProducer); ok {
2340 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002341 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002342 checkProducesJars(ctx, dep)
2343 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002344 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002345 case staticLibTag:
2346 checkProducesJars(ctx, dep)
2347 deps.classpath = append(deps.classpath, dep.Srcs()...)
2348 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2349 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2350 }
2351 } else {
2352 switch tag {
2353 case bootClasspathTag:
2354 // If a system modules dependency has been added to the bootclasspath
2355 // then add its libs to the bootclasspath.
2356 sm := module.(SystemModulesProvider)
2357 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2358
2359 case systemModulesTag:
2360 if deps.systemModules != nil {
2361 panic("Found two system module dependencies")
2362 }
2363 sm := module.(SystemModulesProvider)
2364 outputDir, outputDeps := sm.OutputDirAndDeps()
2365 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002366
2367 case instrumentationForTag:
2368 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 -07002369 }
2370 }
2371
2372 addCLCFromDep(ctx, module, j.classLoaderContexts)
2373 })
2374
2375 return deps
2376}
2377
2378func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2379 deps.processorPath = append(deps.processorPath, pluginJars...)
2380 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2381}
2382
2383// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2384// this interface.
2385type ProvidesUsesLib interface {
2386 ProvidesUsesLib() *string
2387}
2388
2389func (j *Module) ProvidesUsesLib() *string {
2390 return j.usesLibraryProperties.Provides_uses_lib
2391}
satayev1c564cc2021-05-25 19:50:30 +01002392
2393type ModuleWithStem interface {
2394 Stem() string
2395}
2396
2397var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002398
Chris Parsons637458d2023-09-19 20:09:00 +00002399func (j *Module) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Wei Libafb6d62021-12-10 03:14:59 -08002400 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002401 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002402 if lib, ok := ctx.Module().(*Library); ok {
2403 javaLibraryBp2Build(ctx, lib)
2404 }
2405 case "java_binary_host":
2406 if binary, ok := ctx.Module().(*Binary); ok {
2407 javaBinaryHostBp2Build(ctx, binary)
2408 }
Zi Wang65b36722023-05-23 15:18:33 -07002409 case "java_test_host":
2410 if testHost, ok := ctx.Module().(*TestHost); ok {
2411 javaTestHostBp2Build(ctx, testHost)
2412 }
Chris Parsons39a16972023-06-08 14:28:51 +00002413 default:
2414 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002415 }
Wei Libafb6d62021-12-10 03:14:59 -08002416}