blob: cdb58a2f9d4a3bd7cf0d565b1c3ffc43ad205c13 [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
Colin Crossd788b3e2023-11-28 13:14:56 -080023 "github.com/google/blueprint"
Jaewoong Jung26342642021-03-17 15:56:23 -070024 "github.com/google/blueprint/pathtools"
25 "github.com/google/blueprint/proptools"
26
Yu Liueae7b362023-11-16 17:05:47 -080027 "android/soong/aconfig"
Jaewoong Jung26342642021-03-17 15:56:23 -070028 "android/soong/android"
29 "android/soong/dexpreopt"
30 "android/soong/java/config"
31)
32
33// This file contains the definition and the implementation of the base module that most
34// source-based Java module structs embed.
35
36// TODO:
37// Autogenerated files:
38// Renderscript
39// Post-jar passes:
40// Proguard
41// Rmtypedefs
42// DroidDoc
43// Findbugs
44
45// Properties that are common to most Java modules, i.e. whether it's a host or device module.
46type CommonProperties struct {
47 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
48 // or .aidl files.
49 Srcs []string `android:"path,arch_variant"`
50
51 // list Kotlin of source files containing Kotlin code that should be treated as common code in
52 // a codebase that supports Kotlin multiplatform. See
53 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
54 Common_srcs []string `android:"path,arch_variant"`
55
56 // list of source files that should not be used to build the Java module.
57 // This is most useful in the arch/multilib variants to remove non-common files
58 Exclude_srcs []string `android:"path,arch_variant"`
59
60 // list of directories containing Java resources
61 Java_resource_dirs []string `android:"arch_variant"`
62
63 // list of directories that should be excluded from java_resource_dirs
64 Exclude_java_resource_dirs []string `android:"arch_variant"`
65
66 // list of files to use as Java resources
67 Java_resources []string `android:"path,arch_variant"`
68
69 // list of files that should be excluded from java_resources and java_resource_dirs
70 Exclude_java_resources []string `android:"path,arch_variant"`
71
72 // list of module-specific flags that will be used for javac compiles
73 Javacflags []string `android:"arch_variant"`
74
75 // list of module-specific flags that will be used for kotlinc compiles
76 Kotlincflags []string `android:"arch_variant"`
77
78 // list of java libraries that will be in the classpath
79 Libs []string `android:"arch_variant"`
80
81 // list of java libraries that will be compiled into the resulting jar
82 Static_libs []string `android:"arch_variant"`
83
Jihoon Kang381c2fa2023-06-01 22:17:32 +000084 // list of java libraries that should not be used to build this module
85 Exclude_static_libs []string `android:"arch_variant"`
86
Jaewoong Jung26342642021-03-17 15:56:23 -070087 // manifest file to be included in resulting jar
88 Manifest *string `android:"path"`
89
90 // if not blank, run jarjar using the specified rules file
91 Jarjar_rules *string `android:"path,arch_variant"`
92
93 // If not blank, set the java version passed to javac as -source and -target
94 Java_version *string
95
96 // If set to true, allow this module to be dexed and installed on devices. Has no
97 // effect on host modules, which are always considered installable.
98 Installable *bool
99
100 // If set to true, include sources used to compile the module in to the final jar
101 Include_srcs *bool
102
103 // If not empty, classes are restricted to the specified packages and their sub-packages.
104 // This restriction is checked after applying jarjar rules and including static libs.
105 Permitted_packages []string
106
107 // List of modules to use as annotation processors
108 Plugins []string
109
110 // List of modules to export to libraries that directly depend on this library as annotation
111 // processors. Note that if the plugins set generates_api: true this will disable the turbine
112 // optimization on modules that depend on this module, which will reduce parallelism and cause
113 // more recompilation.
114 Exported_plugins []string
115
116 // The number of Java source entries each Javac instance can process
117 Javac_shard_size *int64
118
119 // Add host jdk tools.jar to bootclasspath
120 Use_tools_jar *bool
121
122 Openjdk9 struct {
123 // List of source files that should only be used when passing -source 1.9 or higher
124 Srcs []string `android:"path"`
125
126 // List of javac flags that should only be used when passing -source 1.9 or higher
127 Javacflags []string
128 }
129
130 // When compiling language level 9+ .java code in packages that are part of
131 // a system module, patch_module names the module that your sources and
132 // dependencies should be patched into. The Android runtime currently
133 // doesn't implement the JEP 261 module system so this option is only
134 // supported at compile time. It should only be needed to compile tests in
135 // packages that exist in libcore and which are inconvenient to move
136 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400137 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700138
139 Jacoco struct {
140 // List of classes to include for instrumentation with jacoco to collect coverage
141 // information at runtime when building with coverage enabled. If unset defaults to all
142 // classes.
143 // Supports '*' as the last character of an entry in the list as a wildcard match.
144 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
145 // it matches classes in the package that have the class name as a prefix.
146 Include_filter []string
147
148 // List of classes to exclude from instrumentation with jacoco to collect coverage
149 // information at runtime when building with coverage enabled. Overrides classes selected
150 // by the include_filter property.
151 // Supports '*' as the last character of an entry in the list as a wildcard match.
152 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
153 // it matches classes in the package that have the class name as a prefix.
154 Exclude_filter []string
155 }
156
157 Errorprone struct {
158 // List of javac flags that should only be used when running errorprone.
159 Javacflags []string
160
161 // List of java_plugin modules that provide extra errorprone checks.
162 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700163
Cole Faust2b1536e2021-06-18 12:25:54 -0700164 // This property can be in 3 states. When set to true, errorprone will
165 // be run during the regular build. When set to false, errorprone will
166 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
167 // environment variable is true. Setting this to false will improve build
168 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700169 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700170 }
171
172 Proto struct {
173 // List of extra options that will be passed to the proto generator.
174 Output_params []string
175 }
176
Sam Delmericoc7593722022-08-31 15:57:52 -0400177 // If true, then jacocoagent is automatically added as a libs dependency so that
178 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000180 // If true, then the module supports statically including the jacocoagent
181 // into the library.
182 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700183
184 // List of files to include in the META-INF/services folder of the resulting jar.
185 Services []string `android:"path,arch_variant"`
186
187 // If true, package the kotlin stdlib into the jar. Defaults to true.
188 Static_kotlin_stdlib *bool `android:"arch_variant"`
189
190 // A list of java_library instances that provide additional hiddenapi annotations for the library.
191 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700192
193 // Additional srcJars tacked in by GeneratedJavaLibraryModule
194 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000195
196 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400197 Headers_only *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700198}
199
200// Properties that are specific to device modules. Host module factories should not add these when
201// constructing a new module.
202type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000203 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000204 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000206 // 1) numerical API level, "current", "none", or "core_platform"
207 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
208 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
209 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700210 Sdk_version *string
211
212 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000213 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700214 Min_sdk_version *string
215
satayev0a420e72021-11-29 17:25:52 +0000216 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
217 // Defaults to empty string "". See sdk_version for possible values.
218 Max_sdk_version *string
219
William Loh5a082f92022-05-17 20:21:50 +0000220 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
221 // Defaults to empty string "". See sdk_version for possible values.
222 Replace_max_sdk_version_placeholder *string
223
Jaewoong Jung26342642021-03-17 15:56:23 -0700224 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000225 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700226 Target_sdk_version *string
227
228 // Whether to compile against the platform APIs instead of an SDK.
229 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000230 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700231 Platform_apis *bool
232
233 Aidl struct {
234 // Top level directories to pass to aidl tool
235 Include_dirs []string
236
237 // Directories rooted at the Android.bp file to pass to aidl tool
238 Local_include_dirs []string
239
240 // directories that should be added as include directories for any aidl sources of modules
241 // that depend on this module, as well as to aidl for this module.
242 Export_include_dirs []string
243
244 // whether to generate traces (for systrace) for this interface
245 Generate_traces *bool
246
247 // whether to generate Binder#GetTransaction name method.
248 Generate_get_transaction_name *bool
249
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100250 // whether all interfaces should be annotated with required permissions.
251 Enforce_permissions *bool
252
253 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
254 Enforce_permissions_exceptions []string `android:"path"`
255
Jaewoong Jung26342642021-03-17 15:56:23 -0700256 // list of flags that will be passed to the AIDL compiler
257 Flags []string
258 }
259
260 // If true, export a copy of the module as a -hostdex module for host testing.
261 Hostdex *bool
262
263 Target struct {
264 Hostdex struct {
265 // Additional required dependencies to add to -hostdex modules.
266 Required []string
267 }
268 }
269
270 // When targeting 1.9 and above, override the modules to use with --system,
271 // otherwise provides defaults libraries to add to the bootclasspath.
272 System_modules *string
273
Jaewoong Jung26342642021-03-17 15:56:23 -0700274 IsSDKLibrary bool `blueprint:"mutated"`
275
276 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
277 // Defaults to false.
278 V4_signature *bool
279
280 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
281 // public stubs library.
282 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000283
284 HiddenAPIPackageProperties
285 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700286}
287
Jooyung Han01d80d82022-01-08 12:16:32 +0900288// Device properties that can be overridden by overriding module (e.g. override_android_app)
289type OverridableDeviceProperties struct {
290 // set the name of the output. If not set, `name` is used.
291 // To override a module with this property set, overriding module might need to set this as well.
292 // Otherwise, both the overridden and the overriding modules will have the same output name, which
293 // can cause the duplicate output error.
294 Stem *string
295}
296
Jaewoong Jung26342642021-03-17 15:56:23 -0700297// Functionality common to Module and Import
298//
299// It is embedded in Module so its functionality can be used by methods in Module
300// but it is currently only initialized by Import and Library.
301type embeddableInModuleAndImport struct {
302
303 // Functionality related to this being used as a component of a java_sdk_library.
304 EmbeddableSdkLibraryComponent
305}
306
Paul Duffin71b33cc2021-06-23 11:39:47 +0100307func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
308 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700309}
310
311// Module/Import's DepIsInSameApex(...) delegates to this method.
312//
313// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
314// the one provided by ApexModuleBase.
315func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
316 // dependencies other than the static linkage are all considered crossing APEX boundary
317 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
318 return true
319 }
320 return false
321}
322
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100323// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
324// or an invalid path describing the reason it is invalid.
325//
326// It is unset if a dex jar isn't applicable, i.e. no build rule has been
327// requested to create one.
328//
329// If a dex jar has been requested to be built then it is set, and it may be
330// either a valid android.Path, or invalid with a reason message. The latter
331// happens if the source that should produce the dex file isn't able to.
332//
333// E.g. it is invalid with a reason message if there is a prebuilt APEX that
334// could produce the dex jar through a deapexer module, but the APEX isn't
335// installable so doing so wouldn't be safe.
336type OptionalDexJarPath struct {
337 isSet bool
338 path android.OptionalPath
339}
340
341// IsSet returns true if a path has been set, either invalid or valid.
342func (o OptionalDexJarPath) IsSet() bool {
343 return o.isSet
344}
345
346// Valid returns true if there is a path that is valid.
347func (o OptionalDexJarPath) Valid() bool {
348 return o.isSet && o.path.Valid()
349}
350
351// Path returns the valid path, or panics if it's either not set or is invalid.
352func (o OptionalDexJarPath) Path() android.Path {
353 if !o.isSet {
354 panic("path isn't set")
355 }
356 return o.path.Path()
357}
358
359// PathOrNil returns the path if it's set and valid, or else nil.
360func (o OptionalDexJarPath) PathOrNil() android.Path {
361 if o.Valid() {
362 return o.Path()
363 }
364 return nil
365}
366
367// InvalidReason returns the reason for an invalid path, which is never "". It
368// returns "" for an unset or valid path.
369func (o OptionalDexJarPath) InvalidReason() string {
370 if !o.isSet {
371 return ""
372 }
373 return o.path.InvalidReason()
374}
375
376func (o OptionalDexJarPath) String() string {
377 if !o.isSet {
378 return "<unset>"
379 }
380 return o.path.String()
381}
382
383// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
384func makeUnsetDexJarPath() OptionalDexJarPath {
385 return OptionalDexJarPath{isSet: false}
386}
387
388// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
389// the given OptionalPath, which may be valid or invalid.
390func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
391 return OptionalDexJarPath{isSet: true, path: path}
392}
393
394// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
395// valid given path. It returns an unset OptionalDexJarPath if the given path is
396// nil.
397func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
398 if path == nil {
399 return makeUnsetDexJarPath()
400 }
401 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
402}
403
Jaewoong Jung26342642021-03-17 15:56:23 -0700404// Module contains the properties and members used by all java module types
405type Module struct {
406 android.ModuleBase
407 android.DefaultableModuleBase
408 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700409
410 // Functionality common to Module and Import.
411 embeddableInModuleAndImport
412
413 properties CommonProperties
414 protoProperties android.ProtoProperties
415 deviceProperties DeviceProperties
416
Jooyung Han01d80d82022-01-08 12:16:32 +0900417 overridableDeviceProperties OverridableDeviceProperties
418
Jaewoong Jung26342642021-03-17 15:56:23 -0700419 // jar file containing header classes including static library dependencies, suitable for
420 // inserting into the bootclasspath/classpath of another compile
421 headerJarFile android.Path
422
423 // jar file containing implementation classes including static library dependencies but no
424 // resources
425 implementationJarFile android.Path
426
427 // jar file containing only resources including from static library dependencies
428 resourceJar android.Path
429
430 // args and dependencies to package source files into a srcjar
431 srcJarArgs []string
432 srcJarDeps android.Paths
433
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000434 // the source files of this module and all its static dependencies
435 transitiveSrcFiles *android.DepSet[android.Path]
436
Jaewoong Jung26342642021-03-17 15:56:23 -0700437 // jar file containing implementation classes and resources including static library
438 // dependencies
439 implementationAndResourcesJar android.Path
440
441 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100442 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700443
444 // output file containing uninstrumented classes that will be instrumented by jacoco
445 jacocoReportClassesFile android.Path
446
447 // output file of the module, which may be a classes jar or a dex jar
448 outputFile android.Path
449 extraOutputFiles android.Paths
450
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100451 exportAidlIncludeDirs android.Paths
452 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700453
454 logtagsSrcs android.Paths
455
456 // installed file for binary dependency
457 installFile android.Path
458
Colin Cross3108ce12021-11-10 14:38:50 -0800459 // installed file for hostdex copy
460 hostdexInstallFile android.InstallPath
461
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800462 // list of unique .java and .kt source files
463 uniqueSrcFiles android.Paths
464
465 // list of srcjars that was passed to javac
466 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700467
468 // manifest file to use instead of properties.Manifest
469 overrideManifest android.OptionalPath
470
Jaewoong Jung26342642021-03-17 15:56:23 -0700471 // list of plugins that this java module is exporting
472 exportedPluginJars android.Paths
473
474 // list of plugins that this java module is exporting
475 exportedPluginClasses []string
476
477 // if true, the exported plugins generate API and require disabling turbine.
478 exportedDisableTurbine bool
479
480 // list of source files, collected from srcFiles with unique java and all kt files,
481 // will be used by android.IDEInfo struct
482 expandIDEInfoCompiledSrcs []string
483
484 // expanded Jarjar_rules
485 expandJarjarRules android.Path
486
Jaewoong Jung26342642021-03-17 15:56:23 -0700487 // Extra files generated by the module type to be added as java resources.
488 extraResources android.Paths
489
490 hiddenAPI
491 dexer
492 dexpreopter
493 usesLibrary
494 linter
495
496 // list of the xref extraction files
497 kytheFiles android.Paths
498
Jaewoong Jung26342642021-03-17 15:56:23 -0700499 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900500
501 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000502 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000503 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400504
505 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000506
507 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000508
509 // output file name based on Stem property.
510 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
511 // or the module should override Stem().
512 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700513
Colin Crossd788b3e2023-11-28 13:14:56 -0800514 // Single aconfig "cache file" merged from this module and all dependencies.
515 mergedAconfigFiles map[string]android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700516}
517
Jiyong Park92315372021-04-02 08:45:46 +0900518func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
519 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900520 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700521 return nil
522 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900523 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000524 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700525 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
526 } else {
527 // Treat stable core platform as stable.
528 return nil
529 }
530 } else {
531 return fmt.Errorf("non stable SDK %v", sdkVersion)
532 }
533}
534
535// checkSdkVersions enforces restrictions around SDK dependencies.
536func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
537 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900538 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900539 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700540 ctx.PropertyErrorf("sdk_version",
541 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
542 }
543 }
544 }
545
546 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
547 // See rank() for details.
548 ctx.VisitDirectDeps(func(module android.Module) {
549 tag := ctx.OtherModuleDependencyTag(module)
550 switch module.(type) {
551 // TODO(satayev): cover other types as well, e.g. imports
552 case *Library, *AndroidLibrary:
553 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400554 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700555 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
556 }
557 }
558 })
559}
560
561func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900562 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700563 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900564 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700565 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000566 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 -0700567 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000568 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 -0700569 }
570
571 }
572}
573
Mark Whitea15790a2023-08-22 21:28:11 +0000574func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
575 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400576 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000577 installable := proptools.Bool(j.properties.Installable)
578
579 if headersOnly && installable {
580 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.")
581 }
582 }
583}
584
Jaewoong Jung26342642021-03-17 15:56:23 -0700585func (j *Module) addHostProperties() {
586 j.AddProperties(
587 &j.properties,
588 &j.protoProperties,
589 &j.usesLibraryProperties,
590 )
591}
592
593func (j *Module) addHostAndDeviceProperties() {
594 j.addHostProperties()
595 j.AddProperties(
596 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900597 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700598 &j.dexer.dexProperties,
599 &j.dexpreoptProperties,
600 &j.linter.properties,
601 )
602}
603
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000604// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
605// makes it available through the hiddenAPIPropertyInfoProvider.
606func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
607 hiddenAPIInfo := newHiddenAPIPropertyInfo()
608
609 // Populate with flag file paths from the properties.
610 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
611
612 // Populate with package rules from the properties.
613 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
614
615 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
616}
617
Jaewoong Jung26342642021-03-17 15:56:23 -0700618func (j *Module) OutputFiles(tag string) (android.Paths, error) {
619 switch tag {
620 case "":
621 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
622 case android.DefaultDistTag:
623 return android.Paths{j.outputFile}, nil
624 case ".jar":
625 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700626 case ".hjar":
627 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700628 case ".proguard_map":
629 if j.dexer.proguardDictionary.Valid() {
630 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
631 }
632 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700633 case ".generated_srcjars":
634 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000635 case ".lint":
636 if j.linter.outputs.xml != nil {
637 return android.Paths{j.linter.outputs.xml}, nil
638 }
639 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700640 default:
641 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
642 }
643}
644
645var _ android.OutputFileProducer = (*Module)(nil)
646
647func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
648 initJavaModule(module, hod, false)
649}
650
651func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
652 initJavaModule(module, hod, true)
653}
654
655func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
656 multilib := android.MultilibCommon
657 if multiTargets {
658 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
659 } else {
660 android.InitAndroidArchModule(module, hod, multilib)
661 }
662 android.InitDefaultableModule(module)
663}
664
665func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
666 return j.properties.Instrument &&
667 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
668 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
669}
670
671func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000672 return j.properties.Supports_static_instrumentation &&
673 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700674 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
675 ctx.Config().UnbundledBuild())
676}
677
678func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
679 // Force enable the instrumentation for java code that is built for APEXes ...
680 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
681 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
682 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
683 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
684 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
685 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
686 return true
687 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
688 return true
689 }
690 }
691 return false
692}
693
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400694func (j *Module) setInstrument(value bool) {
695 j.properties.Instrument = value
696}
697
Jiyong Park92315372021-04-02 08:45:46 +0900698func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
699 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700700}
701
Jiyong Parkf1691d22021-03-29 20:11:58 +0900702func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700703 return proptools.String(j.deviceProperties.System_modules)
704}
705
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000706func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700707 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000708 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700709 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000710 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700711}
712
Yu Liuf2b94012023-09-19 15:09:10 -0700713func (j *Module) GetDeviceProperties() *DeviceProperties {
714 return &j.deviceProperties
715}
716
Spandan Dasa26eda72023-03-02 00:56:06 +0000717func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
718 if j.deviceProperties.Max_sdk_version != nil {
719 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
720 }
721 // Default is PrivateApiLevel
722 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000723}
724
Spandan Dasa26eda72023-03-02 00:56:06 +0000725func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
726 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
727 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
728 }
729 // Default is PrivateApiLevel
730 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000731}
732
Jiyong Parkf1691d22021-03-29 20:11:58 +0900733func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000734 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900735}
736
Spandan Dasca70fc42023-03-01 23:38:49 +0000737func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900738 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000739 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900740 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000741 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700742}
743
744func (j *Module) AvailableFor(what string) bool {
745 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
746 // Exception: for hostdex: true libraries, the platform variant is created
747 // even if it's not marked as available to platform. In that case, the platform
748 // variant is used only for the hostdex and not installed to the device.
749 return true
750 }
751 return j.ApexModuleBase.AvailableFor(what)
752}
753
754func (j *Module) deps(ctx android.BottomUpMutatorContext) {
755 if ctx.Device() {
756 j.linter.deps(ctx)
757
Jiyong Parkf1691d22021-03-29 20:11:58 +0900758 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700759
760 if j.deviceProperties.SyspropPublicStub != "" {
761 // This is a sysprop implementation library that has a corresponding sysprop public
762 // stubs library, and a dependency on it so that dependencies on the implementation can
763 // be forwarded to the public stubs library when necessary.
764 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
765 }
766 }
767
768 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000769
770 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700771 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
772
773 // Add dependency on libraries that provide additional hidden api annotations.
774 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
775
776 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
777 // Require java_sdk_library at inter-partition java dependency to ensure stable
778 // interface between partitions. If inter-partition java_library dependency is detected,
779 // raise build error because java_library doesn't have a stable interface.
780 //
781 // Inputs:
782 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
783 // if true, enable enforcement
784 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
785 // exception list of java_library names to allow inter-partition dependency
786 for idx := range j.properties.Libs {
787 if libDeps[idx] == nil {
788 continue
789 }
790
791 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
792 // java_sdk_library is always allowed at inter-partition dependency.
793 // So, skip check.
794 if _, ok := javaDep.(*SdkLibrary); ok {
795 continue
796 }
797
798 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
799 }
800 }
801 }
802
803 // For library dependencies that are component libraries (like stubs), add the implementation
804 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
805 for _, dep := range libDeps {
806 if dep != nil {
807 if component, ok := dep.(SdkLibraryComponentDependency); ok {
808 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100809 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100810 tag := usesLibReqTag
811 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
812 tag = usesLibOptTag
813 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100814 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700815 }
816 }
817 }
818 }
819
820 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
821 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
822 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
823
824 android.ProtoDeps(ctx, &j.protoProperties)
825 if j.hasSrcExt(".proto") {
826 protoDeps(ctx, &j.protoProperties)
827 }
828
829 if j.hasSrcExt(".kt") {
830 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
831 // Kotlin files
832 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
833 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700834 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700835 }
836
837 // Framework libraries need special handling in static coverage builds: they should not have
838 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
839 // the same jacoco classes coming from different bootclasspath jars.
840 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
841 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
842 j.properties.Instrument = true
843 }
844 } else if j.shouldInstrumentStatic(ctx) {
845 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
846 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700847
848 if j.useCompose() {
849 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
850 "androidx.compose.compiler_compiler-hosted")
851 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700852}
853
854func hasSrcExt(srcs []string, ext string) bool {
855 for _, src := range srcs {
856 if filepath.Ext(src) == ext {
857 return true
858 }
859 }
860
861 return false
862}
863
864func (j *Module) hasSrcExt(ext string) bool {
865 return hasSrcExt(j.properties.Srcs, ext)
866}
867
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100868func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
869 var flags string
870
871 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
872 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
873 flags = "-Wmissing-permission-annotation -Werror"
874 }
875 }
876 return flags
877}
878
Jaewoong Jung26342642021-03-17 15:56:23 -0700879func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000880 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
882 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
883 aidlIncludes = append(aidlIncludes,
884 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
885 aidlIncludes = append(aidlIncludes,
886 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
887
888 var flags []string
889 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000890 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700891
892 flags = append(flags, j.deviceProperties.Aidl.Flags...)
893
894 if aidlPreprocess.Valid() {
895 flags = append(flags, "-p"+aidlPreprocess.String())
896 deps = append(deps, aidlPreprocess.Path())
897 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000898 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700899 }
900
901 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000902 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700903 }
904
905 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000906 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700907 }
908
Sam Delmerico2351eac2022-05-24 17:10:02 +0000909 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700910 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000911 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000913 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
914 // add flags for dirs containing AIDL srcs that haven't been specified yet
915 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700916
Zim8774ae12022-08-17 11:46:34 +0100917 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000918 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100919 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700920 flags = append(flags, "-t")
921 }
922
923 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
924 flags = append(flags, "--transaction_names")
925 }
926
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100927 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
928 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
929 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
930 }
931
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000932 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900933 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
934
Jaewoong Jung26342642021-03-17 15:56:23 -0700935 return strings.Join(flags, " "), deps
936}
937
938func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
939
940 var flags javaBuilderFlags
941
942 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900943 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700944
Cole Faust2b1536e2021-06-18 12:25:54 -0700945 epEnabled := j.properties.Errorprone.Enabled
946 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100947 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700948 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
949 }
950
951 errorProneFlags := []string{
952 "-Xplugin:ErrorProne",
953 "${config.ErrorProneChecks}",
954 }
955 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
956
Colin Cross8bf6cad2022-02-28 13:07:03 -0800957 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700958 "'" + strings.Join(errorProneFlags, " ") + "'"
959 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
960 }
961
962 // classpath
963 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
964 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700965 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700966 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
967 flags.processorPath = append(flags.processorPath, deps.processorPath...)
968 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
969
970 flags.processors = append(flags.processors, deps.processorClasses...)
971 flags.processors = android.FirstUniqueStrings(flags.processors)
972
973 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900974 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700975 // Give host-side tools a version of OpenJDK's standard libraries
976 // close to what they're targeting. As of Dec 2017, AOSP is only
977 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
978 //
979 // When building with OpenJDK 8, the following should have no
980 // effect since those jars would be available by default.
981 //
982 // When building with OpenJDK 9 but targeting a version < 1.8,
983 // putting them on the bootclasspath means that:
984 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
985 // b) references to existing APIs are not reinterpreted in an
986 // OpenJDK 9-specific way, eg. calls to subclasses of
987 // java.nio.Buffer as in http://b/70862583
988 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
989 flags.bootClasspath = append(flags.bootClasspath,
990 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
991 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
992 if Bool(j.properties.Use_tools_jar) {
993 flags.bootClasspath = append(flags.bootClasspath,
994 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
995 }
996 }
997
998 // systemModules
999 flags.systemModules = deps.systemModules
1000
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 return flags
1002}
1003
1004func (j *Module) collectJavacFlags(
1005 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1006 // javac flags.
1007 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001008 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001009
Mythri Alle4b9f6182023-10-25 15:17:11 +00001010 needsDebugInfo = false
1011 for _, flag := range javacFlags {
1012 if strings.HasPrefix(flag, "-g") {
1013 needsDebugInfo = true
1014 }
1015 }
1016
1017 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001018 // For non-host binaries, override the -g flag passed globally to remove
1019 // local variable debug info to reduce disk and memory usage.
1020 javacFlags = append(javacFlags, "-g:source,lines")
1021 }
1022 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1023
1024 if flags.javaVersion.usesJavaModules() {
1025 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001026 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1027 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1028 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1029 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001030
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001031 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001032 if j.properties.Patch_module != nil {
1033 // Manually specify build directory in case it is not under the repo root.
1034 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1035 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001036 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001037
Jaewoong Jung26342642021-03-17 15:56:23 -07001038 classPath := flags.classpath.FormJavaClassPath("")
1039 if classPath != "" {
1040 patchPaths = append(patchPaths, classPath)
1041 }
1042 javacFlags = append(
1043 javacFlags,
1044 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1045 }
1046 }
1047
1048 if len(javacFlags) > 0 {
1049 // optimization.
1050 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1051 flags.javacFlags = "$javacFlags"
1052 }
1053
1054 return flags
1055}
1056
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001057func (j *Module) AddJSONData(d *map[string]interface{}) {
1058 (&j.ModuleBase).AddJSONData(d)
1059 (*d)["Java"] = map[string]interface{}{
1060 "SourceExtensions": j.sourceExtensions,
1061 }
1062
1063}
1064
usta0391ca42023-09-19 15:51:59 -04001065func (j *Module) addGeneratedSrcJars(path android.Path) {
1066 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001067}
1068
Colin Cross4eae06d2023-06-20 22:40:02 -07001069func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001070 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1071
1072 deps := j.collectDeps(ctx)
1073 flags := j.collectBuilderFlags(ctx, deps)
1074
1075 if flags.javaVersion.usesJavaModules() {
1076 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001077 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1078 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1079 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001080 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001081
Jaewoong Jung26342642021-03-17 15:56:23 -07001082 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001083 j.sourceExtensions = []string{}
1084 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1085 if hasSrcExt(srcFiles.Strings(), ext) {
1086 j.sourceExtensions = append(j.sourceExtensions, ext)
1087 }
1088 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001089 if hasSrcExt(srcFiles.Strings(), ".proto") {
1090 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1091 }
1092
1093 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1094 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1095 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1096 }
1097
Sam Delmerico2351eac2022-05-24 17:10:02 +00001098 aidlSrcs := srcFiles.FilterByExt(".aidl")
1099 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1100
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001101 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001102 srcFiles = j.genSources(ctx, srcFiles, flags)
1103
1104 // Collect javac flags only after computing the full set of srcFiles to
1105 // ensure that the --patch-module lookup paths are complete.
1106 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1107
1108 srcJars := srcFiles.FilterByExt(".srcjar")
1109 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001110 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001111 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001112 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001113
1114 if j.properties.Jarjar_rules != nil {
1115 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1116 }
1117
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001118 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001119
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001120 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001121 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001122 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001123 if _, found := set[v.String()]; !found {
1124 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001125 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 }
1127 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001128 var uniqueKtFiles android.Paths
1129 for _, v := range srcFiles.FilterByExt(".kt") {
1130 if _, found := set[v.String()]; !found {
1131 set[v.String()] = true
1132 uniqueKtFiles = append(uniqueKtFiles, v)
1133 }
1134 }
1135
1136 var uniqueSrcFiles android.Paths
1137 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1138 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1139 j.uniqueSrcFiles = uniqueSrcFiles
Aditya Choudhary26df39f2023-11-29 16:42:42 +00001140 ctx.SetProvider(blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001141
Colin Crossb5db4012022-03-28 17:12:39 -07001142 // We don't currently run annotation processors in turbine, which means we can't use turbine
1143 // generated header jars when an annotation processor that generates API is enabled. One
1144 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1145 // is used to run all of the annotation processors.
1146 disableTurbine := deps.disableTurbine
1147
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001148 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001149 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1150
1151 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001152 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001153
Colin Cross4eae06d2023-06-20 22:40:02 -07001154 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1155 // any dependencies so that it can override any non-final R classes from dependencies with the
1156 // final R classes from the app.
1157 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1158
Mark Whitea15790a2023-08-22 21:28:11 +00001159 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001160 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001161 if srcFiles.HasExt(".kt") {
1162 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1163 }
1164 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1165 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1166 }
1167
1168 _, j.headerJarFile =
1169 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1170 extraCombinedJars)
1171 if ctx.Failed() {
1172 return
1173 }
1174
1175 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1176 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1177 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1178 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1179 AidlIncludeDirs: j.exportAidlIncludeDirs,
1180 ExportedPlugins: j.exportedPluginJars,
1181 ExportedPluginClasses: j.exportedPluginClasses,
1182 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1183 })
1184
1185 j.outputFile = j.headerJarFile
1186 return
1187 }
1188
Jaewoong Jung26342642021-03-17 15:56:23 -07001189 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001190 // When using kotlin sources turbine is used to generate annotation processor sources,
1191 // including for annotation processors that generate API, so we can use turbine for
1192 // java sources too.
1193 disableTurbine = false
1194
Jaewoong Jung26342642021-03-17 15:56:23 -07001195 // user defined kotlin flags.
1196 kotlincFlags := j.properties.Kotlincflags
1197 CheckKotlincFlags(ctx, kotlincFlags)
1198
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001199 // Workaround for KT-46512
1200 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001201
1202 // If there are kotlin files, compile them first but pass all the kotlin and java files
1203 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1204 // won't emit any classes for them.
1205 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1206 if ctx.Device() {
1207 kotlincFlags = append(kotlincFlags, "-no-jdk")
1208 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001209
1210 for _, plugin := range deps.kotlinPlugins {
1211 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1212 }
1213 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1214
Jaewoong Jung26342642021-03-17 15:56:23 -07001215 if len(kotlincFlags) > 0 {
1216 // optimization.
1217 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1218 flags.kotlincFlags += "$kotlincFlags"
1219 }
1220
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001221 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001222 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1223
1224 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1225 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1226
1227 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1228 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1229
Isaac Chioua23d9942022-04-06 06:14:38 +00001230 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001231 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001232 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1233 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001234 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001235 srcJars = append(srcJars, kaptSrcJar)
1236 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001237 // Disable annotation processing in javac, it's already been handled by kapt
1238 flags.processorPath = nil
1239 flags.processors = nil
1240 }
1241
1242 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001243 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001244 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001245 if ctx.Failed() {
1246 return
1247 }
1248
Isaac Chioua23d9942022-04-06 06:14:38 +00001249 // Make javac rule depend on the kotlinc rule
1250 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1251
Jaewoong Jung26342642021-03-17 15:56:23 -07001252 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001253 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1254
Jaewoong Jung26342642021-03-17 15:56:23 -07001255 // Jar kotlin classes into the final jar after javac
1256 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1257 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001258 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001259 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001260 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001261 } else {
1262 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001263 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 }
1265 }
1266
1267 jars := append(android.Paths(nil), kotlinJars...)
1268
Jaewoong Jung26342642021-03-17 15:56:23 -07001269 j.compiledSrcJars = srcJars
1270
1271 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001272 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001273 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001274 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1275 enableSharding = true
1276 // Formerly, there was a check here that prevented annotation processors
1277 // from being used when sharding was enabled, as some annotation processors
1278 // do not function correctly in sharded environments. It was removed to
1279 // allow for the use of annotation processors that do function correctly
1280 // with sharding enabled. See: b/77284273.
1281 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001282 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001283 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001284 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001285 if ctx.Failed() {
1286 return
1287 }
1288 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001289 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001290 hasErrorproneableFiles := false
1291 for _, ext := range j.sourceExtensions {
1292 if ext != ".proto" && ext != ".aidl" {
1293 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1294 // compile, and it's not useful to have warnings on these generated sources.
1295 hasErrorproneableFiles = true
1296 break
1297 }
1298 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001299 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001300 if Bool(j.properties.Errorprone.Enabled) {
1301 // If error-prone is enabled, enable errorprone flags on the regular
1302 // build.
1303 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001304 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001305 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1306 // a new jar file just for compiling with the errorprone compiler to.
1307 // This is because we don't want to cause the java files to get completely
1308 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1309 // We also don't want to run this if errorprone is enabled by default for
1310 // this module, or else we could have duplicated errorprone messages.
1311 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001312 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001313 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001314
Vadim Spivak3c496f02023-06-08 06:14:59 +00001315 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001316 "errorprone", "errorprone")
1317
Jaewoong Jung26342642021-03-17 15:56:23 -07001318 extraJarDeps = append(extraJarDeps, errorprone)
1319 }
1320
1321 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001322 if headerJarFileWithoutDepsOrJarjar != nil {
1323 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1324 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001325 shardSize := int(*(j.properties.Javac_shard_size))
1326 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001327 if len(uniqueJavaFiles) > 0 {
1328 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001329 for idx, shardSrc := range shardSrcs {
1330 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1331 nil, flags, extraJarDeps)
1332 jars = append(jars, classes)
1333 }
1334 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001335 // Assume approximately 5 sources per srcjar.
1336 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1337 // 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 -07001338 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001339 startIdx := len(shardSrcs)
1340 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1341 for idx, shardSrcJars := range shardSrcJarsList {
1342 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1343 nil, shardSrcJars, flags, extraJarDeps)
1344 jars = append(jars, classes)
1345 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001346 }
1347 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001348 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001349 jars = append(jars, classes)
1350 }
1351 if ctx.Failed() {
1352 return
1353 }
1354 }
1355
1356 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1357
1358 var includeSrcJar android.WritablePath
1359 if Bool(j.properties.Include_srcs) {
1360 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1361 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1362 }
1363
1364 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1365 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1366 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1367 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1368
1369 var resArgs []string
1370 var resDeps android.Paths
1371
1372 resArgs = append(resArgs, dirArgs...)
1373 resDeps = append(resDeps, dirDeps...)
1374
1375 resArgs = append(resArgs, fileArgs...)
1376 resDeps = append(resDeps, fileDeps...)
1377
1378 resArgs = append(resArgs, extraArgs...)
1379 resDeps = append(resDeps, extraDeps...)
1380
1381 if len(resArgs) > 0 {
1382 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1383 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1384 j.resourceJar = resourceJar
1385 if ctx.Failed() {
1386 return
1387 }
1388 }
1389
1390 var resourceJars android.Paths
1391 if j.resourceJar != nil {
1392 resourceJars = append(resourceJars, j.resourceJar)
1393 }
1394 if Bool(j.properties.Include_srcs) {
1395 resourceJars = append(resourceJars, includeSrcJar)
1396 }
1397 resourceJars = append(resourceJars, deps.staticResourceJars...)
1398
1399 if len(resourceJars) > 1 {
1400 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1401 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1402 false, nil, nil)
1403 j.resourceJar = combinedJar
1404 } else if len(resourceJars) == 1 {
1405 j.resourceJar = resourceJars[0]
1406 }
1407
1408 if len(deps.staticJars) > 0 {
1409 jars = append(jars, deps.staticJars...)
1410 }
1411
1412 manifest := j.overrideManifest
1413 if !manifest.Valid() && j.properties.Manifest != nil {
1414 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1415 }
1416
1417 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1418 if len(services) > 0 {
1419 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1420 var zipargs []string
1421 for _, file := range services {
1422 serviceFile := file.String()
1423 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1424 }
1425 rule := zip
1426 args := map[string]string{
1427 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1428 }
1429 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1430 rule = zipRE
1431 args["implicits"] = strings.Join(services.Strings(), ",")
1432 }
1433 ctx.Build(pctx, android.BuildParams{
1434 Rule: rule,
1435 Output: servicesJar,
1436 Implicits: services,
1437 Args: args,
1438 })
1439 jars = append(jars, servicesJar)
1440 }
1441
Colin Cross4eae06d2023-06-20 22:40:02 -07001442 jars = append(android.CopyOf(extraCombinedJars), jars...)
1443
Jaewoong Jung26342642021-03-17 15:56:23 -07001444 // Combine the classes built from sources, any manifests, and any static libraries into
1445 // classes.jar. If there is only one input jar this step will be skipped.
1446 var outputFile android.OutputPath
1447
1448 if len(jars) == 1 && !manifest.Valid() {
1449 // Optimization: skip the combine step as there is nothing to do
1450 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1451 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1452 // any if len(jars) == 1.
1453
Jihoon Kang1147b312023-06-08 23:25:57 +00001454 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1455 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1456 // either with .from-source or .from-text suffix.
1457 // outputFile should be agnostic to the build configuration,
1458 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1459 // to the copy rules.
1460 stub, _ := moduleStubLinkType(ctx.ModuleName())
1461
Jaewoong Jung26342642021-03-17 15:56:23 -07001462 // Transform the single path to the jar into an OutputPath as that is required by the following
1463 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001464 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 // The path contains an embedded OutputPath so reuse that.
1466 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001467 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001468 // The path is an OutputPath so reuse it directly.
1469 outputFile = outputPath
1470 } else {
1471 // The file is not in the out directory so create an OutputPath into which it can be copied
1472 // and which the following code can use to refer to it.
1473 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1474 ctx.Build(pctx, android.BuildParams{
1475 Rule: android.Cp,
1476 Input: jars[0],
1477 Output: combinedJar,
1478 })
1479 outputFile = combinedJar.OutputPath
1480 }
1481 } else {
1482 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1483 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1484 false, nil, nil)
1485 outputFile = combinedJar.OutputPath
1486 }
1487
1488 // jarjar implementation jar if necessary
1489 if j.expandJarjarRules != nil {
1490 // Transform classes.jar into classes-jarjar.jar
1491 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1492 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1493 outputFile = jarjarFile
1494
1495 // jarjar resource jar if necessary
1496 if j.resourceJar != nil {
1497 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1498 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1499 j.resourceJar = resourceJarJarFile
1500 }
1501
1502 if ctx.Failed() {
1503 return
1504 }
1505 }
1506
1507 // Check package restrictions if necessary.
1508 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001509 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001510 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001511
1512 // Create a rule to copy the output jar to another path and add a validate dependency that
1513 // will check that the jar only contains the permitted packages. The new location will become
1514 // the output file of this module.
1515 inputFile := outputFile
1516 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1517 ctx.Build(pctx, android.BuildParams{
1518 Rule: android.Cp,
1519 Input: inputFile,
1520 Output: outputFile,
1521 // Make sure that any dependency on the output file will cause ninja to run the package check
1522 // rule.
1523 Validation: pkgckFile,
1524 })
1525
1526 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001527 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001528
1529 if ctx.Failed() {
1530 return
1531 }
1532 }
1533
1534 j.implementationJarFile = outputFile
1535 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001536 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1537 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1538 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1539 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1540 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1541 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1542 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001543 }
1544
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001545 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1546 specs := j.jacocoModuleToZipCommand(ctx)
1547 if ctx.Failed() {
1548 return
1549 }
1550
Jaewoong Jung26342642021-03-17 15:56:23 -07001551 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001552 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001553 }
1554
1555 // merge implementation jar with resources if necessary
1556 implementationAndResourcesJar := outputFile
1557 if j.resourceJar != nil {
1558 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1559 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1560 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1561 false, nil, nil)
1562 implementationAndResourcesJar = combinedJar
1563 }
1564
1565 j.implementationAndResourcesJar = implementationAndResourcesJar
1566
1567 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001568 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001569 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1570 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001571 if compileDex == nil {
1572 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001573 }
1574 if j.deviceProperties.Hostdex == nil {
1575 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1576 }
1577 }
1578
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001579 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001580 if j.hasCode(ctx) {
1581 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001582 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001583 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1584 }
1585 // Dex compilation
1586 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001587 params := &compileDexParams{
1588 flags: flags,
1589 sdkVersion: j.SdkVersion(ctx),
1590 minSdkVersion: j.MinSdkVersion(ctx),
1591 classesJar: implementationAndResourcesJar,
1592 jarName: jarName,
1593 }
1594 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001595 if ctx.Failed() {
1596 return
1597 }
1598
Jaewoong Jung26342642021-03-17 15:56:23 -07001599 // merge dex jar with resources if necessary
1600 if j.resourceJar != nil {
1601 jars := android.Paths{dexOutputFile, j.resourceJar}
1602 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1603 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1604 false, nil, nil)
1605 if *j.dexProperties.Uncompress_dex {
1606 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001607 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001608 dexOutputFile = combinedAlignedJar
1609 } else {
1610 dexOutputFile = combinedJar
1611 }
1612 }
1613
Paul Duffin4de94502021-05-16 05:21:16 +01001614 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001615
1616 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001617
1618 // Encode hidden API flags in dex file, if needed.
1619 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1620
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001621 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001622
1623 // Dexpreopting
1624 j.dexpreopt(ctx, dexOutputFile)
1625
1626 outputFile = dexOutputFile
1627 } else {
1628 // There is no code to compile into a dex jar, make sure the resources are propagated
1629 // to the APK if this is an app.
1630 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001631 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001632 }
1633
1634 if ctx.Failed() {
1635 return
1636 }
1637 } else {
1638 outputFile = implementationAndResourcesJar
1639 }
1640
1641 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001642 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1643 if !apiLevel.IsPreview() {
1644 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001645 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001646 // When running metalava, we pass --version-codename. When that value
1647 // is not REL, metalava will add 1 to the --current-version argument.
1648 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1649 // branch) and the codename is REL, except potentially on the most
1650 // recent non-master branch. On that branch, it goes through two other
1651 // phases before it gets to the phase previously described:
1652 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1653 // is not rel. This happens for most of the internal branch's life
1654 // while the branch has been cut but is still under active development.
1655 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1656 // REL. This happens briefly during the release process. During this
1657 // state the code to add --current-version is commented out, and then
1658 // that commenting out is reverted after the codename is set to REL.
1659 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1660 // prior version and the codename is always non-REL.
1661 //
1662 // We need to add one here to match metalava adding 1. Technically
1663 // this means that in the state described in the second bullet point
1664 // above, this number is 1 higher than it should be.
1665 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001666 }
1667 }
1668
1669 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001670 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1671 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001672 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1673 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001674 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001675 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001676 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001677 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001678 j.linter.javaLanguageLevel = flags.javaVersion.String()
1679 j.linter.kotlinLanguageLevel = "1.3"
1680 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1681 j.linter.buildModuleReportZip = true
1682 }
1683 j.linter.lint(ctx)
1684 }
1685
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001686 j.collectTransitiveSrcFiles(ctx, srcFiles)
1687
Jaewoong Jung26342642021-03-17 15:56:23 -07001688 ctx.CheckbuildFile(outputFile)
1689
Colin Crossd788b3e2023-11-28 13:14:56 -08001690 aconfig.CollectDependencyAconfigFiles(ctx, &j.mergedAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001691
Jaewoong Jung26342642021-03-17 15:56:23 -07001692 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1693 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001694 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1695 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001696 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1697 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1698 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1699 AidlIncludeDirs: j.exportAidlIncludeDirs,
1700 SrcJarArgs: j.srcJarArgs,
1701 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001702 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001703 ExportedPlugins: j.exportedPluginJars,
1704 ExportedPluginClasses: j.exportedPluginClasses,
1705 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1706 JacocoReportClassesFile: j.jacocoReportClassesFile,
1707 })
1708
1709 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1710 j.outputFile = outputFile.WithoutRel()
1711}
1712
Colin Crossa1ff7c62021-09-17 14:11:52 -07001713func (j *Module) useCompose() bool {
1714 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1715}
1716
Sam Delmerico95d70942023-08-02 18:00:35 -04001717func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1718 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1719 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1720
1721 ctx.VisitDirectDeps(func(m android.Module) {
1722 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1723 depTag := ctx.OtherModuleDependencyTag(m)
1724
1725 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1726 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1727 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1728 }
1729
1730 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1731 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1732 }
1733 })
1734
1735 directUnconditionalExportedFlags := android.Paths{}
1736 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1737 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1738 if exportUnconditionally {
1739 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1740 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1741 directUnconditionalExportedFlags = proguardFlagsForThisModule
1742 }
1743
1744 return ProguardSpecInfo{
1745 Export_proguard_flags_files: exportUnconditionally,
1746 ProguardFlagsFiles: android.NewDepSet[android.Path](
1747 android.POSTORDER,
1748 proguardFlagsForThisModule,
1749 transitiveProguardFlags,
1750 ),
1751 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1752 android.POSTORDER,
1753 directUnconditionalExportedFlags,
1754 transitiveUnconditionalExportedFlags,
1755 ),
1756 }
1757
1758}
1759
Cole Faust75fffb12021-06-13 15:23:16 -07001760// Returns a copy of the supplied flags, but with all the errorprone-related
1761// fields copied to the regular build's fields.
1762func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1763 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1764
1765 if len(flags.errorProneExtraJavacFlags) > 0 {
1766 if len(flags.javacFlags) > 0 {
1767 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1768 } else {
1769 flags.javacFlags = flags.errorProneExtraJavacFlags
1770 }
1771 }
1772 return flags
1773}
1774
Jaewoong Jung26342642021-03-17 15:56:23 -07001775func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1776 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1777
1778 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001779 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001780 if idx >= 0 {
1781 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001782 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001783 jarName += strconv.Itoa(idx)
1784 }
1785
1786 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001787 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001788
1789 if ctx.Config().EmitXrefRules() {
1790 extractionFile := android.PathForModuleOut(ctx, kzipName)
1791 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1792 j.kytheFiles = append(j.kytheFiles, extractionFile)
1793 }
1794
Vadim Spivak3c496f02023-06-08 06:14:59 +00001795 if len(flags.processorPath) > 0 {
1796 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1797 }
1798
Jaewoong Jung26342642021-03-17 15:56:23 -07001799 return classes
1800}
1801
1802// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1803// since some of these flags may be used internally.
1804func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1805 for _, flag := range flags {
1806 flag = strings.TrimSpace(flag)
1807
1808 if !strings.HasPrefix(flag, "-") {
1809 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1810 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1811 ctx.PropertyErrorf("kotlincflags",
1812 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1813 } else if inList(flag, config.KotlincIllegalFlags) {
1814 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1815 } else if flag == "-include-runtime" {
1816 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1817 } else {
1818 args := strings.Split(flag, " ")
1819 if args[0] == "-kotlin-home" {
1820 ctx.PropertyErrorf("kotlincflags",
1821 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1822 }
1823 }
1824 }
1825}
1826
1827func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1828 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001829 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001830
1831 var jars android.Paths
1832 if len(srcFiles) > 0 || len(srcJars) > 0 {
1833 // Compile java sources into turbine.jar.
1834 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1835 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1836 if ctx.Failed() {
1837 return nil, nil
1838 }
1839 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001840 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001841 }
1842
1843 jars = append(jars, extraJars...)
1844
1845 // Combine any static header libraries into classes-header.jar. If there is only
1846 // one input jar this step will be skipped.
1847 jars = append(jars, deps.staticHeaderJars...)
1848
1849 // we cannot skip the combine step for now if there is only one jar
1850 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1851 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1852 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1853 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001854 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001855
1856 if j.expandJarjarRules != nil {
1857 // Transform classes.jar into classes-jarjar.jar
1858 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001859 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1860 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001861 if ctx.Failed() {
1862 return nil, nil
1863 }
1864 }
1865
Colin Cross3d56ed52021-11-18 22:23:12 -08001866 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001867}
1868
1869func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001870 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001871
1872 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1873 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1874
1875 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1876
1877 j.jacocoReportClassesFile = jacocoReportClassesFile
1878
1879 return instrumentedJar
1880}
1881
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001882type providesTransitiveHeaderJars struct {
1883 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001884 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001885 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001886 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001887}
1888
Colin Crossc85750b2022-04-21 12:50:51 -07001889func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001890 return j.transitiveLibsHeaderJars
1891}
1892
Colin Crossc85750b2022-04-21 12:50:51 -07001893func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001894 return j.transitiveStaticLibsHeaderJars
1895}
1896
1897func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1898 directLibs := android.Paths{}
1899 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001900 transitiveLibs := []*android.DepSet[android.Path]{}
1901 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001902 ctx.VisitDirectDeps(func(module android.Module) {
1903 // don't add deps of the prebuilt version of the same library
1904 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1905 return
1906 }
1907
1908 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001909 tag := ctx.OtherModuleDependencyTag(module)
1910 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1911 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1912 directLibs = append(directLibs, dep.HeaderJars...)
1913 } else if tag == staticLibTag {
1914 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001915 } else {
1916 // Don't propagate transitive libs for other kinds of dependencies.
1917 return
1918 }
1919
1920 if dep.TransitiveLibsHeaderJars != nil {
1921 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1922 }
1923 if dep.TransitiveStaticLibsHeaderJars != nil {
1924 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001925 }
1926 })
1927 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1928 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1929}
1930
Jaewoong Jung26342642021-03-17 15:56:23 -07001931func (j *Module) HeaderJars() android.Paths {
1932 if j.headerJarFile == nil {
1933 return nil
1934 }
1935 return android.Paths{j.headerJarFile}
1936}
1937
1938func (j *Module) ImplementationJars() android.Paths {
1939 if j.implementationJarFile == nil {
1940 return nil
1941 }
1942 return android.Paths{j.implementationJarFile}
1943}
1944
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001945func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001946 return j.dexJarFile
1947}
1948
1949func (j *Module) DexJarInstallPath() android.Path {
1950 return j.installFile
1951}
1952
1953func (j *Module) ImplementationAndResourcesJars() android.Paths {
1954 if j.implementationAndResourcesJar == nil {
1955 return nil
1956 }
1957 return android.Paths{j.implementationAndResourcesJar}
1958}
1959
1960func (j *Module) AidlIncludeDirs() android.Paths {
1961 // exportAidlIncludeDirs is type android.Paths already
1962 return j.exportAidlIncludeDirs
1963}
1964
1965func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1966 return j.classLoaderContexts
1967}
1968
1969// Collect information for opening IDE project files in java/jdeps.go.
1970func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1971 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1972 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1973 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1974 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1975 if j.expandJarjarRules != nil {
1976 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1977 }
Yikef6282022022-04-13 20:41:01 +08001978 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1979 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001980 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001981}
1982
1983func (j *Module) CompilerDeps() []string {
1984 jdeps := []string{}
1985 jdeps = append(jdeps, j.properties.Libs...)
1986 jdeps = append(jdeps, j.properties.Static_libs...)
1987 return jdeps
1988}
1989
1990func (j *Module) hasCode(ctx android.ModuleContext) bool {
1991 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1992 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1993}
1994
1995// Implements android.ApexModule
1996func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1997 return j.depIsInSameApex(ctx, dep)
1998}
1999
2000// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00002001func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00002002 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00002003 minSdkVersion := j.MinSdkVersion(ctx)
2004 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07002005 return fmt.Errorf("min_sdk_version is not specified")
2006 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002007 // If the module is compiling against core (via sdk_version), skip comparison check.
2008 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07002009 return nil
2010 }
Spandan Das7fa982c2023-02-24 18:38:56 +00002011 if minSdkVersion.GreaterThan(sdkVersion) {
2012 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002013 }
2014 return nil
2015}
2016
2017func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002018 if j.stem == "" {
2019 panic("Stem() called before stem property was set")
2020 }
2021 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002022}
2023
Jaewoong Jung26342642021-03-17 15:56:23 -07002024func (j *Module) JacocoReportClassesFile() android.Path {
2025 return j.jacocoReportClassesFile
2026}
2027
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002028func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2029 var fromDeps []*android.DepSet[android.Path]
2030 ctx.VisitDirectDeps(func(module android.Module) {
2031 tag := ctx.OtherModuleDependencyTag(module)
2032 if tag == staticLibTag {
2033 depInfo := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2034 if depInfo.TransitiveSrcFiles != nil {
2035 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2036 }
2037 }
2038 })
2039
2040 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2041}
2042
Jaewoong Jung26342642021-03-17 15:56:23 -07002043func (j *Module) IsInstallable() bool {
2044 return Bool(j.properties.Installable)
2045}
2046
2047type sdkLinkType int
2048
2049const (
2050 // TODO(jiyong) rename these for better readability. Make the allowed
2051 // and disallowed link types explicit
2052 // order is important here. See rank()
2053 javaCore sdkLinkType = iota
2054 javaSdk
2055 javaSystem
2056 javaModule
2057 javaSystemServer
2058 javaPlatform
2059)
2060
2061func (lt sdkLinkType) String() string {
2062 switch lt {
2063 case javaCore:
2064 return "core Java API"
2065 case javaSdk:
2066 return "Android API"
2067 case javaSystem:
2068 return "system API"
2069 case javaModule:
2070 return "module API"
2071 case javaSystemServer:
2072 return "system server API"
2073 case javaPlatform:
2074 return "private API"
2075 default:
2076 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2077 }
2078}
2079
2080// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2081// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2082// can't statically depend on modules that use Platform API.
2083func (lt sdkLinkType) rank() int {
2084 return int(lt)
2085}
2086
2087type moduleWithSdkDep interface {
2088 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002089 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002090}
2091
Jiyong Park92315372021-04-02 08:45:46 +09002092func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002093 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002094 case android.SdkCore.DefaultJavaLibraryName(),
2095 "legacy.core.platform.api.stubs",
2096 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002097 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002098 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002099 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002100 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002101 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002102 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002103 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002104 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002105 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002106 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002107 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002108 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002109 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002110 return javaSystem, true
2111 }
2112
2113 if stub, linkType := moduleStubLinkType(name); stub {
2114 return linkType, true
2115 }
2116
Jiyong Park92315372021-04-02 08:45:46 +09002117 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002118 switch ver.Kind {
2119 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002120 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002121 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002122 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002123 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002124 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002125 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002126 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002127 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002128 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002129 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002130 return javaPlatform, false
2131 }
2132
Jiyong Parkf1691d22021-03-29 20:11:58 +09002133 if !ver.Valid() {
2134 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002135 }
2136 return javaSdk, false
2137}
2138
2139// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2140// this module's. See the comment on rank() for details and an example.
2141func (j *Module) checkSdkLinkType(
2142 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2143 if ctx.Host() {
2144 return
2145 }
2146
Jiyong Park92315372021-04-02 08:45:46 +09002147 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002148 if stubs {
2149 return
2150 }
Jiyong Park92315372021-04-02 08:45:46 +09002151 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002152
2153 if myLinkType.rank() < depLinkType.rank() {
2154 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2155 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2156 "property of the source or target module so that target module is built "+
2157 "with the same or smaller API set when compared to the source.",
2158 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2159 }
2160}
2161
2162func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2163 var deps deps
2164
2165 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002166 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002167 if sdkDep.invalidVersion {
2168 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2169 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2170 } else if sdkDep.useFiles {
2171 // sdkDep.jar is actually equivalent to turbine header.jar.
2172 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002173 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002174 deps.aidlPreprocess = sdkDep.aidl
2175 } else {
2176 deps.aidlPreprocess = sdkDep.aidl
2177 }
2178 }
2179
Jiyong Park92315372021-04-02 08:45:46 +09002180 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002181
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002182 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002183 ctx.VisitDirectDeps(func(module android.Module) {
2184 otherName := ctx.OtherModuleName(module)
2185 tag := ctx.OtherModuleDependencyTag(module)
2186
2187 if IsJniDepTag(tag) {
2188 // Handled by AndroidApp.collectAppDeps
2189 return
2190 }
2191 if tag == certificateTag {
2192 // Handled by AndroidApp.collectAppDeps
2193 return
2194 }
2195
2196 if dep, ok := module.(SdkLibraryDependency); ok {
2197 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002198 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002199 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2200 deps.classpath = append(deps.classpath, depHeaderJars...)
2201 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002202 case staticLibTag:
2203 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2204 }
2205 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2206 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2207 if sdkLinkType != javaPlatform &&
2208 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2209 // dep is a sysprop implementation library, but this module is not linking against
2210 // the platform, so it gets the sysprop public stubs library instead. Replace
2211 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2212 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2213 dep = syspropDep.JavaInfo
2214 }
2215 switch tag {
2216 case bootClasspathTag:
2217 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002218 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002219 if _, ok := module.(*Plugin); ok {
2220 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2221 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002222 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002223 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002224 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2225 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2226 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2227 case java9LibTag:
2228 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2229 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002230 if _, ok := module.(*Plugin); ok {
2231 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2232 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002233 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2234 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2235 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2236 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2237 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2238 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2239 // Turbine doesn't run annotation processors, so any module that uses an
2240 // annotation processor that generates API is incompatible with the turbine
2241 // optimization.
2242 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2243 case pluginTag:
2244 if plugin, ok := module.(*Plugin); ok {
2245 if plugin.pluginProperties.Processor_class != nil {
2246 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2247 } else {
2248 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2249 }
2250 // Turbine doesn't run annotation processors, so any module that uses an
2251 // annotation processor that generates API is incompatible with the turbine
2252 // optimization.
2253 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2254 } else {
2255 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2256 }
2257 case errorpronePluginTag:
2258 if _, ok := module.(*Plugin); ok {
2259 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2260 } else {
2261 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2262 }
2263 case exportedPluginTag:
2264 if plugin, ok := module.(*Plugin); ok {
2265 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2266 if plugin.pluginProperties.Processor_class != nil {
2267 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2268 }
2269 // Turbine doesn't run annotation processors, so any module that uses an
2270 // annotation processor that generates API is incompatible with the turbine
2271 // optimization.
2272 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2273 } else {
2274 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2275 }
2276 case kotlinStdlibTag:
2277 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2278 case kotlinAnnotationsTag:
2279 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002280 case kotlinPluginTag:
2281 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002282 case syspropPublicStubDepTag:
2283 // This is a sysprop implementation library, forward the JavaInfoProvider from
2284 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2285 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2286 JavaInfo: dep,
2287 })
2288 }
2289 } else if dep, ok := module.(android.SourceFileProducer); ok {
2290 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002291 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002292 checkProducesJars(ctx, dep)
2293 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002294 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002295 case staticLibTag:
2296 checkProducesJars(ctx, dep)
2297 deps.classpath = append(deps.classpath, dep.Srcs()...)
2298 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2299 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2300 }
2301 } else {
2302 switch tag {
2303 case bootClasspathTag:
2304 // If a system modules dependency has been added to the bootclasspath
2305 // then add its libs to the bootclasspath.
2306 sm := module.(SystemModulesProvider)
2307 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2308
2309 case systemModulesTag:
2310 if deps.systemModules != nil {
2311 panic("Found two system module dependencies")
2312 }
2313 sm := module.(SystemModulesProvider)
2314 outputDir, outputDeps := sm.OutputDirAndDeps()
2315 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002316
2317 case instrumentationForTag:
2318 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 -07002319 }
2320 }
2321
2322 addCLCFromDep(ctx, module, j.classLoaderContexts)
2323 })
2324
2325 return deps
2326}
2327
2328func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2329 deps.processorPath = append(deps.processorPath, pluginJars...)
2330 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2331}
2332
2333// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2334// this interface.
2335type ProvidesUsesLib interface {
2336 ProvidesUsesLib() *string
2337}
2338
2339func (j *Module) ProvidesUsesLib() *string {
2340 return j.usesLibraryProperties.Provides_uses_lib
2341}
satayev1c564cc2021-05-25 19:50:30 +01002342
2343type ModuleWithStem interface {
2344 Stem() string
2345}
2346
2347var _ ModuleWithStem = (*Module)(nil)