blob: c4b4026208d0daf74d940c72616eab4cd3d6044c [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
Colin Crossd788b3e2023-11-28 13:14:56 -080025 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070026 "github.com/google/blueprint/pathtools"
27 "github.com/google/blueprint/proptools"
28
Yu Liueae7b362023-11-16 17:05:47 -080029 "android/soong/aconfig"
Jaewoong Jung26342642021-03-17 15:56:23 -070030 "android/soong/android"
31 "android/soong/dexpreopt"
32 "android/soong/java/config"
33)
34
35// This file contains the definition and the implementation of the base module that most
36// source-based Java module structs embed.
37
38// TODO:
39// Autogenerated files:
40// Renderscript
41// Post-jar passes:
42// Proguard
43// Rmtypedefs
44// DroidDoc
45// Findbugs
46
47// Properties that are common to most Java modules, i.e. whether it's a host or device module.
48type CommonProperties struct {
49 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
50 // or .aidl files.
51 Srcs []string `android:"path,arch_variant"`
52
53 // list Kotlin of source files containing Kotlin code that should be treated as common code in
54 // a codebase that supports Kotlin multiplatform. See
55 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
56 Common_srcs []string `android:"path,arch_variant"`
57
58 // list of source files that should not be used to build the Java module.
59 // This is most useful in the arch/multilib variants to remove non-common files
60 Exclude_srcs []string `android:"path,arch_variant"`
61
62 // list of directories containing Java resources
63 Java_resource_dirs []string `android:"arch_variant"`
64
65 // list of directories that should be excluded from java_resource_dirs
66 Exclude_java_resource_dirs []string `android:"arch_variant"`
67
68 // list of files to use as Java resources
69 Java_resources []string `android:"path,arch_variant"`
70
71 // list of files that should be excluded from java_resources and java_resource_dirs
72 Exclude_java_resources []string `android:"path,arch_variant"`
73
74 // list of module-specific flags that will be used for javac compiles
75 Javacflags []string `android:"arch_variant"`
76
77 // list of module-specific flags that will be used for kotlinc compiles
78 Kotlincflags []string `android:"arch_variant"`
79
80 // list of java libraries that will be in the classpath
81 Libs []string `android:"arch_variant"`
82
83 // list of java libraries that will be compiled into the resulting jar
84 Static_libs []string `android:"arch_variant"`
85
Jihoon Kang381c2fa2023-06-01 22:17:32 +000086 // list of java libraries that should not be used to build this module
87 Exclude_static_libs []string `android:"arch_variant"`
88
Jaewoong Jung26342642021-03-17 15:56:23 -070089 // manifest file to be included in resulting jar
90 Manifest *string `android:"path"`
91
92 // if not blank, run jarjar using the specified rules file
93 Jarjar_rules *string `android:"path,arch_variant"`
94
95 // If not blank, set the java version passed to javac as -source and -target
96 Java_version *string
97
98 // If set to true, allow this module to be dexed and installed on devices. Has no
99 // effect on host modules, which are always considered installable.
100 Installable *bool
101
102 // If set to true, include sources used to compile the module in to the final jar
103 Include_srcs *bool
104
105 // If not empty, classes are restricted to the specified packages and their sub-packages.
106 // This restriction is checked after applying jarjar rules and including static libs.
107 Permitted_packages []string
108
109 // List of modules to use as annotation processors
110 Plugins []string
111
112 // List of modules to export to libraries that directly depend on this library as annotation
113 // processors. Note that if the plugins set generates_api: true this will disable the turbine
114 // optimization on modules that depend on this module, which will reduce parallelism and cause
115 // more recompilation.
116 Exported_plugins []string
117
118 // The number of Java source entries each Javac instance can process
119 Javac_shard_size *int64
120
121 // Add host jdk tools.jar to bootclasspath
122 Use_tools_jar *bool
123
124 Openjdk9 struct {
125 // List of source files that should only be used when passing -source 1.9 or higher
126 Srcs []string `android:"path"`
127
128 // List of javac flags that should only be used when passing -source 1.9 or higher
129 Javacflags []string
130 }
131
132 // When compiling language level 9+ .java code in packages that are part of
133 // a system module, patch_module names the module that your sources and
134 // dependencies should be patched into. The Android runtime currently
135 // doesn't implement the JEP 261 module system so this option is only
136 // supported at compile time. It should only be needed to compile tests in
137 // packages that exist in libcore and which are inconvenient to move
138 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400139 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700140
141 Jacoco struct {
142 // List of classes to include for instrumentation with jacoco to collect coverage
143 // information at runtime when building with coverage enabled. If unset defaults to all
144 // classes.
145 // Supports '*' as the last character of an entry in the list as a wildcard match.
146 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
147 // it matches classes in the package that have the class name as a prefix.
148 Include_filter []string
149
150 // List of classes to exclude from instrumentation with jacoco to collect coverage
151 // information at runtime when building with coverage enabled. Overrides classes selected
152 // by the include_filter property.
153 // Supports '*' as the last character of an entry in the list as a wildcard match.
154 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
155 // it matches classes in the package that have the class name as a prefix.
156 Exclude_filter []string
157 }
158
159 Errorprone struct {
160 // List of javac flags that should only be used when running errorprone.
161 Javacflags []string
162
163 // List of java_plugin modules that provide extra errorprone checks.
164 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700165
Cole Faust2b1536e2021-06-18 12:25:54 -0700166 // This property can be in 3 states. When set to true, errorprone will
167 // be run during the regular build. When set to false, errorprone will
168 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
169 // environment variable is true. Setting this to false will improve build
170 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700171 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700172 }
173
174 Proto struct {
175 // List of extra options that will be passed to the proto generator.
176 Output_params []string
177 }
178
Sam Delmericoc7593722022-08-31 15:57:52 -0400179 // If true, then jacocoagent is automatically added as a libs dependency so that
180 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700181 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000182 // If true, then the module supports statically including the jacocoagent
183 // into the library.
184 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700185
186 // List of files to include in the META-INF/services folder of the resulting jar.
187 Services []string `android:"path,arch_variant"`
188
189 // If true, package the kotlin stdlib into the jar. Defaults to true.
190 Static_kotlin_stdlib *bool `android:"arch_variant"`
191
192 // A list of java_library instances that provide additional hiddenapi annotations for the library.
193 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700194
195 // Additional srcJars tacked in by GeneratedJavaLibraryModule
196 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000197
198 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400199 Headers_only *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700200}
201
202// Properties that are specific to device modules. Host module factories should not add these when
203// constructing a new module.
204type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000206 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000207 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000208 // 1) numerical API level, "current", "none", or "core_platform"
209 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
210 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
211 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700212 Sdk_version *string
213
214 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000215 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700216 Min_sdk_version *string
217
satayev0a420e72021-11-29 17:25:52 +0000218 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
219 // Defaults to empty string "". See sdk_version for possible values.
220 Max_sdk_version *string
221
William Loh5a082f92022-05-17 20:21:50 +0000222 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
223 // Defaults to empty string "". See sdk_version for possible values.
224 Replace_max_sdk_version_placeholder *string
225
Jaewoong Jung26342642021-03-17 15:56:23 -0700226 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000227 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700228 Target_sdk_version *string
229
230 // Whether to compile against the platform APIs instead of an SDK.
231 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000232 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700233 Platform_apis *bool
234
235 Aidl struct {
236 // Top level directories to pass to aidl tool
237 Include_dirs []string
238
239 // Directories rooted at the Android.bp file to pass to aidl tool
240 Local_include_dirs []string
241
242 // directories that should be added as include directories for any aidl sources of modules
243 // that depend on this module, as well as to aidl for this module.
244 Export_include_dirs []string
245
246 // whether to generate traces (for systrace) for this interface
247 Generate_traces *bool
248
249 // whether to generate Binder#GetTransaction name method.
250 Generate_get_transaction_name *bool
251
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100252 // whether all interfaces should be annotated with required permissions.
253 Enforce_permissions *bool
254
255 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
256 Enforce_permissions_exceptions []string `android:"path"`
257
Jaewoong Jung26342642021-03-17 15:56:23 -0700258 // list of flags that will be passed to the AIDL compiler
259 Flags []string
260 }
261
262 // If true, export a copy of the module as a -hostdex module for host testing.
263 Hostdex *bool
264
265 Target struct {
266 Hostdex struct {
267 // Additional required dependencies to add to -hostdex modules.
268 Required []string
269 }
270 }
271
272 // When targeting 1.9 and above, override the modules to use with --system,
273 // otherwise provides defaults libraries to add to the bootclasspath.
274 System_modules *string
275
Jaewoong Jung26342642021-03-17 15:56:23 -0700276 IsSDKLibrary bool `blueprint:"mutated"`
277
278 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
279 // Defaults to false.
280 V4_signature *bool
281
282 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
283 // public stubs library.
284 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000285
286 HiddenAPIPackageProperties
287 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700288}
289
Jooyung Han01d80d82022-01-08 12:16:32 +0900290// Device properties that can be overridden by overriding module (e.g. override_android_app)
291type OverridableDeviceProperties struct {
292 // set the name of the output. If not set, `name` is used.
293 // To override a module with this property set, overriding module might need to set this as well.
294 // Otherwise, both the overridden and the overriding modules will have the same output name, which
295 // can cause the duplicate output error.
296 Stem *string
297}
298
Jaewoong Jung26342642021-03-17 15:56:23 -0700299// Functionality common to Module and Import
300//
301// It is embedded in Module so its functionality can be used by methods in Module
302// but it is currently only initialized by Import and Library.
303type embeddableInModuleAndImport struct {
304
305 // Functionality related to this being used as a component of a java_sdk_library.
306 EmbeddableSdkLibraryComponent
307}
308
Paul Duffin71b33cc2021-06-23 11:39:47 +0100309func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
310 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700311}
312
313// Module/Import's DepIsInSameApex(...) delegates to this method.
314//
315// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
316// the one provided by ApexModuleBase.
317func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
318 // dependencies other than the static linkage are all considered crossing APEX boundary
319 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
320 return true
321 }
322 return false
323}
324
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100325// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
326// or an invalid path describing the reason it is invalid.
327//
328// It is unset if a dex jar isn't applicable, i.e. no build rule has been
329// requested to create one.
330//
331// If a dex jar has been requested to be built then it is set, and it may be
332// either a valid android.Path, or invalid with a reason message. The latter
333// happens if the source that should produce the dex file isn't able to.
334//
335// E.g. it is invalid with a reason message if there is a prebuilt APEX that
336// could produce the dex jar through a deapexer module, but the APEX isn't
337// installable so doing so wouldn't be safe.
338type OptionalDexJarPath struct {
339 isSet bool
340 path android.OptionalPath
341}
342
343// IsSet returns true if a path has been set, either invalid or valid.
344func (o OptionalDexJarPath) IsSet() bool {
345 return o.isSet
346}
347
348// Valid returns true if there is a path that is valid.
349func (o OptionalDexJarPath) Valid() bool {
350 return o.isSet && o.path.Valid()
351}
352
353// Path returns the valid path, or panics if it's either not set or is invalid.
354func (o OptionalDexJarPath) Path() android.Path {
355 if !o.isSet {
356 panic("path isn't set")
357 }
358 return o.path.Path()
359}
360
361// PathOrNil returns the path if it's set and valid, or else nil.
362func (o OptionalDexJarPath) PathOrNil() android.Path {
363 if o.Valid() {
364 return o.Path()
365 }
366 return nil
367}
368
369// InvalidReason returns the reason for an invalid path, which is never "". It
370// returns "" for an unset or valid path.
371func (o OptionalDexJarPath) InvalidReason() string {
372 if !o.isSet {
373 return ""
374 }
375 return o.path.InvalidReason()
376}
377
378func (o OptionalDexJarPath) String() string {
379 if !o.isSet {
380 return "<unset>"
381 }
382 return o.path.String()
383}
384
385// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
386func makeUnsetDexJarPath() OptionalDexJarPath {
387 return OptionalDexJarPath{isSet: false}
388}
389
390// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
391// the given OptionalPath, which may be valid or invalid.
392func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
393 return OptionalDexJarPath{isSet: true, path: path}
394}
395
396// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
397// valid given path. It returns an unset OptionalDexJarPath if the given path is
398// nil.
399func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
400 if path == nil {
401 return makeUnsetDexJarPath()
402 }
403 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
404}
405
Jaewoong Jung26342642021-03-17 15:56:23 -0700406// Module contains the properties and members used by all java module types
407type Module struct {
408 android.ModuleBase
409 android.DefaultableModuleBase
410 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800411 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700412
413 // Functionality common to Module and Import.
414 embeddableInModuleAndImport
415
416 properties CommonProperties
417 protoProperties android.ProtoProperties
418 deviceProperties DeviceProperties
419
Jooyung Han01d80d82022-01-08 12:16:32 +0900420 overridableDeviceProperties OverridableDeviceProperties
421
Jaewoong Jung26342642021-03-17 15:56:23 -0700422 // jar file containing header classes including static library dependencies, suitable for
423 // inserting into the bootclasspath/classpath of another compile
424 headerJarFile android.Path
425
426 // jar file containing implementation classes including static library dependencies but no
427 // resources
428 implementationJarFile android.Path
429
430 // jar file containing only resources including from static library dependencies
431 resourceJar android.Path
432
433 // args and dependencies to package source files into a srcjar
434 srcJarArgs []string
435 srcJarDeps android.Paths
436
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000437 // the source files of this module and all its static dependencies
438 transitiveSrcFiles *android.DepSet[android.Path]
439
Jaewoong Jung26342642021-03-17 15:56:23 -0700440 // jar file containing implementation classes and resources including static library
441 // dependencies
442 implementationAndResourcesJar android.Path
443
444 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100445 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700446
447 // output file containing uninstrumented classes that will be instrumented by jacoco
448 jacocoReportClassesFile android.Path
449
450 // output file of the module, which may be a classes jar or a dex jar
451 outputFile android.Path
452 extraOutputFiles android.Paths
453
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100454 exportAidlIncludeDirs android.Paths
455 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700456
457 logtagsSrcs android.Paths
458
459 // installed file for binary dependency
460 installFile android.Path
461
Colin Cross3108ce12021-11-10 14:38:50 -0800462 // installed file for hostdex copy
463 hostdexInstallFile android.InstallPath
464
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800465 // list of unique .java and .kt source files
466 uniqueSrcFiles android.Paths
467
468 // list of srcjars that was passed to javac
469 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700470
471 // manifest file to use instead of properties.Manifest
472 overrideManifest android.OptionalPath
473
Jaewoong Jung26342642021-03-17 15:56:23 -0700474 // list of plugins that this java module is exporting
475 exportedPluginJars android.Paths
476
477 // list of plugins that this java module is exporting
478 exportedPluginClasses []string
479
480 // if true, the exported plugins generate API and require disabling turbine.
481 exportedDisableTurbine bool
482
483 // list of source files, collected from srcFiles with unique java and all kt files,
484 // will be used by android.IDEInfo struct
485 expandIDEInfoCompiledSrcs []string
486
487 // expanded Jarjar_rules
488 expandJarjarRules android.Path
489
Jaewoong Jung26342642021-03-17 15:56:23 -0700490 // Extra files generated by the module type to be added as java resources.
491 extraResources android.Paths
492
493 hiddenAPI
494 dexer
495 dexpreopter
496 usesLibrary
497 linter
498
499 // list of the xref extraction files
500 kytheFiles android.Paths
501
Jaewoong Jung26342642021-03-17 15:56:23 -0700502 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900503
504 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000505 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000506 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400507
508 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000509
510 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000511
512 // output file name based on Stem property.
513 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
514 // or the module should override Stem().
515 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700516
Colin Crossd788b3e2023-11-28 13:14:56 -0800517 // Single aconfig "cache file" merged from this module and all dependencies.
518 mergedAconfigFiles map[string]android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700519}
520
Jiyong Park92315372021-04-02 08:45:46 +0900521func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
522 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900523 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700524 return nil
525 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900526 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000527 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700528 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
529 } else {
530 // Treat stable core platform as stable.
531 return nil
532 }
533 } else {
534 return fmt.Errorf("non stable SDK %v", sdkVersion)
535 }
536}
537
538// checkSdkVersions enforces restrictions around SDK dependencies.
539func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
540 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900541 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900542 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700543 ctx.PropertyErrorf("sdk_version",
544 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
545 }
546 }
547 }
548
549 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
550 // See rank() for details.
551 ctx.VisitDirectDeps(func(module android.Module) {
552 tag := ctx.OtherModuleDependencyTag(module)
553 switch module.(type) {
554 // TODO(satayev): cover other types as well, e.g. imports
555 case *Library, *AndroidLibrary:
556 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400557 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700558 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
559 }
560 }
561 })
562}
563
564func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900565 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700566 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900567 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700568 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000569 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 -0700570 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000571 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 -0700572 }
573
574 }
575}
576
Mark Whitea15790a2023-08-22 21:28:11 +0000577func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
578 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400579 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000580 installable := proptools.Bool(j.properties.Installable)
581
582 if headersOnly && installable {
583 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.")
584 }
585 }
586}
587
Jaewoong Jung26342642021-03-17 15:56:23 -0700588func (j *Module) addHostProperties() {
589 j.AddProperties(
590 &j.properties,
591 &j.protoProperties,
592 &j.usesLibraryProperties,
593 )
594}
595
596func (j *Module) addHostAndDeviceProperties() {
597 j.addHostProperties()
598 j.AddProperties(
599 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900600 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700601 &j.dexer.dexProperties,
602 &j.dexpreoptProperties,
603 &j.linter.properties,
604 )
605}
606
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000607// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
608// makes it available through the hiddenAPIPropertyInfoProvider.
609func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
610 hiddenAPIInfo := newHiddenAPIPropertyInfo()
611
612 // Populate with flag file paths from the properties.
613 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
614
615 // Populate with package rules from the properties.
616 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
617
618 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
619}
620
Jaewoong Jung26342642021-03-17 15:56:23 -0700621func (j *Module) OutputFiles(tag string) (android.Paths, error) {
622 switch tag {
623 case "":
624 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
625 case android.DefaultDistTag:
626 return android.Paths{j.outputFile}, nil
627 case ".jar":
628 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700629 case ".hjar":
630 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700631 case ".proguard_map":
632 if j.dexer.proguardDictionary.Valid() {
633 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
634 }
635 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700636 case ".generated_srcjars":
637 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000638 case ".lint":
639 if j.linter.outputs.xml != nil {
640 return android.Paths{j.linter.outputs.xml}, nil
641 }
642 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700643 default:
644 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
645 }
646}
647
648var _ android.OutputFileProducer = (*Module)(nil)
649
650func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
651 initJavaModule(module, hod, false)
652}
653
654func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
655 initJavaModule(module, hod, true)
656}
657
658func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
659 multilib := android.MultilibCommon
660 if multiTargets {
661 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
662 } else {
663 android.InitAndroidArchModule(module, hod, multilib)
664 }
665 android.InitDefaultableModule(module)
666}
667
668func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
669 return j.properties.Instrument &&
670 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
671 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
672}
673
674func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000675 return j.properties.Supports_static_instrumentation &&
676 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700677 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
678 ctx.Config().UnbundledBuild())
679}
680
681func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
682 // Force enable the instrumentation for java code that is built for APEXes ...
683 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
684 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
685 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
686 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
687 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
688 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
689 return true
690 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
691 return true
692 }
693 }
694 return false
695}
696
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400697func (j *Module) setInstrument(value bool) {
698 j.properties.Instrument = value
699}
700
Jiyong Park92315372021-04-02 08:45:46 +0900701func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
702 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700703}
704
Jiyong Parkf1691d22021-03-29 20:11:58 +0900705func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700706 return proptools.String(j.deviceProperties.System_modules)
707}
708
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000709func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700710 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000711 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700712 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000713 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700714}
715
Yu Liuf2b94012023-09-19 15:09:10 -0700716func (j *Module) GetDeviceProperties() *DeviceProperties {
717 return &j.deviceProperties
718}
719
Spandan Dasa26eda72023-03-02 00:56:06 +0000720func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
721 if j.deviceProperties.Max_sdk_version != nil {
722 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
723 }
724 // Default is PrivateApiLevel
725 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000726}
727
Spandan Dasa26eda72023-03-02 00:56:06 +0000728func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
729 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
730 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
731 }
732 // Default is PrivateApiLevel
733 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000734}
735
Jiyong Parkf1691d22021-03-29 20:11:58 +0900736func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000737 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900738}
739
Spandan Dasca70fc42023-03-01 23:38:49 +0000740func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900741 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000742 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900743 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000744 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700745}
746
747func (j *Module) AvailableFor(what string) bool {
748 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
749 // Exception: for hostdex: true libraries, the platform variant is created
750 // even if it's not marked as available to platform. In that case, the platform
751 // variant is used only for the hostdex and not installed to the device.
752 return true
753 }
754 return j.ApexModuleBase.AvailableFor(what)
755}
756
757func (j *Module) deps(ctx android.BottomUpMutatorContext) {
758 if ctx.Device() {
759 j.linter.deps(ctx)
760
Jiyong Parkf1691d22021-03-29 20:11:58 +0900761 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700762
763 if j.deviceProperties.SyspropPublicStub != "" {
764 // This is a sysprop implementation library that has a corresponding sysprop public
765 // stubs library, and a dependency on it so that dependencies on the implementation can
766 // be forwarded to the public stubs library when necessary.
767 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
768 }
769 }
770
771 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000772
773 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700774 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
775
776 // Add dependency on libraries that provide additional hidden api annotations.
777 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
778
779 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
780 // Require java_sdk_library at inter-partition java dependency to ensure stable
781 // interface between partitions. If inter-partition java_library dependency is detected,
782 // raise build error because java_library doesn't have a stable interface.
783 //
784 // Inputs:
785 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
786 // if true, enable enforcement
787 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
788 // exception list of java_library names to allow inter-partition dependency
789 for idx := range j.properties.Libs {
790 if libDeps[idx] == nil {
791 continue
792 }
793
794 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
795 // java_sdk_library is always allowed at inter-partition dependency.
796 // So, skip check.
797 if _, ok := javaDep.(*SdkLibrary); ok {
798 continue
799 }
800
801 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
802 }
803 }
804 }
805
806 // For library dependencies that are component libraries (like stubs), add the implementation
807 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
808 for _, dep := range libDeps {
809 if dep != nil {
810 if component, ok := dep.(SdkLibraryComponentDependency); ok {
811 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100812 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100813 tag := usesLibReqTag
814 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
815 tag = usesLibOptTag
816 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100817 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700818 }
819 }
820 }
821 }
822
823 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
824 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
825 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
826
827 android.ProtoDeps(ctx, &j.protoProperties)
828 if j.hasSrcExt(".proto") {
829 protoDeps(ctx, &j.protoProperties)
830 }
831
832 if j.hasSrcExt(".kt") {
833 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
834 // Kotlin files
835 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
836 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700837 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700838 }
839
840 // Framework libraries need special handling in static coverage builds: they should not have
841 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
842 // the same jacoco classes coming from different bootclasspath jars.
843 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
844 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
845 j.properties.Instrument = true
846 }
847 } else if j.shouldInstrumentStatic(ctx) {
848 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
849 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700850
851 if j.useCompose() {
852 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
853 "androidx.compose.compiler_compiler-hosted")
854 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700855}
856
857func hasSrcExt(srcs []string, ext string) bool {
858 for _, src := range srcs {
859 if filepath.Ext(src) == ext {
860 return true
861 }
862 }
863
864 return false
865}
866
867func (j *Module) hasSrcExt(ext string) bool {
868 return hasSrcExt(j.properties.Srcs, ext)
869}
870
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100871func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
872 var flags string
873
874 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
875 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
876 flags = "-Wmissing-permission-annotation -Werror"
877 }
878 }
879 return flags
880}
881
Jaewoong Jung26342642021-03-17 15:56:23 -0700882func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000883 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700884
885 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
886 aidlIncludes = append(aidlIncludes,
887 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
888 aidlIncludes = append(aidlIncludes,
889 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
890
891 var flags []string
892 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000893 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700894
895 flags = append(flags, j.deviceProperties.Aidl.Flags...)
896
897 if aidlPreprocess.Valid() {
898 flags = append(flags, "-p"+aidlPreprocess.String())
899 deps = append(deps, aidlPreprocess.Path())
900 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000901 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700902 }
903
904 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000905 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700906 }
907
908 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000909 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700910 }
911
Sam Delmerico2351eac2022-05-24 17:10:02 +0000912 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700913 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000914 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700915 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000916 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
917 // add flags for dirs containing AIDL srcs that haven't been specified yet
918 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700919
Zim8774ae12022-08-17 11:46:34 +0100920 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000921 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100922 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700923 flags = append(flags, "-t")
924 }
925
926 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
927 flags = append(flags, "--transaction_names")
928 }
929
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100930 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
931 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
932 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
933 }
934
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000935 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900936 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
937
Jaewoong Jung26342642021-03-17 15:56:23 -0700938 return strings.Join(flags, " "), deps
939}
940
941func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
942
943 var flags javaBuilderFlags
944
945 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900946 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700947
Cole Faust2b1536e2021-06-18 12:25:54 -0700948 epEnabled := j.properties.Errorprone.Enabled
949 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100950 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700951 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
952 }
953
954 errorProneFlags := []string{
955 "-Xplugin:ErrorProne",
956 "${config.ErrorProneChecks}",
957 }
958 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
959
Colin Cross8bf6cad2022-02-28 13:07:03 -0800960 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700961 "'" + strings.Join(errorProneFlags, " ") + "'"
962 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
963 }
964
965 // classpath
966 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
967 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700968 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700969 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
970 flags.processorPath = append(flags.processorPath, deps.processorPath...)
971 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
972
973 flags.processors = append(flags.processors, deps.processorClasses...)
974 flags.processors = android.FirstUniqueStrings(flags.processors)
975
976 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900977 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700978 // Give host-side tools a version of OpenJDK's standard libraries
979 // close to what they're targeting. As of Dec 2017, AOSP is only
980 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
981 //
982 // When building with OpenJDK 8, the following should have no
983 // effect since those jars would be available by default.
984 //
985 // When building with OpenJDK 9 but targeting a version < 1.8,
986 // putting them on the bootclasspath means that:
987 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
988 // b) references to existing APIs are not reinterpreted in an
989 // OpenJDK 9-specific way, eg. calls to subclasses of
990 // java.nio.Buffer as in http://b/70862583
991 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
992 flags.bootClasspath = append(flags.bootClasspath,
993 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
994 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
995 if Bool(j.properties.Use_tools_jar) {
996 flags.bootClasspath = append(flags.bootClasspath,
997 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
998 }
999 }
1000
1001 // systemModules
1002 flags.systemModules = deps.systemModules
1003
Jaewoong Jung26342642021-03-17 15:56:23 -07001004 return flags
1005}
1006
1007func (j *Module) collectJavacFlags(
1008 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1009 // javac flags.
1010 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001011 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001012
Mythri Alle4b9f6182023-10-25 15:17:11 +00001013 needsDebugInfo = false
1014 for _, flag := range javacFlags {
1015 if strings.HasPrefix(flag, "-g") {
1016 needsDebugInfo = true
1017 }
1018 }
1019
1020 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001021 // For non-host binaries, override the -g flag passed globally to remove
1022 // local variable debug info to reduce disk and memory usage.
1023 javacFlags = append(javacFlags, "-g:source,lines")
1024 }
1025 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1026
1027 if flags.javaVersion.usesJavaModules() {
1028 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001029 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1030 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1031 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1032 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001033
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001034 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001035 if j.properties.Patch_module != nil {
1036 // Manually specify build directory in case it is not under the repo root.
1037 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1038 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001039 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001040
1041 // b/150878007
1042 //
1043 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1044 // execution root for --patch-module. If this javac command line is
1045 // invoked within Bazel's execution root working directory, the top
1046 // level directories (e.g. libcore/, tools/, frameworks/) are all
1047 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1048 // --patch-module to fail source file lookups when invoked in the
1049 // execution root.
1050 //
1051 // Short of patching javac or enumerating *all* directories as possible
1052 // input dirs, manually add the top level dir of the source files to be
1053 // compiled.
1054 topLevelDirs := map[string]bool{}
1055 for _, srcFilePath := range srcFiles {
1056 srcFileParts := strings.Split(srcFilePath.String(), "/")
1057 // Ignore source files that are already in the top level directory
1058 // as well as generated files in the out directory. The out
1059 // directory may be an absolute path, which means srcFileParts[0] is the
1060 // empty string, so check that as well. Note that "out" in Bazel's execution
1061 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1062 // anyway, so it's fine to not apply this workaround for generated
1063 // source files.
1064 if len(srcFileParts) > 1 &&
1065 srcFileParts[0] != "" &&
1066 srcFileParts[0] != "out" {
1067 topLevelDirs[srcFileParts[0]] = true
1068 }
1069 }
Cole Faust18994c72023-02-28 16:02:16 -08001070 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001071
1072 classPath := flags.classpath.FormJavaClassPath("")
1073 if classPath != "" {
1074 patchPaths = append(patchPaths, classPath)
1075 }
1076 javacFlags = append(
1077 javacFlags,
1078 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1079 }
1080 }
1081
1082 if len(javacFlags) > 0 {
1083 // optimization.
1084 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1085 flags.javacFlags = "$javacFlags"
1086 }
1087
1088 return flags
1089}
1090
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001091func (j *Module) AddJSONData(d *map[string]interface{}) {
1092 (&j.ModuleBase).AddJSONData(d)
1093 (*d)["Java"] = map[string]interface{}{
1094 "SourceExtensions": j.sourceExtensions,
1095 }
1096
1097}
1098
usta0391ca42023-09-19 15:51:59 -04001099func (j *Module) addGeneratedSrcJars(path android.Path) {
1100 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001101}
1102
Colin Cross4eae06d2023-06-20 22:40:02 -07001103func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001104 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1105
1106 deps := j.collectDeps(ctx)
1107 flags := j.collectBuilderFlags(ctx, deps)
1108
1109 if flags.javaVersion.usesJavaModules() {
1110 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001111 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1112 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1113 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001114 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001115
Jaewoong Jung26342642021-03-17 15:56:23 -07001116 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001117 j.sourceExtensions = []string{}
1118 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1119 if hasSrcExt(srcFiles.Strings(), ext) {
1120 j.sourceExtensions = append(j.sourceExtensions, ext)
1121 }
1122 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001123 if hasSrcExt(srcFiles.Strings(), ".proto") {
1124 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1125 }
1126
1127 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1128 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1129 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1130 }
1131
Sam Delmerico2351eac2022-05-24 17:10:02 +00001132 aidlSrcs := srcFiles.FilterByExt(".aidl")
1133 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1134
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001135 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001136 srcFiles = j.genSources(ctx, srcFiles, flags)
1137
1138 // Collect javac flags only after computing the full set of srcFiles to
1139 // ensure that the --patch-module lookup paths are complete.
1140 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1141
1142 srcJars := srcFiles.FilterByExt(".srcjar")
1143 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001144 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001145 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001146 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001147
1148 if j.properties.Jarjar_rules != nil {
1149 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1150 }
1151
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001152 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001153
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001154 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001155 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001156 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001157 if _, found := set[v.String()]; !found {
1158 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001159 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 }
1161 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001162 var uniqueKtFiles android.Paths
1163 for _, v := range srcFiles.FilterByExt(".kt") {
1164 if _, found := set[v.String()]; !found {
1165 set[v.String()] = true
1166 uniqueKtFiles = append(uniqueKtFiles, v)
1167 }
1168 }
1169
1170 var uniqueSrcFiles android.Paths
1171 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1172 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1173 j.uniqueSrcFiles = uniqueSrcFiles
Aditya Choudhary26df39f2023-11-29 16:42:42 +00001174 ctx.SetProvider(blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001175
Colin Crossb5db4012022-03-28 17:12:39 -07001176 // We don't currently run annotation processors in turbine, which means we can't use turbine
1177 // generated header jars when an annotation processor that generates API is enabled. One
1178 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1179 // is used to run all of the annotation processors.
1180 disableTurbine := deps.disableTurbine
1181
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001182 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1184
1185 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001186 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001187
Colin Cross4eae06d2023-06-20 22:40:02 -07001188 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1189 // any dependencies so that it can override any non-final R classes from dependencies with the
1190 // final R classes from the app.
1191 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1192
Mark Whitea15790a2023-08-22 21:28:11 +00001193 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001194 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001195 if srcFiles.HasExt(".kt") {
1196 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1197 }
1198 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1199 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1200 }
1201
1202 _, j.headerJarFile =
1203 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1204 extraCombinedJars)
1205 if ctx.Failed() {
1206 return
1207 }
1208
1209 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1210 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1211 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1212 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1213 AidlIncludeDirs: j.exportAidlIncludeDirs,
1214 ExportedPlugins: j.exportedPluginJars,
1215 ExportedPluginClasses: j.exportedPluginClasses,
1216 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1217 })
1218
1219 j.outputFile = j.headerJarFile
1220 return
1221 }
1222
Jaewoong Jung26342642021-03-17 15:56:23 -07001223 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001224 // When using kotlin sources turbine is used to generate annotation processor sources,
1225 // including for annotation processors that generate API, so we can use turbine for
1226 // java sources too.
1227 disableTurbine = false
1228
Jaewoong Jung26342642021-03-17 15:56:23 -07001229 // user defined kotlin flags.
1230 kotlincFlags := j.properties.Kotlincflags
1231 CheckKotlincFlags(ctx, kotlincFlags)
1232
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001233 // Workaround for KT-46512
1234 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001235
1236 // If there are kotlin files, compile them first but pass all the kotlin and java files
1237 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1238 // won't emit any classes for them.
1239 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1240 if ctx.Device() {
1241 kotlincFlags = append(kotlincFlags, "-no-jdk")
1242 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001243
1244 for _, plugin := range deps.kotlinPlugins {
1245 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1246 }
1247 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1248
Jaewoong Jung26342642021-03-17 15:56:23 -07001249 if len(kotlincFlags) > 0 {
1250 // optimization.
1251 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1252 flags.kotlincFlags += "$kotlincFlags"
1253 }
1254
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001255 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001256 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1257
1258 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1259 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1260
1261 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1262 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1263
Isaac Chioua23d9942022-04-06 06:14:38 +00001264 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001265 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001266 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1267 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001268 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001269 srcJars = append(srcJars, kaptSrcJar)
1270 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001271 // Disable annotation processing in javac, it's already been handled by kapt
1272 flags.processorPath = nil
1273 flags.processors = nil
1274 }
1275
1276 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001277 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001278 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001279 if ctx.Failed() {
1280 return
1281 }
1282
Isaac Chioua23d9942022-04-06 06:14:38 +00001283 // Make javac rule depend on the kotlinc rule
1284 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1285
Jaewoong Jung26342642021-03-17 15:56:23 -07001286 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001287 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1288
Jaewoong Jung26342642021-03-17 15:56:23 -07001289 // Jar kotlin classes into the final jar after javac
1290 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1291 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001292 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001293 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001294 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001295 } else {
1296 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001297 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001298 }
1299 }
1300
1301 jars := append(android.Paths(nil), kotlinJars...)
1302
Jaewoong Jung26342642021-03-17 15:56:23 -07001303 j.compiledSrcJars = srcJars
1304
1305 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001306 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001307 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001308 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1309 enableSharding = true
1310 // Formerly, there was a check here that prevented annotation processors
1311 // from being used when sharding was enabled, as some annotation processors
1312 // do not function correctly in sharded environments. It was removed to
1313 // allow for the use of annotation processors that do function correctly
1314 // with sharding enabled. See: b/77284273.
1315 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001316 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001317 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001318 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001319 if ctx.Failed() {
1320 return
1321 }
1322 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001323 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001324 hasErrorproneableFiles := false
1325 for _, ext := range j.sourceExtensions {
1326 if ext != ".proto" && ext != ".aidl" {
1327 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1328 // compile, and it's not useful to have warnings on these generated sources.
1329 hasErrorproneableFiles = true
1330 break
1331 }
1332 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001333 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001334 if Bool(j.properties.Errorprone.Enabled) {
1335 // If error-prone is enabled, enable errorprone flags on the regular
1336 // build.
1337 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001338 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001339 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1340 // a new jar file just for compiling with the errorprone compiler to.
1341 // This is because we don't want to cause the java files to get completely
1342 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1343 // We also don't want to run this if errorprone is enabled by default for
1344 // this module, or else we could have duplicated errorprone messages.
1345 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001346 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001347 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001348
Vadim Spivak3c496f02023-06-08 06:14:59 +00001349 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001350 "errorprone", "errorprone")
1351
Jaewoong Jung26342642021-03-17 15:56:23 -07001352 extraJarDeps = append(extraJarDeps, errorprone)
1353 }
1354
1355 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001356 if headerJarFileWithoutDepsOrJarjar != nil {
1357 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1358 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001359 shardSize := int(*(j.properties.Javac_shard_size))
1360 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001361 if len(uniqueJavaFiles) > 0 {
1362 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001363 for idx, shardSrc := range shardSrcs {
1364 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1365 nil, flags, extraJarDeps)
1366 jars = append(jars, classes)
1367 }
1368 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001369 // Assume approximately 5 sources per srcjar.
1370 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1371 // 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 -07001372 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001373 startIdx := len(shardSrcs)
1374 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1375 for idx, shardSrcJars := range shardSrcJarsList {
1376 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1377 nil, shardSrcJars, flags, extraJarDeps)
1378 jars = append(jars, classes)
1379 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001380 }
1381 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001382 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001383 jars = append(jars, classes)
1384 }
1385 if ctx.Failed() {
1386 return
1387 }
1388 }
1389
1390 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1391
1392 var includeSrcJar android.WritablePath
1393 if Bool(j.properties.Include_srcs) {
1394 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1395 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1396 }
1397
1398 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1399 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1400 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1401 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1402
1403 var resArgs []string
1404 var resDeps android.Paths
1405
1406 resArgs = append(resArgs, dirArgs...)
1407 resDeps = append(resDeps, dirDeps...)
1408
1409 resArgs = append(resArgs, fileArgs...)
1410 resDeps = append(resDeps, fileDeps...)
1411
1412 resArgs = append(resArgs, extraArgs...)
1413 resDeps = append(resDeps, extraDeps...)
1414
1415 if len(resArgs) > 0 {
1416 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1417 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1418 j.resourceJar = resourceJar
1419 if ctx.Failed() {
1420 return
1421 }
1422 }
1423
1424 var resourceJars android.Paths
1425 if j.resourceJar != nil {
1426 resourceJars = append(resourceJars, j.resourceJar)
1427 }
1428 if Bool(j.properties.Include_srcs) {
1429 resourceJars = append(resourceJars, includeSrcJar)
1430 }
1431 resourceJars = append(resourceJars, deps.staticResourceJars...)
1432
1433 if len(resourceJars) > 1 {
1434 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1435 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1436 false, nil, nil)
1437 j.resourceJar = combinedJar
1438 } else if len(resourceJars) == 1 {
1439 j.resourceJar = resourceJars[0]
1440 }
1441
1442 if len(deps.staticJars) > 0 {
1443 jars = append(jars, deps.staticJars...)
1444 }
1445
1446 manifest := j.overrideManifest
1447 if !manifest.Valid() && j.properties.Manifest != nil {
1448 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1449 }
1450
1451 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1452 if len(services) > 0 {
1453 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1454 var zipargs []string
1455 for _, file := range services {
1456 serviceFile := file.String()
1457 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1458 }
1459 rule := zip
1460 args := map[string]string{
1461 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1462 }
1463 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1464 rule = zipRE
1465 args["implicits"] = strings.Join(services.Strings(), ",")
1466 }
1467 ctx.Build(pctx, android.BuildParams{
1468 Rule: rule,
1469 Output: servicesJar,
1470 Implicits: services,
1471 Args: args,
1472 })
1473 jars = append(jars, servicesJar)
1474 }
1475
Colin Cross4eae06d2023-06-20 22:40:02 -07001476 jars = append(android.CopyOf(extraCombinedJars), jars...)
1477
Jaewoong Jung26342642021-03-17 15:56:23 -07001478 // Combine the classes built from sources, any manifests, and any static libraries into
1479 // classes.jar. If there is only one input jar this step will be skipped.
1480 var outputFile android.OutputPath
1481
1482 if len(jars) == 1 && !manifest.Valid() {
1483 // Optimization: skip the combine step as there is nothing to do
1484 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1485 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1486 // any if len(jars) == 1.
1487
Jihoon Kang1147b312023-06-08 23:25:57 +00001488 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1489 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1490 // either with .from-source or .from-text suffix.
1491 // outputFile should be agnostic to the build configuration,
1492 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1493 // to the copy rules.
1494 stub, _ := moduleStubLinkType(ctx.ModuleName())
1495
Jaewoong Jung26342642021-03-17 15:56:23 -07001496 // Transform the single path to the jar into an OutputPath as that is required by the following
1497 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001498 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001499 // The path contains an embedded OutputPath so reuse that.
1500 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001501 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001502 // The path is an OutputPath so reuse it directly.
1503 outputFile = outputPath
1504 } else {
1505 // The file is not in the out directory so create an OutputPath into which it can be copied
1506 // and which the following code can use to refer to it.
1507 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1508 ctx.Build(pctx, android.BuildParams{
1509 Rule: android.Cp,
1510 Input: jars[0],
1511 Output: combinedJar,
1512 })
1513 outputFile = combinedJar.OutputPath
1514 }
1515 } else {
1516 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1517 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1518 false, nil, nil)
1519 outputFile = combinedJar.OutputPath
1520 }
1521
1522 // jarjar implementation jar if necessary
1523 if j.expandJarjarRules != nil {
1524 // Transform classes.jar into classes-jarjar.jar
1525 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1526 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1527 outputFile = jarjarFile
1528
1529 // jarjar resource jar if necessary
1530 if j.resourceJar != nil {
1531 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1532 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1533 j.resourceJar = resourceJarJarFile
1534 }
1535
1536 if ctx.Failed() {
1537 return
1538 }
1539 }
1540
1541 // Check package restrictions if necessary.
1542 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001543 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001544 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001545
1546 // Create a rule to copy the output jar to another path and add a validate dependency that
1547 // will check that the jar only contains the permitted packages. The new location will become
1548 // the output file of this module.
1549 inputFile := outputFile
1550 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1551 ctx.Build(pctx, android.BuildParams{
1552 Rule: android.Cp,
1553 Input: inputFile,
1554 Output: outputFile,
1555 // Make sure that any dependency on the output file will cause ninja to run the package check
1556 // rule.
1557 Validation: pkgckFile,
1558 })
1559
1560 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001561 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001562
1563 if ctx.Failed() {
1564 return
1565 }
1566 }
1567
1568 j.implementationJarFile = outputFile
1569 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001570 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1571 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1572 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1573 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1574 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1575 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1576 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001577 }
1578
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001579 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1580 specs := j.jacocoModuleToZipCommand(ctx)
1581 if ctx.Failed() {
1582 return
1583 }
1584
Jaewoong Jung26342642021-03-17 15:56:23 -07001585 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001586 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001587 }
1588
1589 // merge implementation jar with resources if necessary
1590 implementationAndResourcesJar := outputFile
1591 if j.resourceJar != nil {
1592 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1593 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1594 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1595 false, nil, nil)
1596 implementationAndResourcesJar = combinedJar
1597 }
1598
1599 j.implementationAndResourcesJar = implementationAndResourcesJar
1600
1601 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001602 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1604 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001605 if compileDex == nil {
1606 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001607 }
1608 if j.deviceProperties.Hostdex == nil {
1609 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1610 }
1611 }
1612
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001613 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001614 if j.hasCode(ctx) {
1615 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001616 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001617 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1618 }
1619 // Dex compilation
1620 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001621 params := &compileDexParams{
1622 flags: flags,
1623 sdkVersion: j.SdkVersion(ctx),
1624 minSdkVersion: j.MinSdkVersion(ctx),
1625 classesJar: implementationAndResourcesJar,
1626 jarName: jarName,
1627 }
1628 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001629 if ctx.Failed() {
1630 return
1631 }
1632
Jaewoong Jung26342642021-03-17 15:56:23 -07001633 // merge dex jar with resources if necessary
1634 if j.resourceJar != nil {
1635 jars := android.Paths{dexOutputFile, j.resourceJar}
1636 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1637 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1638 false, nil, nil)
1639 if *j.dexProperties.Uncompress_dex {
1640 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001641 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001642 dexOutputFile = combinedAlignedJar
1643 } else {
1644 dexOutputFile = combinedJar
1645 }
1646 }
1647
Paul Duffin4de94502021-05-16 05:21:16 +01001648 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001649
1650 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001651
1652 // Encode hidden API flags in dex file, if needed.
1653 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1654
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001655 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001656
1657 // Dexpreopting
1658 j.dexpreopt(ctx, dexOutputFile)
1659
1660 outputFile = dexOutputFile
1661 } else {
1662 // There is no code to compile into a dex jar, make sure the resources are propagated
1663 // to the APK if this is an app.
1664 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001665 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001666 }
1667
1668 if ctx.Failed() {
1669 return
1670 }
1671 } else {
1672 outputFile = implementationAndResourcesJar
1673 }
1674
1675 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001676 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1677 if !apiLevel.IsPreview() {
1678 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001679 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001680 // When running metalava, we pass --version-codename. When that value
1681 // is not REL, metalava will add 1 to the --current-version argument.
1682 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1683 // branch) and the codename is REL, except potentially on the most
1684 // recent non-master branch. On that branch, it goes through two other
1685 // phases before it gets to the phase previously described:
1686 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1687 // is not rel. This happens for most of the internal branch's life
1688 // while the branch has been cut but is still under active development.
1689 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1690 // REL. This happens briefly during the release process. During this
1691 // state the code to add --current-version is commented out, and then
1692 // that commenting out is reverted after the codename is set to REL.
1693 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1694 // prior version and the codename is always non-REL.
1695 //
1696 // We need to add one here to match metalava adding 1. Technically
1697 // this means that in the state described in the second bullet point
1698 // above, this number is 1 higher than it should be.
1699 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001700 }
1701 }
1702
1703 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001704 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1705 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001706 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1707 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001708 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001709 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001710 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001711 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001712 j.linter.javaLanguageLevel = flags.javaVersion.String()
1713 j.linter.kotlinLanguageLevel = "1.3"
1714 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1715 j.linter.buildModuleReportZip = true
1716 }
1717 j.linter.lint(ctx)
1718 }
1719
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001720 j.collectTransitiveSrcFiles(ctx, srcFiles)
1721
Jaewoong Jung26342642021-03-17 15:56:23 -07001722 ctx.CheckbuildFile(outputFile)
1723
Colin Crossd788b3e2023-11-28 13:14:56 -08001724 aconfig.CollectDependencyAconfigFiles(ctx, &j.mergedAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001725
Jaewoong Jung26342642021-03-17 15:56:23 -07001726 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1727 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001728 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1729 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001730 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1731 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1732 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1733 AidlIncludeDirs: j.exportAidlIncludeDirs,
1734 SrcJarArgs: j.srcJarArgs,
1735 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001736 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001737 ExportedPlugins: j.exportedPluginJars,
1738 ExportedPluginClasses: j.exportedPluginClasses,
1739 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1740 JacocoReportClassesFile: j.jacocoReportClassesFile,
1741 })
1742
1743 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1744 j.outputFile = outputFile.WithoutRel()
1745}
1746
Colin Crossa1ff7c62021-09-17 14:11:52 -07001747func (j *Module) useCompose() bool {
1748 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1749}
1750
Sam Delmerico95d70942023-08-02 18:00:35 -04001751func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1752 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1753 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1754
1755 ctx.VisitDirectDeps(func(m android.Module) {
1756 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1757 depTag := ctx.OtherModuleDependencyTag(m)
1758
1759 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1760 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1761 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1762 }
1763
1764 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1765 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1766 }
1767 })
1768
1769 directUnconditionalExportedFlags := android.Paths{}
1770 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1771 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1772 if exportUnconditionally {
1773 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1774 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1775 directUnconditionalExportedFlags = proguardFlagsForThisModule
1776 }
1777
1778 return ProguardSpecInfo{
1779 Export_proguard_flags_files: exportUnconditionally,
1780 ProguardFlagsFiles: android.NewDepSet[android.Path](
1781 android.POSTORDER,
1782 proguardFlagsForThisModule,
1783 transitiveProguardFlags,
1784 ),
1785 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1786 android.POSTORDER,
1787 directUnconditionalExportedFlags,
1788 transitiveUnconditionalExportedFlags,
1789 ),
1790 }
1791
1792}
1793
Cole Faust75fffb12021-06-13 15:23:16 -07001794// Returns a copy of the supplied flags, but with all the errorprone-related
1795// fields copied to the regular build's fields.
1796func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1797 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1798
1799 if len(flags.errorProneExtraJavacFlags) > 0 {
1800 if len(flags.javacFlags) > 0 {
1801 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1802 } else {
1803 flags.javacFlags = flags.errorProneExtraJavacFlags
1804 }
1805 }
1806 return flags
1807}
1808
Jaewoong Jung26342642021-03-17 15:56:23 -07001809func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1810 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1811
1812 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001813 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001814 if idx >= 0 {
1815 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001816 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 jarName += strconv.Itoa(idx)
1818 }
1819
1820 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001821 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001822
1823 if ctx.Config().EmitXrefRules() {
1824 extractionFile := android.PathForModuleOut(ctx, kzipName)
1825 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1826 j.kytheFiles = append(j.kytheFiles, extractionFile)
1827 }
1828
Vadim Spivak3c496f02023-06-08 06:14:59 +00001829 if len(flags.processorPath) > 0 {
1830 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1831 }
1832
Jaewoong Jung26342642021-03-17 15:56:23 -07001833 return classes
1834}
1835
1836// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1837// since some of these flags may be used internally.
1838func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1839 for _, flag := range flags {
1840 flag = strings.TrimSpace(flag)
1841
1842 if !strings.HasPrefix(flag, "-") {
1843 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1844 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1845 ctx.PropertyErrorf("kotlincflags",
1846 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1847 } else if inList(flag, config.KotlincIllegalFlags) {
1848 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1849 } else if flag == "-include-runtime" {
1850 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1851 } else {
1852 args := strings.Split(flag, " ")
1853 if args[0] == "-kotlin-home" {
1854 ctx.PropertyErrorf("kotlincflags",
1855 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1856 }
1857 }
1858 }
1859}
1860
1861func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1862 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001863 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001864
1865 var jars android.Paths
1866 if len(srcFiles) > 0 || len(srcJars) > 0 {
1867 // Compile java sources into turbine.jar.
1868 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1869 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1870 if ctx.Failed() {
1871 return nil, nil
1872 }
1873 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001874 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 }
1876
1877 jars = append(jars, extraJars...)
1878
1879 // Combine any static header libraries into classes-header.jar. If there is only
1880 // one input jar this step will be skipped.
1881 jars = append(jars, deps.staticHeaderJars...)
1882
1883 // we cannot skip the combine step for now if there is only one jar
1884 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1885 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1886 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1887 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001888 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001889
1890 if j.expandJarjarRules != nil {
1891 // Transform classes.jar into classes-jarjar.jar
1892 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001893 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1894 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001895 if ctx.Failed() {
1896 return nil, nil
1897 }
1898 }
1899
Colin Cross3d56ed52021-11-18 22:23:12 -08001900 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001901}
1902
1903func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001904 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001905
1906 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1907 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1908
1909 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1910
1911 j.jacocoReportClassesFile = jacocoReportClassesFile
1912
1913 return instrumentedJar
1914}
1915
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001916type providesTransitiveHeaderJars struct {
1917 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001918 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001919 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001920 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001921}
1922
Colin Crossc85750b2022-04-21 12:50:51 -07001923func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001924 return j.transitiveLibsHeaderJars
1925}
1926
Colin Crossc85750b2022-04-21 12:50:51 -07001927func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001928 return j.transitiveStaticLibsHeaderJars
1929}
1930
1931func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1932 directLibs := android.Paths{}
1933 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001934 transitiveLibs := []*android.DepSet[android.Path]{}
1935 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001936 ctx.VisitDirectDeps(func(module android.Module) {
1937 // don't add deps of the prebuilt version of the same library
1938 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1939 return
1940 }
1941
1942 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001943 tag := ctx.OtherModuleDependencyTag(module)
1944 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1945 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1946 directLibs = append(directLibs, dep.HeaderJars...)
1947 } else if tag == staticLibTag {
1948 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001949 } else {
1950 // Don't propagate transitive libs for other kinds of dependencies.
1951 return
1952 }
1953
1954 if dep.TransitiveLibsHeaderJars != nil {
1955 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1956 }
1957 if dep.TransitiveStaticLibsHeaderJars != nil {
1958 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001959 }
1960 })
1961 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1962 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1963}
1964
Jaewoong Jung26342642021-03-17 15:56:23 -07001965func (j *Module) HeaderJars() android.Paths {
1966 if j.headerJarFile == nil {
1967 return nil
1968 }
1969 return android.Paths{j.headerJarFile}
1970}
1971
1972func (j *Module) ImplementationJars() android.Paths {
1973 if j.implementationJarFile == nil {
1974 return nil
1975 }
1976 return android.Paths{j.implementationJarFile}
1977}
1978
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001979func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001980 return j.dexJarFile
1981}
1982
1983func (j *Module) DexJarInstallPath() android.Path {
1984 return j.installFile
1985}
1986
1987func (j *Module) ImplementationAndResourcesJars() android.Paths {
1988 if j.implementationAndResourcesJar == nil {
1989 return nil
1990 }
1991 return android.Paths{j.implementationAndResourcesJar}
1992}
1993
1994func (j *Module) AidlIncludeDirs() android.Paths {
1995 // exportAidlIncludeDirs is type android.Paths already
1996 return j.exportAidlIncludeDirs
1997}
1998
1999func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
2000 return j.classLoaderContexts
2001}
2002
2003// Collect information for opening IDE project files in java/jdeps.go.
2004func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
2005 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
2006 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
2007 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
2008 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
2009 if j.expandJarjarRules != nil {
2010 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
2011 }
Yikef6282022022-04-13 20:41:01 +08002012 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
2013 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00002014 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002015}
2016
2017func (j *Module) CompilerDeps() []string {
2018 jdeps := []string{}
2019 jdeps = append(jdeps, j.properties.Libs...)
2020 jdeps = append(jdeps, j.properties.Static_libs...)
2021 return jdeps
2022}
2023
2024func (j *Module) hasCode(ctx android.ModuleContext) bool {
2025 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
2026 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
2027}
2028
2029// Implements android.ApexModule
2030func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
2031 return j.depIsInSameApex(ctx, dep)
2032}
2033
2034// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002035func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002036 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002037 minSdkVersion := j.MinSdkVersion(ctx)
2038 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002039 return fmt.Errorf("min_sdk_version is not specified")
2040 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002041 // If the module is compiling against core (via sdk_version), skip comparison check.
2042 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002043 return nil
2044 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002045 if minSdkVersion.GreaterThan(sdkVersion) {
2046 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002047 }
2048 return nil
2049}
2050
2051func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002052 if j.stem == "" {
2053 panic("Stem() called before stem property was set")
2054 }
2055 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002056}
2057
Jaewoong Jung26342642021-03-17 15:56:23 -07002058func (j *Module) JacocoReportClassesFile() android.Path {
2059 return j.jacocoReportClassesFile
2060}
2061
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002062func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2063 var fromDeps []*android.DepSet[android.Path]
2064 ctx.VisitDirectDeps(func(module android.Module) {
2065 tag := ctx.OtherModuleDependencyTag(module)
2066 if tag == staticLibTag {
2067 depInfo := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2068 if depInfo.TransitiveSrcFiles != nil {
2069 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2070 }
2071 }
2072 })
2073
2074 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2075}
2076
Jaewoong Jung26342642021-03-17 15:56:23 -07002077func (j *Module) IsInstallable() bool {
2078 return Bool(j.properties.Installable)
2079}
2080
2081type sdkLinkType int
2082
2083const (
2084 // TODO(jiyong) rename these for better readability. Make the allowed
2085 // and disallowed link types explicit
2086 // order is important here. See rank()
2087 javaCore sdkLinkType = iota
2088 javaSdk
2089 javaSystem
2090 javaModule
2091 javaSystemServer
2092 javaPlatform
2093)
2094
2095func (lt sdkLinkType) String() string {
2096 switch lt {
2097 case javaCore:
2098 return "core Java API"
2099 case javaSdk:
2100 return "Android API"
2101 case javaSystem:
2102 return "system API"
2103 case javaModule:
2104 return "module API"
2105 case javaSystemServer:
2106 return "system server API"
2107 case javaPlatform:
2108 return "private API"
2109 default:
2110 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2111 }
2112}
2113
2114// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2115// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2116// can't statically depend on modules that use Platform API.
2117func (lt sdkLinkType) rank() int {
2118 return int(lt)
2119}
2120
2121type moduleWithSdkDep interface {
2122 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002123 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002124}
2125
Jiyong Park92315372021-04-02 08:45:46 +09002126func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002127 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002128 case android.SdkCore.DefaultJavaLibraryName(),
2129 "legacy.core.platform.api.stubs",
2130 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002131 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002132 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002133 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002134 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002135 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002136 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002137 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002138 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002139 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002140 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002141 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002142 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002143 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002144 return javaSystem, true
2145 }
2146
2147 if stub, linkType := moduleStubLinkType(name); stub {
2148 return linkType, true
2149 }
2150
Jiyong Park92315372021-04-02 08:45:46 +09002151 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002152 switch ver.Kind {
2153 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002154 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002155 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002156 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002157 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002158 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002159 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002160 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002161 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002162 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002163 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002164 return javaPlatform, false
2165 }
2166
Jiyong Parkf1691d22021-03-29 20:11:58 +09002167 if !ver.Valid() {
2168 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002169 }
2170 return javaSdk, false
2171}
2172
2173// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2174// this module's. See the comment on rank() for details and an example.
2175func (j *Module) checkSdkLinkType(
2176 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2177 if ctx.Host() {
2178 return
2179 }
2180
Jiyong Park92315372021-04-02 08:45:46 +09002181 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002182 if stubs {
2183 return
2184 }
Jiyong Park92315372021-04-02 08:45:46 +09002185 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002186
2187 if myLinkType.rank() < depLinkType.rank() {
2188 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2189 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2190 "property of the source or target module so that target module is built "+
2191 "with the same or smaller API set when compared to the source.",
2192 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2193 }
2194}
2195
2196func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2197 var deps deps
2198
2199 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002200 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002201 if sdkDep.invalidVersion {
2202 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2203 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2204 } else if sdkDep.useFiles {
2205 // sdkDep.jar is actually equivalent to turbine header.jar.
2206 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002207 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002208 deps.aidlPreprocess = sdkDep.aidl
2209 } else {
2210 deps.aidlPreprocess = sdkDep.aidl
2211 }
2212 }
2213
Jiyong Park92315372021-04-02 08:45:46 +09002214 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002215
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002216 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002217 ctx.VisitDirectDeps(func(module android.Module) {
2218 otherName := ctx.OtherModuleName(module)
2219 tag := ctx.OtherModuleDependencyTag(module)
2220
2221 if IsJniDepTag(tag) {
2222 // Handled by AndroidApp.collectAppDeps
2223 return
2224 }
2225 if tag == certificateTag {
2226 // Handled by AndroidApp.collectAppDeps
2227 return
2228 }
2229
2230 if dep, ok := module.(SdkLibraryDependency); ok {
2231 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002232 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002233 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2234 deps.classpath = append(deps.classpath, depHeaderJars...)
2235 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002236 case staticLibTag:
2237 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2238 }
2239 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2240 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2241 if sdkLinkType != javaPlatform &&
2242 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2243 // dep is a sysprop implementation library, but this module is not linking against
2244 // the platform, so it gets the sysprop public stubs library instead. Replace
2245 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2246 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2247 dep = syspropDep.JavaInfo
2248 }
2249 switch tag {
2250 case bootClasspathTag:
2251 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002252 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002253 if _, ok := module.(*Plugin); ok {
2254 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2255 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002256 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002257 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002258 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2259 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2260 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2261 case java9LibTag:
2262 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2263 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002264 if _, ok := module.(*Plugin); ok {
2265 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2266 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002267 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2268 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2269 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2270 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2271 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2272 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2273 // Turbine doesn't run annotation processors, so any module that uses an
2274 // annotation processor that generates API is incompatible with the turbine
2275 // optimization.
2276 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2277 case pluginTag:
2278 if plugin, ok := module.(*Plugin); ok {
2279 if plugin.pluginProperties.Processor_class != nil {
2280 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2281 } else {
2282 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2283 }
2284 // Turbine doesn't run annotation processors, so any module that uses an
2285 // annotation processor that generates API is incompatible with the turbine
2286 // optimization.
2287 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2288 } else {
2289 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2290 }
2291 case errorpronePluginTag:
2292 if _, ok := module.(*Plugin); ok {
2293 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2294 } else {
2295 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2296 }
2297 case exportedPluginTag:
2298 if plugin, ok := module.(*Plugin); ok {
2299 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2300 if plugin.pluginProperties.Processor_class != nil {
2301 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2302 }
2303 // Turbine doesn't run annotation processors, so any module that uses an
2304 // annotation processor that generates API is incompatible with the turbine
2305 // optimization.
2306 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2307 } else {
2308 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2309 }
2310 case kotlinStdlibTag:
2311 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2312 case kotlinAnnotationsTag:
2313 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002314 case kotlinPluginTag:
2315 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002316 case syspropPublicStubDepTag:
2317 // This is a sysprop implementation library, forward the JavaInfoProvider from
2318 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2319 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2320 JavaInfo: dep,
2321 })
2322 }
2323 } else if dep, ok := module.(android.SourceFileProducer); ok {
2324 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002325 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002326 checkProducesJars(ctx, dep)
2327 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002328 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002329 case staticLibTag:
2330 checkProducesJars(ctx, dep)
2331 deps.classpath = append(deps.classpath, dep.Srcs()...)
2332 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2333 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2334 }
2335 } else {
2336 switch tag {
2337 case bootClasspathTag:
2338 // If a system modules dependency has been added to the bootclasspath
2339 // then add its libs to the bootclasspath.
2340 sm := module.(SystemModulesProvider)
2341 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2342
2343 case systemModulesTag:
2344 if deps.systemModules != nil {
2345 panic("Found two system module dependencies")
2346 }
2347 sm := module.(SystemModulesProvider)
2348 outputDir, outputDeps := sm.OutputDirAndDeps()
2349 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002350
2351 case instrumentationForTag:
2352 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 -07002353 }
2354 }
2355
2356 addCLCFromDep(ctx, module, j.classLoaderContexts)
2357 })
2358
2359 return deps
2360}
2361
2362func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2363 deps.processorPath = append(deps.processorPath, pluginJars...)
2364 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2365}
2366
2367// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2368// this interface.
2369type ProvidesUsesLib interface {
2370 ProvidesUsesLib() *string
2371}
2372
2373func (j *Module) ProvidesUsesLib() *string {
2374 return j.usesLibraryProperties.Provides_uses_lib
2375}
satayev1c564cc2021-05-25 19:50:30 +01002376
2377type ModuleWithStem interface {
2378 Stem() string
2379}
2380
2381var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002382
Chris Parsons637458d2023-09-19 20:09:00 +00002383func (j *Module) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
Wei Libafb6d62021-12-10 03:14:59 -08002384 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002385 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002386 if lib, ok := ctx.Module().(*Library); ok {
2387 javaLibraryBp2Build(ctx, lib)
2388 }
2389 case "java_binary_host":
2390 if binary, ok := ctx.Module().(*Binary); ok {
2391 javaBinaryHostBp2Build(ctx, binary)
2392 }
Zi Wang65b36722023-05-23 15:18:33 -07002393 case "java_test_host":
2394 if testHost, ok := ctx.Module().(*TestHost); ok {
2395 javaTestHostBp2Build(ctx, testHost)
2396 }
Chris Parsons39a16972023-06-08 14:28:51 +00002397 default:
2398 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002399 }
Wei Libafb6d62021-12-10 03:14:59 -08002400}