blob: 295340d3cadf1d8e75fcabfb65f2e9175094d5a1 [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
Yu Liueae7b362023-11-16 17:05:47 -080028 "android/soong/aconfig"
Jaewoong Jung26342642021-03-17 15:56:23 -070029 "android/soong/android"
30 "android/soong/dexpreopt"
31 "android/soong/java/config"
32)
33
34// This file contains the definition and the implementation of the base module that most
35// source-based Java module structs embed.
36
37// TODO:
38// Autogenerated files:
39// Renderscript
40// Post-jar passes:
41// Proguard
42// Rmtypedefs
43// DroidDoc
44// Findbugs
45
46// Properties that are common to most Java modules, i.e. whether it's a host or device module.
47type CommonProperties struct {
48 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
49 // or .aidl files.
50 Srcs []string `android:"path,arch_variant"`
51
52 // list Kotlin of source files containing Kotlin code that should be treated as common code in
53 // a codebase that supports Kotlin multiplatform. See
54 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
55 Common_srcs []string `android:"path,arch_variant"`
56
57 // list of source files that should not be used to build the Java module.
58 // This is most useful in the arch/multilib variants to remove non-common files
59 Exclude_srcs []string `android:"path,arch_variant"`
60
61 // list of directories containing Java resources
62 Java_resource_dirs []string `android:"arch_variant"`
63
64 // list of directories that should be excluded from java_resource_dirs
65 Exclude_java_resource_dirs []string `android:"arch_variant"`
66
67 // list of files to use as Java resources
68 Java_resources []string `android:"path,arch_variant"`
69
70 // list of files that should be excluded from java_resources and java_resource_dirs
71 Exclude_java_resources []string `android:"path,arch_variant"`
72
73 // list of module-specific flags that will be used for javac compiles
74 Javacflags []string `android:"arch_variant"`
75
76 // list of module-specific flags that will be used for kotlinc compiles
77 Kotlincflags []string `android:"arch_variant"`
78
79 // list of java libraries that will be in the classpath
80 Libs []string `android:"arch_variant"`
81
82 // list of java libraries that will be compiled into the resulting jar
83 Static_libs []string `android:"arch_variant"`
84
Jihoon Kang381c2fa2023-06-01 22:17:32 +000085 // list of java libraries that should not be used to build this module
86 Exclude_static_libs []string `android:"arch_variant"`
87
Jaewoong Jung26342642021-03-17 15:56:23 -070088 // manifest file to be included in resulting jar
89 Manifest *string `android:"path"`
90
91 // if not blank, run jarjar using the specified rules file
92 Jarjar_rules *string `android:"path,arch_variant"`
93
94 // If not blank, set the java version passed to javac as -source and -target
95 Java_version *string
96
97 // If set to true, allow this module to be dexed and installed on devices. Has no
98 // effect on host modules, which are always considered installable.
99 Installable *bool
100
101 // If set to true, include sources used to compile the module in to the final jar
102 Include_srcs *bool
103
104 // If not empty, classes are restricted to the specified packages and their sub-packages.
105 // This restriction is checked after applying jarjar rules and including static libs.
106 Permitted_packages []string
107
108 // List of modules to use as annotation processors
109 Plugins []string
110
111 // List of modules to export to libraries that directly depend on this library as annotation
112 // processors. Note that if the plugins set generates_api: true this will disable the turbine
113 // optimization on modules that depend on this module, which will reduce parallelism and cause
114 // more recompilation.
115 Exported_plugins []string
116
117 // The number of Java source entries each Javac instance can process
118 Javac_shard_size *int64
119
120 // Add host jdk tools.jar to bootclasspath
121 Use_tools_jar *bool
122
123 Openjdk9 struct {
124 // List of source files that should only be used when passing -source 1.9 or higher
125 Srcs []string `android:"path"`
126
127 // List of javac flags that should only be used when passing -source 1.9 or higher
128 Javacflags []string
129 }
130
131 // When compiling language level 9+ .java code in packages that are part of
132 // a system module, patch_module names the module that your sources and
133 // dependencies should be patched into. The Android runtime currently
134 // doesn't implement the JEP 261 module system so this option is only
135 // supported at compile time. It should only be needed to compile tests in
136 // packages that exist in libcore and which are inconvenient to move
137 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400138 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700139
140 Jacoco struct {
141 // List of classes to include for instrumentation with jacoco to collect coverage
142 // information at runtime when building with coverage enabled. If unset defaults to all
143 // classes.
144 // Supports '*' as the last character of an entry in the list as a wildcard match.
145 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
146 // it matches classes in the package that have the class name as a prefix.
147 Include_filter []string
148
149 // List of classes to exclude from instrumentation with jacoco to collect coverage
150 // information at runtime when building with coverage enabled. Overrides classes selected
151 // by the include_filter property.
152 // Supports '*' as the last character of an entry in the list as a wildcard match.
153 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
154 // it matches classes in the package that have the class name as a prefix.
155 Exclude_filter []string
156 }
157
158 Errorprone struct {
159 // List of javac flags that should only be used when running errorprone.
160 Javacflags []string
161
162 // List of java_plugin modules that provide extra errorprone checks.
163 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700164
Cole Faust2b1536e2021-06-18 12:25:54 -0700165 // This property can be in 3 states. When set to true, errorprone will
166 // be run during the regular build. When set to false, errorprone will
167 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
168 // environment variable is true. Setting this to false will improve build
169 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700170 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700171 }
172
173 Proto struct {
174 // List of extra options that will be passed to the proto generator.
175 Output_params []string
176 }
177
Sam Delmericoc7593722022-08-31 15:57:52 -0400178 // If true, then jacocoagent is automatically added as a libs dependency so that
179 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700180 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000181 // If true, then the module supports statically including the jacocoagent
182 // into the library.
183 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700184
185 // List of files to include in the META-INF/services folder of the resulting jar.
186 Services []string `android:"path,arch_variant"`
187
188 // If true, package the kotlin stdlib into the jar. Defaults to true.
189 Static_kotlin_stdlib *bool `android:"arch_variant"`
190
191 // A list of java_library instances that provide additional hiddenapi annotations for the library.
192 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700193
194 // Additional srcJars tacked in by GeneratedJavaLibraryModule
195 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000196
197 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400198 Headers_only *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700199}
200
201// Properties that are specific to device modules. Host module factories should not add these when
202// constructing a new module.
203type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000204 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000205 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000206 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000207 // 1) numerical API level, "current", "none", or "core_platform"
208 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
209 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
210 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 Sdk_version *string
212
213 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000214 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700215 Min_sdk_version *string
216
satayev0a420e72021-11-29 17:25:52 +0000217 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
218 // Defaults to empty string "". See sdk_version for possible values.
219 Max_sdk_version *string
220
William Loh5a082f92022-05-17 20:21:50 +0000221 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
222 // Defaults to empty string "". See sdk_version for possible values.
223 Replace_max_sdk_version_placeholder *string
224
Jaewoong Jung26342642021-03-17 15:56:23 -0700225 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000226 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700227 Target_sdk_version *string
228
229 // Whether to compile against the platform APIs instead of an SDK.
230 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000231 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700232 Platform_apis *bool
233
234 Aidl struct {
235 // Top level directories to pass to aidl tool
236 Include_dirs []string
237
238 // Directories rooted at the Android.bp file to pass to aidl tool
239 Local_include_dirs []string
240
241 // directories that should be added as include directories for any aidl sources of modules
242 // that depend on this module, as well as to aidl for this module.
243 Export_include_dirs []string
244
245 // whether to generate traces (for systrace) for this interface
246 Generate_traces *bool
247
248 // whether to generate Binder#GetTransaction name method.
249 Generate_get_transaction_name *bool
250
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100251 // whether all interfaces should be annotated with required permissions.
252 Enforce_permissions *bool
253
254 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
255 Enforce_permissions_exceptions []string `android:"path"`
256
Jaewoong Jung26342642021-03-17 15:56:23 -0700257 // list of flags that will be passed to the AIDL compiler
258 Flags []string
259 }
260
261 // If true, export a copy of the module as a -hostdex module for host testing.
262 Hostdex *bool
263
264 Target struct {
265 Hostdex struct {
266 // Additional required dependencies to add to -hostdex modules.
267 Required []string
268 }
269 }
270
271 // When targeting 1.9 and above, override the modules to use with --system,
272 // otherwise provides defaults libraries to add to the bootclasspath.
273 System_modules *string
274
Jaewoong Jung26342642021-03-17 15:56:23 -0700275 IsSDKLibrary bool `blueprint:"mutated"`
276
277 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
278 // Defaults to false.
279 V4_signature *bool
280
281 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
282 // public stubs library.
283 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000284
285 HiddenAPIPackageProperties
286 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700287}
288
Jooyung Han01d80d82022-01-08 12:16:32 +0900289// Device properties that can be overridden by overriding module (e.g. override_android_app)
290type OverridableDeviceProperties struct {
291 // set the name of the output. If not set, `name` is used.
292 // To override a module with this property set, overriding module might need to set this as well.
293 // Otherwise, both the overridden and the overriding modules will have the same output name, which
294 // can cause the duplicate output error.
295 Stem *string
296}
297
Jaewoong Jung26342642021-03-17 15:56:23 -0700298// Functionality common to Module and Import
299//
300// It is embedded in Module so its functionality can be used by methods in Module
301// but it is currently only initialized by Import and Library.
302type embeddableInModuleAndImport struct {
303
304 // Functionality related to this being used as a component of a java_sdk_library.
305 EmbeddableSdkLibraryComponent
306}
307
Paul Duffin71b33cc2021-06-23 11:39:47 +0100308func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
309 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700310}
311
312// Module/Import's DepIsInSameApex(...) delegates to this method.
313//
314// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
315// the one provided by ApexModuleBase.
316func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
317 // dependencies other than the static linkage are all considered crossing APEX boundary
318 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
319 return true
320 }
321 return false
322}
323
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100324// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
325// or an invalid path describing the reason it is invalid.
326//
327// It is unset if a dex jar isn't applicable, i.e. no build rule has been
328// requested to create one.
329//
330// If a dex jar has been requested to be built then it is set, and it may be
331// either a valid android.Path, or invalid with a reason message. The latter
332// happens if the source that should produce the dex file isn't able to.
333//
334// E.g. it is invalid with a reason message if there is a prebuilt APEX that
335// could produce the dex jar through a deapexer module, but the APEX isn't
336// installable so doing so wouldn't be safe.
337type OptionalDexJarPath struct {
338 isSet bool
339 path android.OptionalPath
340}
341
342// IsSet returns true if a path has been set, either invalid or valid.
343func (o OptionalDexJarPath) IsSet() bool {
344 return o.isSet
345}
346
347// Valid returns true if there is a path that is valid.
348func (o OptionalDexJarPath) Valid() bool {
349 return o.isSet && o.path.Valid()
350}
351
352// Path returns the valid path, or panics if it's either not set or is invalid.
353func (o OptionalDexJarPath) Path() android.Path {
354 if !o.isSet {
355 panic("path isn't set")
356 }
357 return o.path.Path()
358}
359
360// PathOrNil returns the path if it's set and valid, or else nil.
361func (o OptionalDexJarPath) PathOrNil() android.Path {
362 if o.Valid() {
363 return o.Path()
364 }
365 return nil
366}
367
368// InvalidReason returns the reason for an invalid path, which is never "". It
369// returns "" for an unset or valid path.
370func (o OptionalDexJarPath) InvalidReason() string {
371 if !o.isSet {
372 return ""
373 }
374 return o.path.InvalidReason()
375}
376
377func (o OptionalDexJarPath) String() string {
378 if !o.isSet {
379 return "<unset>"
380 }
381 return o.path.String()
382}
383
384// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
385func makeUnsetDexJarPath() OptionalDexJarPath {
386 return OptionalDexJarPath{isSet: false}
387}
388
389// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
390// the given OptionalPath, which may be valid or invalid.
391func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
392 return OptionalDexJarPath{isSet: true, path: path}
393}
394
395// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
396// valid given path. It returns an unset OptionalDexJarPath if the given path is
397// nil.
398func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
399 if path == nil {
400 return makeUnsetDexJarPath()
401 }
402 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
403}
404
Jaewoong Jung26342642021-03-17 15:56:23 -0700405// Module contains the properties and members used by all java module types
406type Module struct {
407 android.ModuleBase
408 android.DefaultableModuleBase
409 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800410 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700411
412 // Functionality common to Module and Import.
413 embeddableInModuleAndImport
414
415 properties CommonProperties
416 protoProperties android.ProtoProperties
417 deviceProperties DeviceProperties
418
Jooyung Han01d80d82022-01-08 12:16:32 +0900419 overridableDeviceProperties OverridableDeviceProperties
420
Jaewoong Jung26342642021-03-17 15:56:23 -0700421 // jar file containing header classes including static library dependencies, suitable for
422 // inserting into the bootclasspath/classpath of another compile
423 headerJarFile android.Path
424
425 // jar file containing implementation classes including static library dependencies but no
426 // resources
427 implementationJarFile android.Path
428
429 // jar file containing only resources including from static library dependencies
430 resourceJar android.Path
431
432 // args and dependencies to package source files into a srcjar
433 srcJarArgs []string
434 srcJarDeps android.Paths
435
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000436 // the source files of this module and all its static dependencies
437 transitiveSrcFiles *android.DepSet[android.Path]
438
Jaewoong Jung26342642021-03-17 15:56:23 -0700439 // jar file containing implementation classes and resources including static library
440 // dependencies
441 implementationAndResourcesJar android.Path
442
443 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100444 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700445
446 // output file containing uninstrumented classes that will be instrumented by jacoco
447 jacocoReportClassesFile android.Path
448
449 // output file of the module, which may be a classes jar or a dex jar
450 outputFile android.Path
451 extraOutputFiles android.Paths
452
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100453 exportAidlIncludeDirs android.Paths
454 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700455
456 logtagsSrcs android.Paths
457
458 // installed file for binary dependency
459 installFile android.Path
460
Colin Cross3108ce12021-11-10 14:38:50 -0800461 // installed file for hostdex copy
462 hostdexInstallFile android.InstallPath
463
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800464 // list of unique .java and .kt source files
465 uniqueSrcFiles android.Paths
466
467 // list of srcjars that was passed to javac
468 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700469
470 // manifest file to use instead of properties.Manifest
471 overrideManifest android.OptionalPath
472
Jaewoong Jung26342642021-03-17 15:56:23 -0700473 // list of plugins that this java module is exporting
474 exportedPluginJars android.Paths
475
476 // list of plugins that this java module is exporting
477 exportedPluginClasses []string
478
479 // if true, the exported plugins generate API and require disabling turbine.
480 exportedDisableTurbine bool
481
482 // list of source files, collected from srcFiles with unique java and all kt files,
483 // will be used by android.IDEInfo struct
484 expandIDEInfoCompiledSrcs []string
485
486 // expanded Jarjar_rules
487 expandJarjarRules android.Path
488
Jaewoong Jung26342642021-03-17 15:56:23 -0700489 // Extra files generated by the module type to be added as java resources.
490 extraResources android.Paths
491
492 hiddenAPI
493 dexer
494 dexpreopter
495 usesLibrary
496 linter
497
498 // list of the xref extraction files
499 kytheFiles android.Paths
500
Jaewoong Jung26342642021-03-17 15:56:23 -0700501 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900502
503 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000504 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000505 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400506
507 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000508
509 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000510
511 // output file name based on Stem property.
512 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
513 // or the module should override Stem().
514 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700515
Yu Liueae7b362023-11-16 17:05:47 -0800516 // Aconfig files for all transitive deps. Also exposed via TransitiveDeclarationsInfo
517 transitiveAconfigFiles map[string]*android.DepSet[android.Path]
Jaewoong Jung26342642021-03-17 15:56:23 -0700518}
519
Jiyong Park92315372021-04-02 08:45:46 +0900520func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
521 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900522 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700523 return nil
524 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900525 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000526 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700527 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
528 } else {
529 // Treat stable core platform as stable.
530 return nil
531 }
532 } else {
533 return fmt.Errorf("non stable SDK %v", sdkVersion)
534 }
535}
536
537// checkSdkVersions enforces restrictions around SDK dependencies.
538func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
539 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900540 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900541 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700542 ctx.PropertyErrorf("sdk_version",
543 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
544 }
545 }
546 }
547
548 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
549 // See rank() for details.
550 ctx.VisitDirectDeps(func(module android.Module) {
551 tag := ctx.OtherModuleDependencyTag(module)
552 switch module.(type) {
553 // TODO(satayev): cover other types as well, e.g. imports
554 case *Library, *AndroidLibrary:
555 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400556 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700557 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
558 }
559 }
560 })
561}
562
563func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900564 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700565 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900566 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700567 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000568 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 -0700569 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000570 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 -0700571 }
572
573 }
574}
575
Mark Whitea15790a2023-08-22 21:28:11 +0000576func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
577 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400578 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000579 installable := proptools.Bool(j.properties.Installable)
580
581 if headersOnly && installable {
582 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.")
583 }
584 }
585}
586
Jaewoong Jung26342642021-03-17 15:56:23 -0700587func (j *Module) addHostProperties() {
588 j.AddProperties(
589 &j.properties,
590 &j.protoProperties,
591 &j.usesLibraryProperties,
592 )
593}
594
595func (j *Module) addHostAndDeviceProperties() {
596 j.addHostProperties()
597 j.AddProperties(
598 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900599 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700600 &j.dexer.dexProperties,
601 &j.dexpreoptProperties,
602 &j.linter.properties,
603 )
604}
605
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000606// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
607// makes it available through the hiddenAPIPropertyInfoProvider.
608func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
609 hiddenAPIInfo := newHiddenAPIPropertyInfo()
610
611 // Populate with flag file paths from the properties.
612 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
613
614 // Populate with package rules from the properties.
615 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
616
617 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
618}
619
Jaewoong Jung26342642021-03-17 15:56:23 -0700620func (j *Module) OutputFiles(tag string) (android.Paths, error) {
621 switch tag {
622 case "":
623 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
624 case android.DefaultDistTag:
625 return android.Paths{j.outputFile}, nil
626 case ".jar":
627 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700628 case ".hjar":
629 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700630 case ".proguard_map":
631 if j.dexer.proguardDictionary.Valid() {
632 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
633 }
634 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700635 case ".generated_srcjars":
636 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000637 case ".lint":
638 if j.linter.outputs.xml != nil {
639 return android.Paths{j.linter.outputs.xml}, nil
640 }
641 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700642 default:
643 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
644 }
645}
646
647var _ android.OutputFileProducer = (*Module)(nil)
648
649func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
650 initJavaModule(module, hod, false)
651}
652
653func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
654 initJavaModule(module, hod, true)
655}
656
657func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
658 multilib := android.MultilibCommon
659 if multiTargets {
660 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
661 } else {
662 android.InitAndroidArchModule(module, hod, multilib)
663 }
664 android.InitDefaultableModule(module)
665}
666
667func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
668 return j.properties.Instrument &&
669 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
670 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
671}
672
673func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000674 return j.properties.Supports_static_instrumentation &&
675 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700676 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
677 ctx.Config().UnbundledBuild())
678}
679
680func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
681 // Force enable the instrumentation for java code that is built for APEXes ...
682 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
683 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
684 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
685 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
686 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
687 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
688 return true
689 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
690 return true
691 }
692 }
693 return false
694}
695
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400696func (j *Module) setInstrument(value bool) {
697 j.properties.Instrument = value
698}
699
Jiyong Park92315372021-04-02 08:45:46 +0900700func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
701 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700702}
703
Jiyong Parkf1691d22021-03-29 20:11:58 +0900704func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700705 return proptools.String(j.deviceProperties.System_modules)
706}
707
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000708func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700709 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000710 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700711 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000712 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700713}
714
Yu Liuf2b94012023-09-19 15:09:10 -0700715func (j *Module) GetDeviceProperties() *DeviceProperties {
716 return &j.deviceProperties
717}
718
Spandan Dasa26eda72023-03-02 00:56:06 +0000719func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
720 if j.deviceProperties.Max_sdk_version != nil {
721 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
722 }
723 // Default is PrivateApiLevel
724 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000725}
726
Spandan Dasa26eda72023-03-02 00:56:06 +0000727func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
728 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
729 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
730 }
731 // Default is PrivateApiLevel
732 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000733}
734
Jiyong Parkf1691d22021-03-29 20:11:58 +0900735func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000736 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900737}
738
Spandan Dasca70fc42023-03-01 23:38:49 +0000739func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900740 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000741 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900742 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000743 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700744}
745
746func (j *Module) AvailableFor(what string) bool {
747 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
748 // Exception: for hostdex: true libraries, the platform variant is created
749 // even if it's not marked as available to platform. In that case, the platform
750 // variant is used only for the hostdex and not installed to the device.
751 return true
752 }
753 return j.ApexModuleBase.AvailableFor(what)
754}
755
756func (j *Module) deps(ctx android.BottomUpMutatorContext) {
757 if ctx.Device() {
758 j.linter.deps(ctx)
759
Jiyong Parkf1691d22021-03-29 20:11:58 +0900760 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700761
762 if j.deviceProperties.SyspropPublicStub != "" {
763 // This is a sysprop implementation library that has a corresponding sysprop public
764 // stubs library, and a dependency on it so that dependencies on the implementation can
765 // be forwarded to the public stubs library when necessary.
766 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
767 }
768 }
769
770 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000771
772 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700773 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
774
775 // Add dependency on libraries that provide additional hidden api annotations.
776 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
777
778 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
779 // Require java_sdk_library at inter-partition java dependency to ensure stable
780 // interface between partitions. If inter-partition java_library dependency is detected,
781 // raise build error because java_library doesn't have a stable interface.
782 //
783 // Inputs:
784 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
785 // if true, enable enforcement
786 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
787 // exception list of java_library names to allow inter-partition dependency
788 for idx := range j.properties.Libs {
789 if libDeps[idx] == nil {
790 continue
791 }
792
793 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
794 // java_sdk_library is always allowed at inter-partition dependency.
795 // So, skip check.
796 if _, ok := javaDep.(*SdkLibrary); ok {
797 continue
798 }
799
800 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
801 }
802 }
803 }
804
805 // For library dependencies that are component libraries (like stubs), add the implementation
806 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
807 for _, dep := range libDeps {
808 if dep != nil {
809 if component, ok := dep.(SdkLibraryComponentDependency); ok {
810 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100811 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100812 tag := usesLibReqTag
813 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
814 tag = usesLibOptTag
815 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100816 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700817 }
818 }
819 }
820 }
821
822 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
823 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
824 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
825
826 android.ProtoDeps(ctx, &j.protoProperties)
827 if j.hasSrcExt(".proto") {
828 protoDeps(ctx, &j.protoProperties)
829 }
830
831 if j.hasSrcExt(".kt") {
832 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
833 // Kotlin files
834 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
835 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700836 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700837 }
838
839 // Framework libraries need special handling in static coverage builds: they should not have
840 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
841 // the same jacoco classes coming from different bootclasspath jars.
842 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
843 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
844 j.properties.Instrument = true
845 }
846 } else if j.shouldInstrumentStatic(ctx) {
847 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
848 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700849
850 if j.useCompose() {
851 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
852 "androidx.compose.compiler_compiler-hosted")
853 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700854}
855
856func hasSrcExt(srcs []string, ext string) bool {
857 for _, src := range srcs {
858 if filepath.Ext(src) == ext {
859 return true
860 }
861 }
862
863 return false
864}
865
866func (j *Module) hasSrcExt(ext string) bool {
867 return hasSrcExt(j.properties.Srcs, ext)
868}
869
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100870func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
871 var flags string
872
873 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
874 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
875 flags = "-Wmissing-permission-annotation -Werror"
876 }
877 }
878 return flags
879}
880
Jaewoong Jung26342642021-03-17 15:56:23 -0700881func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000882 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700883
884 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
885 aidlIncludes = append(aidlIncludes,
886 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
887 aidlIncludes = append(aidlIncludes,
888 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
889
890 var flags []string
891 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000892 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700893
894 flags = append(flags, j.deviceProperties.Aidl.Flags...)
895
896 if aidlPreprocess.Valid() {
897 flags = append(flags, "-p"+aidlPreprocess.String())
898 deps = append(deps, aidlPreprocess.Path())
899 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000900 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700901 }
902
903 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000904 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700905 }
906
907 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000908 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700909 }
910
Sam Delmerico2351eac2022-05-24 17:10:02 +0000911 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000913 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700914 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000915 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
916 // add flags for dirs containing AIDL srcs that haven't been specified yet
917 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700918
Zim8774ae12022-08-17 11:46:34 +0100919 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000920 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100921 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700922 flags = append(flags, "-t")
923 }
924
925 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
926 flags = append(flags, "--transaction_names")
927 }
928
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100929 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
930 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
931 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
932 }
933
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000934 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900935 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
936
Jaewoong Jung26342642021-03-17 15:56:23 -0700937 return strings.Join(flags, " "), deps
938}
939
940func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
941
942 var flags javaBuilderFlags
943
944 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900945 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700946
Cole Faust2b1536e2021-06-18 12:25:54 -0700947 epEnabled := j.properties.Errorprone.Enabled
948 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100949 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700950 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
951 }
952
953 errorProneFlags := []string{
954 "-Xplugin:ErrorProne",
955 "${config.ErrorProneChecks}",
956 }
957 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
958
Colin Cross8bf6cad2022-02-28 13:07:03 -0800959 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700960 "'" + strings.Join(errorProneFlags, " ") + "'"
961 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
962 }
963
964 // classpath
965 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
966 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700967 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700968 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
969 flags.processorPath = append(flags.processorPath, deps.processorPath...)
970 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
971
972 flags.processors = append(flags.processors, deps.processorClasses...)
973 flags.processors = android.FirstUniqueStrings(flags.processors)
974
975 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900976 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700977 // Give host-side tools a version of OpenJDK's standard libraries
978 // close to what they're targeting. As of Dec 2017, AOSP is only
979 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
980 //
981 // When building with OpenJDK 8, the following should have no
982 // effect since those jars would be available by default.
983 //
984 // When building with OpenJDK 9 but targeting a version < 1.8,
985 // putting them on the bootclasspath means that:
986 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
987 // b) references to existing APIs are not reinterpreted in an
988 // OpenJDK 9-specific way, eg. calls to subclasses of
989 // java.nio.Buffer as in http://b/70862583
990 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
991 flags.bootClasspath = append(flags.bootClasspath,
992 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
993 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
994 if Bool(j.properties.Use_tools_jar) {
995 flags.bootClasspath = append(flags.bootClasspath,
996 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
997 }
998 }
999
1000 // systemModules
1001 flags.systemModules = deps.systemModules
1002
Jaewoong Jung26342642021-03-17 15:56:23 -07001003 return flags
1004}
1005
1006func (j *Module) collectJavacFlags(
1007 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1008 // javac flags.
1009 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001010 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001011
Mythri Alle4b9f6182023-10-25 15:17:11 +00001012 needsDebugInfo = false
1013 for _, flag := range javacFlags {
1014 if strings.HasPrefix(flag, "-g") {
1015 needsDebugInfo = true
1016 }
1017 }
1018
1019 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001020 // For non-host binaries, override the -g flag passed globally to remove
1021 // local variable debug info to reduce disk and memory usage.
1022 javacFlags = append(javacFlags, "-g:source,lines")
1023 }
1024 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1025
1026 if flags.javaVersion.usesJavaModules() {
1027 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001028 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1029 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1030 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1031 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001032
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001033 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001034 if j.properties.Patch_module != nil {
1035 // Manually specify build directory in case it is not under the repo root.
1036 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1037 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001038 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001039
1040 // b/150878007
1041 //
1042 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1043 // execution root for --patch-module. If this javac command line is
1044 // invoked within Bazel's execution root working directory, the top
1045 // level directories (e.g. libcore/, tools/, frameworks/) are all
1046 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1047 // --patch-module to fail source file lookups when invoked in the
1048 // execution root.
1049 //
1050 // Short of patching javac or enumerating *all* directories as possible
1051 // input dirs, manually add the top level dir of the source files to be
1052 // compiled.
1053 topLevelDirs := map[string]bool{}
1054 for _, srcFilePath := range srcFiles {
1055 srcFileParts := strings.Split(srcFilePath.String(), "/")
1056 // Ignore source files that are already in the top level directory
1057 // as well as generated files in the out directory. The out
1058 // directory may be an absolute path, which means srcFileParts[0] is the
1059 // empty string, so check that as well. Note that "out" in Bazel's execution
1060 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1061 // anyway, so it's fine to not apply this workaround for generated
1062 // source files.
1063 if len(srcFileParts) > 1 &&
1064 srcFileParts[0] != "" &&
1065 srcFileParts[0] != "out" {
1066 topLevelDirs[srcFileParts[0]] = true
1067 }
1068 }
Cole Faust18994c72023-02-28 16:02:16 -08001069 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001070
1071 classPath := flags.classpath.FormJavaClassPath("")
1072 if classPath != "" {
1073 patchPaths = append(patchPaths, classPath)
1074 }
1075 javacFlags = append(
1076 javacFlags,
1077 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1078 }
1079 }
1080
1081 if len(javacFlags) > 0 {
1082 // optimization.
1083 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1084 flags.javacFlags = "$javacFlags"
1085 }
1086
1087 return flags
1088}
1089
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001090func (j *Module) AddJSONData(d *map[string]interface{}) {
1091 (&j.ModuleBase).AddJSONData(d)
1092 (*d)["Java"] = map[string]interface{}{
1093 "SourceExtensions": j.sourceExtensions,
1094 }
1095
1096}
1097
usta0391ca42023-09-19 15:51:59 -04001098func (j *Module) addGeneratedSrcJars(path android.Path) {
1099 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001100}
1101
Colin Cross4eae06d2023-06-20 22:40:02 -07001102func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001103 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1104
1105 deps := j.collectDeps(ctx)
1106 flags := j.collectBuilderFlags(ctx, deps)
1107
1108 if flags.javaVersion.usesJavaModules() {
1109 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001110 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1111 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1112 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001113 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001114
Jaewoong Jung26342642021-03-17 15:56:23 -07001115 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001116 j.sourceExtensions = []string{}
1117 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1118 if hasSrcExt(srcFiles.Strings(), ext) {
1119 j.sourceExtensions = append(j.sourceExtensions, ext)
1120 }
1121 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001122 if hasSrcExt(srcFiles.Strings(), ".proto") {
1123 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1124 }
1125
1126 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1127 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1128 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1129 }
1130
Sam Delmerico2351eac2022-05-24 17:10:02 +00001131 aidlSrcs := srcFiles.FilterByExt(".aidl")
1132 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1133
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001134 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001135 srcFiles = j.genSources(ctx, srcFiles, flags)
1136
1137 // Collect javac flags only after computing the full set of srcFiles to
1138 // ensure that the --patch-module lookup paths are complete.
1139 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1140
1141 srcJars := srcFiles.FilterByExt(".srcjar")
1142 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001143 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001144 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001145 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001146
1147 if j.properties.Jarjar_rules != nil {
1148 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1149 }
1150
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001151 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001152
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001153 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001155 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001156 if _, found := set[v.String()]; !found {
1157 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001158 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 }
1160 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001161 var uniqueKtFiles android.Paths
1162 for _, v := range srcFiles.FilterByExt(".kt") {
1163 if _, found := set[v.String()]; !found {
1164 set[v.String()] = true
1165 uniqueKtFiles = append(uniqueKtFiles, v)
1166 }
1167 }
1168
1169 var uniqueSrcFiles android.Paths
1170 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1171 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1172 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001173
Colin Crossb5db4012022-03-28 17:12:39 -07001174 // We don't currently run annotation processors in turbine, which means we can't use turbine
1175 // generated header jars when an annotation processor that generates API is enabled. One
1176 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1177 // is used to run all of the annotation processors.
1178 disableTurbine := deps.disableTurbine
1179
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001180 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001181 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1182
1183 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001184 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001185
Colin Cross4eae06d2023-06-20 22:40:02 -07001186 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1187 // any dependencies so that it can override any non-final R classes from dependencies with the
1188 // final R classes from the app.
1189 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1190
Mark Whitea15790a2023-08-22 21:28:11 +00001191 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001192 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001193 if srcFiles.HasExt(".kt") {
1194 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1195 }
1196 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1197 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1198 }
1199
1200 _, j.headerJarFile =
1201 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1202 extraCombinedJars)
1203 if ctx.Failed() {
1204 return
1205 }
1206
1207 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1208 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1209 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1210 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1211 AidlIncludeDirs: j.exportAidlIncludeDirs,
1212 ExportedPlugins: j.exportedPluginJars,
1213 ExportedPluginClasses: j.exportedPluginClasses,
1214 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1215 })
1216
1217 j.outputFile = j.headerJarFile
1218 return
1219 }
1220
Jaewoong Jung26342642021-03-17 15:56:23 -07001221 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001222 // When using kotlin sources turbine is used to generate annotation processor sources,
1223 // including for annotation processors that generate API, so we can use turbine for
1224 // java sources too.
1225 disableTurbine = false
1226
Jaewoong Jung26342642021-03-17 15:56:23 -07001227 // user defined kotlin flags.
1228 kotlincFlags := j.properties.Kotlincflags
1229 CheckKotlincFlags(ctx, kotlincFlags)
1230
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001231 // Workaround for KT-46512
1232 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001233
1234 // If there are kotlin files, compile them first but pass all the kotlin and java files
1235 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1236 // won't emit any classes for them.
1237 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1238 if ctx.Device() {
1239 kotlincFlags = append(kotlincFlags, "-no-jdk")
1240 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001241
1242 for _, plugin := range deps.kotlinPlugins {
1243 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1244 }
1245 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1246
Jaewoong Jung26342642021-03-17 15:56:23 -07001247 if len(kotlincFlags) > 0 {
1248 // optimization.
1249 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1250 flags.kotlincFlags += "$kotlincFlags"
1251 }
1252
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001253 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001254 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1255
1256 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1257 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1258
1259 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1260 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1261
Isaac Chioua23d9942022-04-06 06:14:38 +00001262 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001263 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001264 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1265 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001266 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001267 srcJars = append(srcJars, kaptSrcJar)
1268 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001269 // Disable annotation processing in javac, it's already been handled by kapt
1270 flags.processorPath = nil
1271 flags.processors = nil
1272 }
1273
1274 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001275 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001276 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001277 if ctx.Failed() {
1278 return
1279 }
1280
Isaac Chioua23d9942022-04-06 06:14:38 +00001281 // Make javac rule depend on the kotlinc rule
1282 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1283
Jaewoong Jung26342642021-03-17 15:56:23 -07001284 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001285 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1286
Jaewoong Jung26342642021-03-17 15:56:23 -07001287 // Jar kotlin classes into the final jar after javac
1288 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1289 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001290 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001291 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001292 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001293 } else {
1294 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001295 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001296 }
1297 }
1298
1299 jars := append(android.Paths(nil), kotlinJars...)
1300
Jaewoong Jung26342642021-03-17 15:56:23 -07001301 j.compiledSrcJars = srcJars
1302
1303 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001304 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001305 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001306 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1307 enableSharding = true
1308 // Formerly, there was a check here that prevented annotation processors
1309 // from being used when sharding was enabled, as some annotation processors
1310 // do not function correctly in sharded environments. It was removed to
1311 // allow for the use of annotation processors that do function correctly
1312 // with sharding enabled. See: b/77284273.
1313 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001314 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001315 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001316 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001317 if ctx.Failed() {
1318 return
1319 }
1320 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001321 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001322 hasErrorproneableFiles := false
1323 for _, ext := range j.sourceExtensions {
1324 if ext != ".proto" && ext != ".aidl" {
1325 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1326 // compile, and it's not useful to have warnings on these generated sources.
1327 hasErrorproneableFiles = true
1328 break
1329 }
1330 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001331 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001332 if Bool(j.properties.Errorprone.Enabled) {
1333 // If error-prone is enabled, enable errorprone flags on the regular
1334 // build.
1335 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001336 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001337 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1338 // a new jar file just for compiling with the errorprone compiler to.
1339 // This is because we don't want to cause the java files to get completely
1340 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1341 // We also don't want to run this if errorprone is enabled by default for
1342 // this module, or else we could have duplicated errorprone messages.
1343 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001344 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001345 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001346
Vadim Spivak3c496f02023-06-08 06:14:59 +00001347 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001348 "errorprone", "errorprone")
1349
Jaewoong Jung26342642021-03-17 15:56:23 -07001350 extraJarDeps = append(extraJarDeps, errorprone)
1351 }
1352
1353 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001354 if headerJarFileWithoutDepsOrJarjar != nil {
1355 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1356 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001357 shardSize := int(*(j.properties.Javac_shard_size))
1358 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001359 if len(uniqueJavaFiles) > 0 {
1360 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001361 for idx, shardSrc := range shardSrcs {
1362 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1363 nil, flags, extraJarDeps)
1364 jars = append(jars, classes)
1365 }
1366 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001367 // Assume approximately 5 sources per srcjar.
1368 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1369 // 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 -07001370 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001371 startIdx := len(shardSrcs)
1372 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1373 for idx, shardSrcJars := range shardSrcJarsList {
1374 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1375 nil, shardSrcJars, flags, extraJarDeps)
1376 jars = append(jars, classes)
1377 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001378 }
1379 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001380 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001381 jars = append(jars, classes)
1382 }
1383 if ctx.Failed() {
1384 return
1385 }
1386 }
1387
1388 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1389
1390 var includeSrcJar android.WritablePath
1391 if Bool(j.properties.Include_srcs) {
1392 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1393 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1394 }
1395
1396 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1397 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1398 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1399 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1400
1401 var resArgs []string
1402 var resDeps android.Paths
1403
1404 resArgs = append(resArgs, dirArgs...)
1405 resDeps = append(resDeps, dirDeps...)
1406
1407 resArgs = append(resArgs, fileArgs...)
1408 resDeps = append(resDeps, fileDeps...)
1409
1410 resArgs = append(resArgs, extraArgs...)
1411 resDeps = append(resDeps, extraDeps...)
1412
1413 if len(resArgs) > 0 {
1414 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1415 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1416 j.resourceJar = resourceJar
1417 if ctx.Failed() {
1418 return
1419 }
1420 }
1421
1422 var resourceJars android.Paths
1423 if j.resourceJar != nil {
1424 resourceJars = append(resourceJars, j.resourceJar)
1425 }
1426 if Bool(j.properties.Include_srcs) {
1427 resourceJars = append(resourceJars, includeSrcJar)
1428 }
1429 resourceJars = append(resourceJars, deps.staticResourceJars...)
1430
1431 if len(resourceJars) > 1 {
1432 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1433 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1434 false, nil, nil)
1435 j.resourceJar = combinedJar
1436 } else if len(resourceJars) == 1 {
1437 j.resourceJar = resourceJars[0]
1438 }
1439
1440 if len(deps.staticJars) > 0 {
1441 jars = append(jars, deps.staticJars...)
1442 }
1443
1444 manifest := j.overrideManifest
1445 if !manifest.Valid() && j.properties.Manifest != nil {
1446 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1447 }
1448
1449 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1450 if len(services) > 0 {
1451 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1452 var zipargs []string
1453 for _, file := range services {
1454 serviceFile := file.String()
1455 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1456 }
1457 rule := zip
1458 args := map[string]string{
1459 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1460 }
1461 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1462 rule = zipRE
1463 args["implicits"] = strings.Join(services.Strings(), ",")
1464 }
1465 ctx.Build(pctx, android.BuildParams{
1466 Rule: rule,
1467 Output: servicesJar,
1468 Implicits: services,
1469 Args: args,
1470 })
1471 jars = append(jars, servicesJar)
1472 }
1473
Colin Cross4eae06d2023-06-20 22:40:02 -07001474 jars = append(android.CopyOf(extraCombinedJars), jars...)
1475
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 // Combine the classes built from sources, any manifests, and any static libraries into
1477 // classes.jar. If there is only one input jar this step will be skipped.
1478 var outputFile android.OutputPath
1479
1480 if len(jars) == 1 && !manifest.Valid() {
1481 // Optimization: skip the combine step as there is nothing to do
1482 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1483 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1484 // any if len(jars) == 1.
1485
Jihoon Kang1147b312023-06-08 23:25:57 +00001486 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1487 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1488 // either with .from-source or .from-text suffix.
1489 // outputFile should be agnostic to the build configuration,
1490 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1491 // to the copy rules.
1492 stub, _ := moduleStubLinkType(ctx.ModuleName())
1493
Jaewoong Jung26342642021-03-17 15:56:23 -07001494 // Transform the single path to the jar into an OutputPath as that is required by the following
1495 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001496 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001497 // The path contains an embedded OutputPath so reuse that.
1498 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001499 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001500 // The path is an OutputPath so reuse it directly.
1501 outputFile = outputPath
1502 } else {
1503 // The file is not in the out directory so create an OutputPath into which it can be copied
1504 // and which the following code can use to refer to it.
1505 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1506 ctx.Build(pctx, android.BuildParams{
1507 Rule: android.Cp,
1508 Input: jars[0],
1509 Output: combinedJar,
1510 })
1511 outputFile = combinedJar.OutputPath
1512 }
1513 } else {
1514 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1515 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1516 false, nil, nil)
1517 outputFile = combinedJar.OutputPath
1518 }
1519
1520 // jarjar implementation jar if necessary
1521 if j.expandJarjarRules != nil {
1522 // Transform classes.jar into classes-jarjar.jar
1523 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1524 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1525 outputFile = jarjarFile
1526
1527 // jarjar resource jar if necessary
1528 if j.resourceJar != nil {
1529 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1530 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1531 j.resourceJar = resourceJarJarFile
1532 }
1533
1534 if ctx.Failed() {
1535 return
1536 }
1537 }
1538
1539 // Check package restrictions if necessary.
1540 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001541 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001542 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001543
1544 // Create a rule to copy the output jar to another path and add a validate dependency that
1545 // will check that the jar only contains the permitted packages. The new location will become
1546 // the output file of this module.
1547 inputFile := outputFile
1548 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1549 ctx.Build(pctx, android.BuildParams{
1550 Rule: android.Cp,
1551 Input: inputFile,
1552 Output: outputFile,
1553 // Make sure that any dependency on the output file will cause ninja to run the package check
1554 // rule.
1555 Validation: pkgckFile,
1556 })
1557
1558 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001559 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001560
1561 if ctx.Failed() {
1562 return
1563 }
1564 }
1565
1566 j.implementationJarFile = outputFile
1567 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001568 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1569 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1570 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1571 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1572 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1573 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1574 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001575 }
1576
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001577 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1578 specs := j.jacocoModuleToZipCommand(ctx)
1579 if ctx.Failed() {
1580 return
1581 }
1582
Jaewoong Jung26342642021-03-17 15:56:23 -07001583 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001584 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001585 }
1586
1587 // merge implementation jar with resources if necessary
1588 implementationAndResourcesJar := outputFile
1589 if j.resourceJar != nil {
1590 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1591 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1592 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1593 false, nil, nil)
1594 implementationAndResourcesJar = combinedJar
1595 }
1596
1597 j.implementationAndResourcesJar = implementationAndResourcesJar
1598
1599 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001600 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001601 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1602 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001603 if compileDex == nil {
1604 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001605 }
1606 if j.deviceProperties.Hostdex == nil {
1607 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1608 }
1609 }
1610
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001611 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001612 if j.hasCode(ctx) {
1613 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001614 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001615 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1616 }
1617 // Dex compilation
1618 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001619 params := &compileDexParams{
1620 flags: flags,
1621 sdkVersion: j.SdkVersion(ctx),
1622 minSdkVersion: j.MinSdkVersion(ctx),
1623 classesJar: implementationAndResourcesJar,
1624 jarName: jarName,
1625 }
1626 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001627 if ctx.Failed() {
1628 return
1629 }
1630
Jaewoong Jung26342642021-03-17 15:56:23 -07001631 // merge dex jar with resources if necessary
1632 if j.resourceJar != nil {
1633 jars := android.Paths{dexOutputFile, j.resourceJar}
1634 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1635 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1636 false, nil, nil)
1637 if *j.dexProperties.Uncompress_dex {
1638 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001639 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001640 dexOutputFile = combinedAlignedJar
1641 } else {
1642 dexOutputFile = combinedJar
1643 }
1644 }
1645
Paul Duffin4de94502021-05-16 05:21:16 +01001646 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001647
1648 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001649
1650 // Encode hidden API flags in dex file, if needed.
1651 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1652
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001653 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001654
1655 // Dexpreopting
1656 j.dexpreopt(ctx, dexOutputFile)
1657
1658 outputFile = dexOutputFile
1659 } else {
1660 // There is no code to compile into a dex jar, make sure the resources are propagated
1661 // to the APK if this is an app.
1662 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001663 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001664 }
1665
1666 if ctx.Failed() {
1667 return
1668 }
1669 } else {
1670 outputFile = implementationAndResourcesJar
1671 }
1672
1673 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001674 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1675 if !apiLevel.IsPreview() {
1676 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001677 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001678 // When running metalava, we pass --version-codename. When that value
1679 // is not REL, metalava will add 1 to the --current-version argument.
1680 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1681 // branch) and the codename is REL, except potentially on the most
1682 // recent non-master branch. On that branch, it goes through two other
1683 // phases before it gets to the phase previously described:
1684 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1685 // is not rel. This happens for most of the internal branch's life
1686 // while the branch has been cut but is still under active development.
1687 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1688 // REL. This happens briefly during the release process. During this
1689 // state the code to add --current-version is commented out, and then
1690 // that commenting out is reverted after the codename is set to REL.
1691 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1692 // prior version and the codename is always non-REL.
1693 //
1694 // We need to add one here to match metalava adding 1. Technically
1695 // this means that in the state described in the second bullet point
1696 // above, this number is 1 higher than it should be.
1697 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001698 }
1699 }
1700
1701 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001702 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1703 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001704 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1705 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001706 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001707 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001708 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001709 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001710 j.linter.javaLanguageLevel = flags.javaVersion.String()
1711 j.linter.kotlinLanguageLevel = "1.3"
1712 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1713 j.linter.buildModuleReportZip = true
1714 }
1715 j.linter.lint(ctx)
1716 }
1717
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001718 j.collectTransitiveSrcFiles(ctx, srcFiles)
1719
Jaewoong Jung26342642021-03-17 15:56:23 -07001720 ctx.CheckbuildFile(outputFile)
1721
Yu Liueae7b362023-11-16 17:05:47 -08001722 aconfig.CollectTransitiveAconfigFiles(ctx, &j.transitiveAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001723
Jaewoong Jung26342642021-03-17 15:56:23 -07001724 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1725 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001726 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1727 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1729 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1730 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1731 AidlIncludeDirs: j.exportAidlIncludeDirs,
1732 SrcJarArgs: j.srcJarArgs,
1733 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001734 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001735 ExportedPlugins: j.exportedPluginJars,
1736 ExportedPluginClasses: j.exportedPluginClasses,
1737 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1738 JacocoReportClassesFile: j.jacocoReportClassesFile,
1739 })
1740
1741 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1742 j.outputFile = outputFile.WithoutRel()
1743}
1744
Colin Crossa1ff7c62021-09-17 14:11:52 -07001745func (j *Module) useCompose() bool {
1746 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1747}
1748
Sam Delmerico95d70942023-08-02 18:00:35 -04001749func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1750 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1751 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1752
1753 ctx.VisitDirectDeps(func(m android.Module) {
1754 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1755 depTag := ctx.OtherModuleDependencyTag(m)
1756
1757 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1758 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1759 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1760 }
1761
1762 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1763 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1764 }
1765 })
1766
1767 directUnconditionalExportedFlags := android.Paths{}
1768 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1769 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1770 if exportUnconditionally {
1771 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1772 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1773 directUnconditionalExportedFlags = proguardFlagsForThisModule
1774 }
1775
1776 return ProguardSpecInfo{
1777 Export_proguard_flags_files: exportUnconditionally,
1778 ProguardFlagsFiles: android.NewDepSet[android.Path](
1779 android.POSTORDER,
1780 proguardFlagsForThisModule,
1781 transitiveProguardFlags,
1782 ),
1783 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1784 android.POSTORDER,
1785 directUnconditionalExportedFlags,
1786 transitiveUnconditionalExportedFlags,
1787 ),
1788 }
1789
1790}
1791
Cole Faust75fffb12021-06-13 15:23:16 -07001792// Returns a copy of the supplied flags, but with all the errorprone-related
1793// fields copied to the regular build's fields.
1794func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1795 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1796
1797 if len(flags.errorProneExtraJavacFlags) > 0 {
1798 if len(flags.javacFlags) > 0 {
1799 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1800 } else {
1801 flags.javacFlags = flags.errorProneExtraJavacFlags
1802 }
1803 }
1804 return flags
1805}
1806
Jaewoong Jung26342642021-03-17 15:56:23 -07001807func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1808 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1809
1810 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001811 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001812 if idx >= 0 {
1813 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001814 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001815 jarName += strconv.Itoa(idx)
1816 }
1817
1818 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001819 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001820
1821 if ctx.Config().EmitXrefRules() {
1822 extractionFile := android.PathForModuleOut(ctx, kzipName)
1823 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1824 j.kytheFiles = append(j.kytheFiles, extractionFile)
1825 }
1826
Vadim Spivak3c496f02023-06-08 06:14:59 +00001827 if len(flags.processorPath) > 0 {
1828 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1829 }
1830
Jaewoong Jung26342642021-03-17 15:56:23 -07001831 return classes
1832}
1833
1834// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1835// since some of these flags may be used internally.
1836func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1837 for _, flag := range flags {
1838 flag = strings.TrimSpace(flag)
1839
1840 if !strings.HasPrefix(flag, "-") {
1841 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1842 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1843 ctx.PropertyErrorf("kotlincflags",
1844 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1845 } else if inList(flag, config.KotlincIllegalFlags) {
1846 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1847 } else if flag == "-include-runtime" {
1848 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1849 } else {
1850 args := strings.Split(flag, " ")
1851 if args[0] == "-kotlin-home" {
1852 ctx.PropertyErrorf("kotlincflags",
1853 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1854 }
1855 }
1856 }
1857}
1858
1859func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1860 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001861 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001862
1863 var jars android.Paths
1864 if len(srcFiles) > 0 || len(srcJars) > 0 {
1865 // Compile java sources into turbine.jar.
1866 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1867 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1868 if ctx.Failed() {
1869 return nil, nil
1870 }
1871 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001872 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001873 }
1874
1875 jars = append(jars, extraJars...)
1876
1877 // Combine any static header libraries into classes-header.jar. If there is only
1878 // one input jar this step will be skipped.
1879 jars = append(jars, deps.staticHeaderJars...)
1880
1881 // we cannot skip the combine step for now if there is only one jar
1882 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1883 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1884 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1885 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001886 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001887
1888 if j.expandJarjarRules != nil {
1889 // Transform classes.jar into classes-jarjar.jar
1890 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001891 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1892 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001893 if ctx.Failed() {
1894 return nil, nil
1895 }
1896 }
1897
Colin Cross3d56ed52021-11-18 22:23:12 -08001898 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001899}
1900
1901func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001902 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001903
1904 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1905 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1906
1907 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1908
1909 j.jacocoReportClassesFile = jacocoReportClassesFile
1910
1911 return instrumentedJar
1912}
1913
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001914type providesTransitiveHeaderJars struct {
1915 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001916 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001917 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001918 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001919}
1920
Colin Crossc85750b2022-04-21 12:50:51 -07001921func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001922 return j.transitiveLibsHeaderJars
1923}
1924
Colin Crossc85750b2022-04-21 12:50:51 -07001925func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001926 return j.transitiveStaticLibsHeaderJars
1927}
1928
1929func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1930 directLibs := android.Paths{}
1931 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001932 transitiveLibs := []*android.DepSet[android.Path]{}
1933 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001934 ctx.VisitDirectDeps(func(module android.Module) {
1935 // don't add deps of the prebuilt version of the same library
1936 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1937 return
1938 }
1939
1940 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001941 tag := ctx.OtherModuleDependencyTag(module)
1942 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1943 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1944 directLibs = append(directLibs, dep.HeaderJars...)
1945 } else if tag == staticLibTag {
1946 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001947 } else {
1948 // Don't propagate transitive libs for other kinds of dependencies.
1949 return
1950 }
1951
1952 if dep.TransitiveLibsHeaderJars != nil {
1953 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1954 }
1955 if dep.TransitiveStaticLibsHeaderJars != nil {
1956 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001957 }
1958 })
1959 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1960 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1961}
1962
Jaewoong Jung26342642021-03-17 15:56:23 -07001963func (j *Module) HeaderJars() android.Paths {
1964 if j.headerJarFile == nil {
1965 return nil
1966 }
1967 return android.Paths{j.headerJarFile}
1968}
1969
1970func (j *Module) ImplementationJars() android.Paths {
1971 if j.implementationJarFile == nil {
1972 return nil
1973 }
1974 return android.Paths{j.implementationJarFile}
1975}
1976
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001977func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001978 return j.dexJarFile
1979}
1980
1981func (j *Module) DexJarInstallPath() android.Path {
1982 return j.installFile
1983}
1984
1985func (j *Module) ImplementationAndResourcesJars() android.Paths {
1986 if j.implementationAndResourcesJar == nil {
1987 return nil
1988 }
1989 return android.Paths{j.implementationAndResourcesJar}
1990}
1991
1992func (j *Module) AidlIncludeDirs() android.Paths {
1993 // exportAidlIncludeDirs is type android.Paths already
1994 return j.exportAidlIncludeDirs
1995}
1996
1997func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1998 return j.classLoaderContexts
1999}
2000
2001// Collect information for opening IDE project files in java/jdeps.go.
2002func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
2003 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2004 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2005 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2006 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
2007 if j.expandJarjarRules != nil {
2008 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
2009 }
Yikef6282022022-04-13 20:41:01 +08002010 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2011 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002012 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002013}
2014
2015func (j *Module) CompilerDeps() []string {
2016 jdeps := []string{}
2017 jdeps = append(jdeps, j.properties.Libs...)
2018 jdeps = append(jdeps, j.properties.Static_libs...)
2019 return jdeps
2020}
2021
2022func (j *Module) hasCode(ctx android.ModuleContext) bool {
2023 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2024 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2025}
2026
2027// Implements android.ApexModule
2028func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2029 return j.depIsInSameApex(ctx, dep)
2030}
2031
2032// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002033func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002034 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002035 minSdkVersion := j.MinSdkVersion(ctx)
2036 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002037 return fmt.Errorf("min_sdk_version is not specified")
2038 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002039 // If the module is compiling against core (via sdk_version), skip comparison check.
2040 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002041 return nil
2042 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002043 if minSdkVersion.GreaterThan(sdkVersion) {
2044 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002045 }
2046 return nil
2047}
2048
2049func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002050 if j.stem == "" {
2051 panic("Stem() called before stem property was set")
2052 }
2053 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002054}
2055
Jaewoong Jung26342642021-03-17 15:56:23 -07002056func (j *Module) JacocoReportClassesFile() android.Path {
2057 return j.jacocoReportClassesFile
2058}
2059
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002060func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2061 var fromDeps []*android.DepSet[android.Path]
2062 ctx.VisitDirectDeps(func(module android.Module) {
2063 tag := ctx.OtherModuleDependencyTag(module)
2064 if tag == staticLibTag {
2065 depInfo := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2066 if depInfo.TransitiveSrcFiles != nil {
2067 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2068 }
2069 }
2070 })
2071
2072 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2073}
2074
Jaewoong Jung26342642021-03-17 15:56:23 -07002075func (j *Module) IsInstallable() bool {
2076 return Bool(j.properties.Installable)
2077}
2078
Yu Liueae7b362023-11-16 17:05:47 -08002079func (j *Module) getTransitiveAconfigFiles(container string) []android.Path {
2080 return j.transitiveAconfigFiles[container].ToList()
Joe Onorato6fe59eb2023-07-16 13:20:33 -07002081}
2082
Jaewoong Jung26342642021-03-17 15:56:23 -07002083type sdkLinkType int
2084
2085const (
2086 // TODO(jiyong) rename these for better readability. Make the allowed
2087 // and disallowed link types explicit
2088 // order is important here. See rank()
2089 javaCore sdkLinkType = iota
2090 javaSdk
2091 javaSystem
2092 javaModule
2093 javaSystemServer
2094 javaPlatform
2095)
2096
2097func (lt sdkLinkType) String() string {
2098 switch lt {
2099 case javaCore:
2100 return "core Java API"
2101 case javaSdk:
2102 return "Android API"
2103 case javaSystem:
2104 return "system API"
2105 case javaModule:
2106 return "module API"
2107 case javaSystemServer:
2108 return "system server API"
2109 case javaPlatform:
2110 return "private API"
2111 default:
2112 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2113 }
2114}
2115
2116// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2117// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2118// can't statically depend on modules that use Platform API.
2119func (lt sdkLinkType) rank() int {
2120 return int(lt)
2121}
2122
2123type moduleWithSdkDep interface {
2124 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002125 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002126}
2127
Jiyong Park92315372021-04-02 08:45:46 +09002128func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002129 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002130 case android.SdkCore.DefaultJavaLibraryName(),
2131 "legacy.core.platform.api.stubs",
2132 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002133 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002134 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002135 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002136 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002137 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002138 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002139 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002140 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002141 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002142 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002143 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002144 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002145 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002146 return javaSystem, true
2147 }
2148
2149 if stub, linkType := moduleStubLinkType(name); stub {
2150 return linkType, true
2151 }
2152
Jiyong Park92315372021-04-02 08:45:46 +09002153 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002154 switch ver.Kind {
2155 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002156 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002157 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002158 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002159 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002160 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002161 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002162 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002163 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002164 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002165 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002166 return javaPlatform, false
2167 }
2168
Jiyong Parkf1691d22021-03-29 20:11:58 +09002169 if !ver.Valid() {
2170 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002171 }
2172 return javaSdk, false
2173}
2174
2175// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2176// this module's. See the comment on rank() for details and an example.
2177func (j *Module) checkSdkLinkType(
2178 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2179 if ctx.Host() {
2180 return
2181 }
2182
Jiyong Park92315372021-04-02 08:45:46 +09002183 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002184 if stubs {
2185 return
2186 }
Jiyong Park92315372021-04-02 08:45:46 +09002187 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002188
2189 if myLinkType.rank() < depLinkType.rank() {
2190 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2191 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2192 "property of the source or target module so that target module is built "+
2193 "with the same or smaller API set when compared to the source.",
2194 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2195 }
2196}
2197
2198func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2199 var deps deps
2200
2201 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002202 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002203 if sdkDep.invalidVersion {
2204 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2205 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2206 } else if sdkDep.useFiles {
2207 // sdkDep.jar is actually equivalent to turbine header.jar.
2208 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002209 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002210 deps.aidlPreprocess = sdkDep.aidl
2211 } else {
2212 deps.aidlPreprocess = sdkDep.aidl
2213 }
2214 }
2215
Jiyong Park92315372021-04-02 08:45:46 +09002216 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002217
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002218 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002219 ctx.VisitDirectDeps(func(module android.Module) {
2220 otherName := ctx.OtherModuleName(module)
2221 tag := ctx.OtherModuleDependencyTag(module)
2222
2223 if IsJniDepTag(tag) {
2224 // Handled by AndroidApp.collectAppDeps
2225 return
2226 }
2227 if tag == certificateTag {
2228 // Handled by AndroidApp.collectAppDeps
2229 return
2230 }
2231
2232 if dep, ok := module.(SdkLibraryDependency); ok {
2233 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002234 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002235 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2236 deps.classpath = append(deps.classpath, depHeaderJars...)
2237 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002238 case staticLibTag:
2239 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2240 }
2241 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2242 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2243 if sdkLinkType != javaPlatform &&
2244 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2245 // dep is a sysprop implementation library, but this module is not linking against
2246 // the platform, so it gets the sysprop public stubs library instead. Replace
2247 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2248 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2249 dep = syspropDep.JavaInfo
2250 }
2251 switch tag {
2252 case bootClasspathTag:
2253 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002254 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002255 if _, ok := module.(*Plugin); ok {
2256 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2257 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002258 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002259 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002260 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2261 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2262 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2263 case java9LibTag:
2264 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2265 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002266 if _, ok := module.(*Plugin); ok {
2267 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2268 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002269 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2270 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2271 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2272 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2273 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2274 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2275 // Turbine doesn't run annotation processors, so any module that uses an
2276 // annotation processor that generates API is incompatible with the turbine
2277 // optimization.
2278 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2279 case pluginTag:
2280 if plugin, ok := module.(*Plugin); ok {
2281 if plugin.pluginProperties.Processor_class != nil {
2282 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2283 } else {
2284 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2285 }
2286 // Turbine doesn't run annotation processors, so any module that uses an
2287 // annotation processor that generates API is incompatible with the turbine
2288 // optimization.
2289 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2290 } else {
2291 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2292 }
2293 case errorpronePluginTag:
2294 if _, ok := module.(*Plugin); ok {
2295 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2296 } else {
2297 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2298 }
2299 case exportedPluginTag:
2300 if plugin, ok := module.(*Plugin); ok {
2301 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2302 if plugin.pluginProperties.Processor_class != nil {
2303 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2304 }
2305 // Turbine doesn't run annotation processors, so any module that uses an
2306 // annotation processor that generates API is incompatible with the turbine
2307 // optimization.
2308 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2309 } else {
2310 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2311 }
2312 case kotlinStdlibTag:
2313 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2314 case kotlinAnnotationsTag:
2315 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002316 case kotlinPluginTag:
2317 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002318 case syspropPublicStubDepTag:
2319 // This is a sysprop implementation library, forward the JavaInfoProvider from
2320 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2321 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2322 JavaInfo: dep,
2323 })
2324 }
2325 } else if dep, ok := module.(android.SourceFileProducer); ok {
2326 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002327 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002328 checkProducesJars(ctx, dep)
2329 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002330 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002331 case staticLibTag:
2332 checkProducesJars(ctx, dep)
2333 deps.classpath = append(deps.classpath, dep.Srcs()...)
2334 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2335 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2336 }
2337 } else {
2338 switch tag {
2339 case bootClasspathTag:
2340 // If a system modules dependency has been added to the bootclasspath
2341 // then add its libs to the bootclasspath.
2342 sm := module.(SystemModulesProvider)
2343 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2344
2345 case systemModulesTag:
2346 if deps.systemModules != nil {
2347 panic("Found two system module dependencies")
2348 }
2349 sm := module.(SystemModulesProvider)
2350 outputDir, outputDeps := sm.OutputDirAndDeps()
2351 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002352
2353 case instrumentationForTag:
2354 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 -07002355 }
2356 }
2357
2358 addCLCFromDep(ctx, module, j.classLoaderContexts)
2359 })
2360
2361 return deps
2362}
2363
2364func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2365 deps.processorPath = append(deps.processorPath, pluginJars...)
2366 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2367}
2368
2369// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2370// this interface.
2371type ProvidesUsesLib interface {
2372 ProvidesUsesLib() *string
2373}
2374
2375func (j *Module) ProvidesUsesLib() *string {
2376 return j.usesLibraryProperties.Provides_uses_lib
2377}
satayev1c564cc2021-05-25 19:50:30 +01002378
2379type ModuleWithStem interface {
2380 Stem() string
2381}
2382
2383var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002384
Chris Parsons637458d2023-09-19 20:09:00 +00002385func (j *Module) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Wei Libafb6d62021-12-10 03:14:59 -08002386 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002387 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002388 if lib, ok := ctx.Module().(*Library); ok {
2389 javaLibraryBp2Build(ctx, lib)
2390 }
2391 case "java_binary_host":
2392 if binary, ok := ctx.Module().(*Binary); ok {
2393 javaBinaryHostBp2Build(ctx, binary)
2394 }
Zi Wang65b36722023-05-23 15:18:33 -07002395 case "java_test_host":
2396 if testHost, ok := ctx.Module().(*TestHost); ok {
2397 javaTestHostBp2Build(ctx, testHost)
2398 }
Chris Parsons39a16972023-06-08 14:28:51 +00002399 default:
2400 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002401 }
Wei Libafb6d62021-12-10 03:14:59 -08002402}