blob: e52ceddf7101b9c99ff1740bccf324bc61f00277 [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
27 "android/soong/android"
28 "android/soong/dexpreopt"
29 "android/soong/java/config"
30)
31
32// This file contains the definition and the implementation of the base module that most
33// source-based Java module structs embed.
34
35// TODO:
36// Autogenerated files:
37// Renderscript
38// Post-jar passes:
39// Proguard
40// Rmtypedefs
41// DroidDoc
42// Findbugs
43
44// Properties that are common to most Java modules, i.e. whether it's a host or device module.
45type CommonProperties struct {
46 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
47 // or .aidl files.
48 Srcs []string `android:"path,arch_variant"`
49
50 // list Kotlin of source files containing Kotlin code that should be treated as common code in
51 // a codebase that supports Kotlin multiplatform. See
52 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
53 Common_srcs []string `android:"path,arch_variant"`
54
55 // list of source files that should not be used to build the Java module.
56 // This is most useful in the arch/multilib variants to remove non-common files
57 Exclude_srcs []string `android:"path,arch_variant"`
58
59 // list of directories containing Java resources
60 Java_resource_dirs []string `android:"arch_variant"`
61
62 // list of directories that should be excluded from java_resource_dirs
63 Exclude_java_resource_dirs []string `android:"arch_variant"`
64
65 // list of files to use as Java resources
66 Java_resources []string `android:"path,arch_variant"`
67
68 // list of files that should be excluded from java_resources and java_resource_dirs
69 Exclude_java_resources []string `android:"path,arch_variant"`
70
71 // list of module-specific flags that will be used for javac compiles
72 Javacflags []string `android:"arch_variant"`
73
74 // list of module-specific flags that will be used for kotlinc compiles
75 Kotlincflags []string `android:"arch_variant"`
76
77 // list of java libraries that will be in the classpath
78 Libs []string `android:"arch_variant"`
79
80 // list of java libraries that will be compiled into the resulting jar
81 Static_libs []string `android:"arch_variant"`
82
Jihoon Kang381c2fa2023-06-01 22:17:32 +000083 // list of java libraries that should not be used to build this module
84 Exclude_static_libs []string `android:"arch_variant"`
85
Jaewoong Jung26342642021-03-17 15:56:23 -070086 // manifest file to be included in resulting jar
87 Manifest *string `android:"path"`
88
89 // if not blank, run jarjar using the specified rules file
90 Jarjar_rules *string `android:"path,arch_variant"`
91
92 // If not blank, set the java version passed to javac as -source and -target
93 Java_version *string
94
95 // If set to true, allow this module to be dexed and installed on devices. Has no
96 // effect on host modules, which are always considered installable.
97 Installable *bool
98
99 // If set to true, include sources used to compile the module in to the final jar
100 Include_srcs *bool
101
102 // If not empty, classes are restricted to the specified packages and their sub-packages.
103 // This restriction is checked after applying jarjar rules and including static libs.
104 Permitted_packages []string
105
106 // List of modules to use as annotation processors
107 Plugins []string
108
109 // List of modules to export to libraries that directly depend on this library as annotation
110 // processors. Note that if the plugins set generates_api: true this will disable the turbine
111 // optimization on modules that depend on this module, which will reduce parallelism and cause
112 // more recompilation.
113 Exported_plugins []string
114
115 // The number of Java source entries each Javac instance can process
116 Javac_shard_size *int64
117
118 // Add host jdk tools.jar to bootclasspath
119 Use_tools_jar *bool
120
121 Openjdk9 struct {
122 // List of source files that should only be used when passing -source 1.9 or higher
123 Srcs []string `android:"path"`
124
125 // List of javac flags that should only be used when passing -source 1.9 or higher
126 Javacflags []string
127 }
128
129 // When compiling language level 9+ .java code in packages that are part of
130 // a system module, patch_module names the module that your sources and
131 // dependencies should be patched into. The Android runtime currently
132 // doesn't implement the JEP 261 module system so this option is only
133 // supported at compile time. It should only be needed to compile tests in
134 // packages that exist in libcore and which are inconvenient to move
135 // elsewhere.
Liz Kammer0a470a32023-10-05 17:02:00 -0400136 Patch_module *string
Jaewoong Jung26342642021-03-17 15:56:23 -0700137
138 Jacoco struct {
139 // List of classes to include for instrumentation with jacoco to collect coverage
140 // information at runtime when building with coverage enabled. If unset defaults to all
141 // classes.
142 // Supports '*' as the last character of an entry in the list as a wildcard match.
143 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
144 // it matches classes in the package that have the class name as a prefix.
145 Include_filter []string
146
147 // List of classes to exclude from instrumentation with jacoco to collect coverage
148 // information at runtime when building with coverage enabled. Overrides classes selected
149 // by the include_filter property.
150 // Supports '*' as the last character of an entry in the list as a wildcard match.
151 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
152 // it matches classes in the package that have the class name as a prefix.
153 Exclude_filter []string
154 }
155
156 Errorprone struct {
157 // List of javac flags that should only be used when running errorprone.
158 Javacflags []string
159
160 // List of java_plugin modules that provide extra errorprone checks.
161 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700162
Cole Faust2b1536e2021-06-18 12:25:54 -0700163 // This property can be in 3 states. When set to true, errorprone will
164 // be run during the regular build. When set to false, errorprone will
165 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
166 // environment variable is true. Setting this to false will improve build
167 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700168 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700169 }
170
171 Proto struct {
172 // List of extra options that will be passed to the proto generator.
173 Output_params []string
174 }
175
Sam Delmericoc7593722022-08-31 15:57:52 -0400176 // If true, then jacocoagent is automatically added as a libs dependency so that
177 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700178 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000179 // If true, then the module supports statically including the jacocoagent
180 // into the library.
181 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700182
183 // List of files to include in the META-INF/services folder of the resulting jar.
184 Services []string `android:"path,arch_variant"`
185
186 // If true, package the kotlin stdlib into the jar. Defaults to true.
187 Static_kotlin_stdlib *bool `android:"arch_variant"`
188
189 // A list of java_library instances that provide additional hiddenapi annotations for the library.
190 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700191
192 // Additional srcJars tacked in by GeneratedJavaLibraryModule
193 Generated_srcjars []android.Path `android:"mutated"`
Mark Whitea15790a2023-08-22 21:28:11 +0000194
195 // If true, then only the headers are built and not the implementation jar.
Liz Kammer60772632023-10-05 17:18:44 -0400196 Headers_only *bool
Cole Faust2b64af82023-12-13 18:22:18 -0800197
198 // A list of files or dependencies to make available to the build sandbox. This is
199 // useful if source files are symlinks, the targets of the symlinks must be listed here.
200 // Note that currently not all actions implemented by android_apps are sandboxed, so you
201 // may only see this being necessary in lint builds.
202 Compile_data []string `android:"path"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700203}
204
205// Properties that are specific to device modules. Host module factories should not add these when
206// constructing a new module.
207type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000208 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000209 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000210 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000211 // 1) numerical API level, "current", "none", or "core_platform"
212 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
213 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
214 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700215 Sdk_version *string
216
217 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000218 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700219 Min_sdk_version *string
220
satayev0a420e72021-11-29 17:25:52 +0000221 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
222 // Defaults to empty string "". See sdk_version for possible values.
223 Max_sdk_version *string
224
William Loh5a082f92022-05-17 20:21:50 +0000225 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
226 // Defaults to empty string "". See sdk_version for possible values.
227 Replace_max_sdk_version_placeholder *string
228
Jaewoong Jung26342642021-03-17 15:56:23 -0700229 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000230 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700231 Target_sdk_version *string
232
233 // Whether to compile against the platform APIs instead of an SDK.
234 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000235 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700236 Platform_apis *bool
237
238 Aidl struct {
239 // Top level directories to pass to aidl tool
240 Include_dirs []string
241
242 // Directories rooted at the Android.bp file to pass to aidl tool
243 Local_include_dirs []string
244
245 // directories that should be added as include directories for any aidl sources of modules
246 // that depend on this module, as well as to aidl for this module.
247 Export_include_dirs []string
248
249 // whether to generate traces (for systrace) for this interface
250 Generate_traces *bool
251
252 // whether to generate Binder#GetTransaction name method.
253 Generate_get_transaction_name *bool
254
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100255 // whether all interfaces should be annotated with required permissions.
256 Enforce_permissions *bool
257
258 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
259 Enforce_permissions_exceptions []string `android:"path"`
260
Jaewoong Jung26342642021-03-17 15:56:23 -0700261 // list of flags that will be passed to the AIDL compiler
262 Flags []string
263 }
264
265 // If true, export a copy of the module as a -hostdex module for host testing.
266 Hostdex *bool
267
268 Target struct {
269 Hostdex struct {
270 // Additional required dependencies to add to -hostdex modules.
271 Required []string
272 }
273 }
274
275 // When targeting 1.9 and above, override the modules to use with --system,
276 // otherwise provides defaults libraries to add to the bootclasspath.
277 System_modules *string
278
Jaewoong Jung26342642021-03-17 15:56:23 -0700279 IsSDKLibrary bool `blueprint:"mutated"`
280
281 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
282 // Defaults to false.
283 V4_signature *bool
284
285 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
286 // public stubs library.
287 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000288
289 HiddenAPIPackageProperties
290 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700291}
292
Jooyung Han01d80d82022-01-08 12:16:32 +0900293// Device properties that can be overridden by overriding module (e.g. override_android_app)
294type OverridableDeviceProperties struct {
295 // set the name of the output. If not set, `name` is used.
296 // To override a module with this property set, overriding module might need to set this as well.
297 // Otherwise, both the overridden and the overriding modules will have the same output name, which
298 // can cause the duplicate output error.
299 Stem *string
300}
301
Jaewoong Jung26342642021-03-17 15:56:23 -0700302// Functionality common to Module and Import
303//
304// It is embedded in Module so its functionality can be used by methods in Module
305// but it is currently only initialized by Import and Library.
306type embeddableInModuleAndImport struct {
307
308 // Functionality related to this being used as a component of a java_sdk_library.
309 EmbeddableSdkLibraryComponent
310}
311
Paul Duffin71b33cc2021-06-23 11:39:47 +0100312func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
313 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700314}
315
316// Module/Import's DepIsInSameApex(...) delegates to this method.
317//
318// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
319// the one provided by ApexModuleBase.
320func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
321 // dependencies other than the static linkage are all considered crossing APEX boundary
322 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
323 return true
324 }
325 return false
326}
327
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100328// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
329// or an invalid path describing the reason it is invalid.
330//
331// It is unset if a dex jar isn't applicable, i.e. no build rule has been
332// requested to create one.
333//
334// If a dex jar has been requested to be built then it is set, and it may be
335// either a valid android.Path, or invalid with a reason message. The latter
336// happens if the source that should produce the dex file isn't able to.
337//
338// E.g. it is invalid with a reason message if there is a prebuilt APEX that
339// could produce the dex jar through a deapexer module, but the APEX isn't
340// installable so doing so wouldn't be safe.
341type OptionalDexJarPath struct {
342 isSet bool
343 path android.OptionalPath
344}
345
346// IsSet returns true if a path has been set, either invalid or valid.
347func (o OptionalDexJarPath) IsSet() bool {
348 return o.isSet
349}
350
351// Valid returns true if there is a path that is valid.
352func (o OptionalDexJarPath) Valid() bool {
353 return o.isSet && o.path.Valid()
354}
355
356// Path returns the valid path, or panics if it's either not set or is invalid.
357func (o OptionalDexJarPath) Path() android.Path {
358 if !o.isSet {
359 panic("path isn't set")
360 }
361 return o.path.Path()
362}
363
364// PathOrNil returns the path if it's set and valid, or else nil.
365func (o OptionalDexJarPath) PathOrNil() android.Path {
366 if o.Valid() {
367 return o.Path()
368 }
369 return nil
370}
371
372// InvalidReason returns the reason for an invalid path, which is never "". It
373// returns "" for an unset or valid path.
374func (o OptionalDexJarPath) InvalidReason() string {
375 if !o.isSet {
376 return ""
377 }
378 return o.path.InvalidReason()
379}
380
381func (o OptionalDexJarPath) String() string {
382 if !o.isSet {
383 return "<unset>"
384 }
385 return o.path.String()
386}
387
388// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
389func makeUnsetDexJarPath() OptionalDexJarPath {
390 return OptionalDexJarPath{isSet: false}
391}
392
393// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
394// the given OptionalPath, which may be valid or invalid.
395func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
396 return OptionalDexJarPath{isSet: true, path: path}
397}
398
399// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
400// valid given path. It returns an unset OptionalDexJarPath if the given path is
401// nil.
402func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
403 if path == nil {
404 return makeUnsetDexJarPath()
405 }
406 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
407}
408
Jaewoong Jung26342642021-03-17 15:56:23 -0700409// Module contains the properties and members used by all java module types
410type Module struct {
411 android.ModuleBase
412 android.DefaultableModuleBase
413 android.ApexModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700414
415 // Functionality common to Module and Import.
416 embeddableInModuleAndImport
417
418 properties CommonProperties
419 protoProperties android.ProtoProperties
420 deviceProperties DeviceProperties
421
Jooyung Han01d80d82022-01-08 12:16:32 +0900422 overridableDeviceProperties OverridableDeviceProperties
423
Jaewoong Jung26342642021-03-17 15:56:23 -0700424 // jar file containing header classes including static library dependencies, suitable for
425 // inserting into the bootclasspath/classpath of another compile
426 headerJarFile android.Path
427
428 // jar file containing implementation classes including static library dependencies but no
429 // resources
430 implementationJarFile android.Path
431
432 // jar file containing only resources including from static library dependencies
433 resourceJar android.Path
434
435 // args and dependencies to package source files into a srcjar
436 srcJarArgs []string
437 srcJarDeps android.Paths
438
Anton Hansson0e73f9e2023-09-20 13:39:57 +0000439 // the source files of this module and all its static dependencies
440 transitiveSrcFiles *android.DepSet[android.Path]
441
Jaewoong Jung26342642021-03-17 15:56:23 -0700442 // jar file containing implementation classes and resources including static library
443 // dependencies
444 implementationAndResourcesJar android.Path
445
446 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100447 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700448
449 // output file containing uninstrumented classes that will be instrumented by jacoco
450 jacocoReportClassesFile android.Path
451
452 // output file of the module, which may be a classes jar or a dex jar
453 outputFile android.Path
454 extraOutputFiles android.Paths
455
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100456 exportAidlIncludeDirs android.Paths
457 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700458
459 logtagsSrcs android.Paths
460
461 // installed file for binary dependency
462 installFile android.Path
463
Colin Cross3108ce12021-11-10 14:38:50 -0800464 // installed file for hostdex copy
465 hostdexInstallFile android.InstallPath
466
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800467 // list of unique .java and .kt source files
468 uniqueSrcFiles android.Paths
469
470 // list of srcjars that was passed to javac
471 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700472
473 // manifest file to use instead of properties.Manifest
474 overrideManifest android.OptionalPath
475
Jaewoong Jung26342642021-03-17 15:56:23 -0700476 // list of plugins that this java module is exporting
477 exportedPluginJars android.Paths
478
479 // list of plugins that this java module is exporting
480 exportedPluginClasses []string
481
482 // if true, the exported plugins generate API and require disabling turbine.
483 exportedDisableTurbine bool
484
485 // list of source files, collected from srcFiles with unique java and all kt files,
486 // will be used by android.IDEInfo struct
487 expandIDEInfoCompiledSrcs []string
488
489 // expanded Jarjar_rules
490 expandJarjarRules android.Path
491
Jaewoong Jung26342642021-03-17 15:56:23 -0700492 // Extra files generated by the module type to be added as java resources.
493 extraResources android.Paths
494
495 hiddenAPI
496 dexer
497 dexpreopter
498 usesLibrary
499 linter
500
501 // list of the xref extraction files
502 kytheFiles android.Paths
503
Jaewoong Jung26342642021-03-17 15:56:23 -0700504 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900505
506 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000507 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000508 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400509
510 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000511
512 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000513
514 // output file name based on Stem property.
515 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
516 // or the module should override Stem().
517 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700518
Colin Crossd788b3e2023-11-28 13:14:56 -0800519 // Single aconfig "cache file" merged from this module and all dependencies.
520 mergedAconfigFiles map[string]android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700521}
522
Jiyong Park92315372021-04-02 08:45:46 +0900523func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
524 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900525 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700526 return nil
527 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900528 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000529 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700530 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
531 } else {
532 // Treat stable core platform as stable.
533 return nil
534 }
535 } else {
536 return fmt.Errorf("non stable SDK %v", sdkVersion)
537 }
538}
539
540// checkSdkVersions enforces restrictions around SDK dependencies.
541func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
542 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900543 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900544 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700545 ctx.PropertyErrorf("sdk_version",
546 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
547 }
548 }
549 }
550
551 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
552 // See rank() for details.
553 ctx.VisitDirectDeps(func(module android.Module) {
554 tag := ctx.OtherModuleDependencyTag(module)
555 switch module.(type) {
556 // TODO(satayev): cover other types as well, e.g. imports
557 case *Library, *AndroidLibrary:
558 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400559 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700560 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
561 }
562 }
563 })
564}
565
566func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900567 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700568 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900569 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700570 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000571 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 -0700572 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000573 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 -0700574 }
575
576 }
577}
578
Mark Whitea15790a2023-08-22 21:28:11 +0000579func (j *Module) checkHeadersOnly(ctx android.ModuleContext) {
580 if _, ok := ctx.Module().(android.SdkContext); ok {
Liz Kammer60772632023-10-05 17:18:44 -0400581 headersOnly := proptools.Bool(j.properties.Headers_only)
Mark Whitea15790a2023-08-22 21:28:11 +0000582 installable := proptools.Bool(j.properties.Installable)
583
584 if headersOnly && installable {
585 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.")
586 }
587 }
588}
589
Jaewoong Jung26342642021-03-17 15:56:23 -0700590func (j *Module) addHostProperties() {
591 j.AddProperties(
592 &j.properties,
593 &j.protoProperties,
594 &j.usesLibraryProperties,
595 )
596}
597
598func (j *Module) addHostAndDeviceProperties() {
599 j.addHostProperties()
600 j.AddProperties(
601 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900602 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700603 &j.dexer.dexProperties,
604 &j.dexpreoptProperties,
605 &j.linter.properties,
606 )
607}
608
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000609// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
610// makes it available through the hiddenAPIPropertyInfoProvider.
611func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
612 hiddenAPIInfo := newHiddenAPIPropertyInfo()
613
614 // Populate with flag file paths from the properties.
615 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
616
617 // Populate with package rules from the properties.
618 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
619
Colin Cross40213022023-12-13 15:19:49 -0800620 android.SetProvider(ctx, hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000621}
622
Jaewoong Jung26342642021-03-17 15:56:23 -0700623func (j *Module) OutputFiles(tag string) (android.Paths, error) {
624 switch tag {
625 case "":
626 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
627 case android.DefaultDistTag:
628 return android.Paths{j.outputFile}, nil
629 case ".jar":
630 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700631 case ".hjar":
632 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700633 case ".proguard_map":
634 if j.dexer.proguardDictionary.Valid() {
635 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
636 }
637 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Joe Onoratoffac9be2023-08-19 19:48:34 -0700638 case ".generated_srcjars":
639 return j.properties.Generated_srcjars, nil
Thiébaud Weksteend0544362023-09-29 10:26:43 +1000640 case ".lint":
641 if j.linter.outputs.xml != nil {
642 return android.Paths{j.linter.outputs.xml}, nil
643 }
644 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
Jaewoong Jung26342642021-03-17 15:56:23 -0700645 default:
646 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
647 }
648}
649
650var _ android.OutputFileProducer = (*Module)(nil)
651
652func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
653 initJavaModule(module, hod, false)
654}
655
656func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
657 initJavaModule(module, hod, true)
658}
659
660func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
661 multilib := android.MultilibCommon
662 if multiTargets {
663 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
664 } else {
665 android.InitAndroidArchModule(module, hod, multilib)
666 }
667 android.InitDefaultableModule(module)
668}
669
670func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
671 return j.properties.Instrument &&
672 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
673 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
674}
675
676func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000677 return j.properties.Supports_static_instrumentation &&
678 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700679 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
680 ctx.Config().UnbundledBuild())
681}
682
683func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
684 // Force enable the instrumentation for java code that is built for APEXes ...
685 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
686 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
Colin Crossff694a82023-12-13 15:54:49 -0800687 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -0700688 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
689 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
690 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
691 return true
692 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
693 return true
694 }
695 }
696 return false
697}
698
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400699func (j *Module) setInstrument(value bool) {
700 j.properties.Instrument = value
701}
702
Jiyong Park92315372021-04-02 08:45:46 +0900703func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
704 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700705}
706
Jiyong Parkf1691d22021-03-29 20:11:58 +0900707func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700708 return proptools.String(j.deviceProperties.System_modules)
709}
710
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000711func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700712 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000713 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700714 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000715 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700716}
717
Yu Liuf2b94012023-09-19 15:09:10 -0700718func (j *Module) GetDeviceProperties() *DeviceProperties {
719 return &j.deviceProperties
720}
721
Spandan Dasa26eda72023-03-02 00:56:06 +0000722func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
723 if j.deviceProperties.Max_sdk_version != nil {
724 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
725 }
726 // Default is PrivateApiLevel
727 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000728}
729
Spandan Dasa26eda72023-03-02 00:56:06 +0000730func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
731 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
732 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
733 }
734 // Default is PrivateApiLevel
735 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000736}
737
Jiyong Parkf1691d22021-03-29 20:11:58 +0900738func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000739 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900740}
741
Spandan Dasca70fc42023-03-01 23:38:49 +0000742func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900743 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000744 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900745 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000746 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700747}
748
749func (j *Module) AvailableFor(what string) bool {
750 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
751 // Exception: for hostdex: true libraries, the platform variant is created
752 // even if it's not marked as available to platform. In that case, the platform
753 // variant is used only for the hostdex and not installed to the device.
754 return true
755 }
756 return j.ApexModuleBase.AvailableFor(what)
757}
758
759func (j *Module) deps(ctx android.BottomUpMutatorContext) {
760 if ctx.Device() {
761 j.linter.deps(ctx)
762
Jiyong Parkf1691d22021-03-29 20:11:58 +0900763 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700764
765 if j.deviceProperties.SyspropPublicStub != "" {
766 // This is a sysprop implementation library that has a corresponding sysprop public
767 // stubs library, and a dependency on it so that dependencies on the implementation can
768 // be forwarded to the public stubs library when necessary.
769 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
770 }
771 }
772
773 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000774
775 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700776 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
777
778 // Add dependency on libraries that provide additional hidden api annotations.
779 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
780
781 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
782 // Require java_sdk_library at inter-partition java dependency to ensure stable
783 // interface between partitions. If inter-partition java_library dependency is detected,
784 // raise build error because java_library doesn't have a stable interface.
785 //
786 // Inputs:
787 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
788 // if true, enable enforcement
789 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
790 // exception list of java_library names to allow inter-partition dependency
791 for idx := range j.properties.Libs {
792 if libDeps[idx] == nil {
793 continue
794 }
795
796 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
797 // java_sdk_library is always allowed at inter-partition dependency.
798 // So, skip check.
799 if _, ok := javaDep.(*SdkLibrary); ok {
800 continue
801 }
802
803 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
804 }
805 }
806 }
807
808 // For library dependencies that are component libraries (like stubs), add the implementation
809 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
810 for _, dep := range libDeps {
811 if dep != nil {
812 if component, ok := dep.(SdkLibraryComponentDependency); ok {
813 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100814 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100815 tag := usesLibReqTag
816 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
817 tag = usesLibOptTag
818 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100819 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700820 }
821 }
822 }
823 }
824
825 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
826 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
827 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
828
829 android.ProtoDeps(ctx, &j.protoProperties)
830 if j.hasSrcExt(".proto") {
831 protoDeps(ctx, &j.protoProperties)
832 }
833
834 if j.hasSrcExt(".kt") {
835 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
836 // Kotlin files
837 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
838 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700839 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700840 }
841
842 // Framework libraries need special handling in static coverage builds: they should not have
843 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
844 // the same jacoco classes coming from different bootclasspath jars.
845 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
846 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
847 j.properties.Instrument = true
848 }
849 } else if j.shouldInstrumentStatic(ctx) {
850 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
851 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700852
853 if j.useCompose() {
854 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
855 "androidx.compose.compiler_compiler-hosted")
856 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700857}
858
859func hasSrcExt(srcs []string, ext string) bool {
860 for _, src := range srcs {
861 if filepath.Ext(src) == ext {
862 return true
863 }
864 }
865
866 return false
867}
868
869func (j *Module) hasSrcExt(ext string) bool {
870 return hasSrcExt(j.properties.Srcs, ext)
871}
872
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100873func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
874 var flags string
875
876 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
877 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
878 flags = "-Wmissing-permission-annotation -Werror"
879 }
880 }
881 return flags
882}
883
Jaewoong Jung26342642021-03-17 15:56:23 -0700884func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000885 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700886
887 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
888 aidlIncludes = append(aidlIncludes,
889 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
890 aidlIncludes = append(aidlIncludes,
891 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
892
893 var flags []string
894 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000895 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700896
897 flags = append(flags, j.deviceProperties.Aidl.Flags...)
898
899 if aidlPreprocess.Valid() {
900 flags = append(flags, "-p"+aidlPreprocess.String())
901 deps = append(deps, aidlPreprocess.Path())
902 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000903 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700904 }
905
906 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000907 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700908 }
909
910 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000911 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 }
913
Sam Delmerico2351eac2022-05-24 17:10:02 +0000914 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700915 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000916 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700917 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000918 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
919 // add flags for dirs containing AIDL srcs that haven't been specified yet
920 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700921
Zim8774ae12022-08-17 11:46:34 +0100922 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000923 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100924 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700925 flags = append(flags, "-t")
926 }
927
928 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
929 flags = append(flags, "--transaction_names")
930 }
931
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100932 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
933 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
934 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
935 }
936
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000937 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900938 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
939
Jaewoong Jung26342642021-03-17 15:56:23 -0700940 return strings.Join(flags, " "), deps
941}
942
943func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
944
945 var flags javaBuilderFlags
946
947 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900948 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700949
Cole Faust2b1536e2021-06-18 12:25:54 -0700950 epEnabled := j.properties.Errorprone.Enabled
951 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100952 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700953 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
954 }
955
956 errorProneFlags := []string{
957 "-Xplugin:ErrorProne",
958 "${config.ErrorProneChecks}",
959 }
960 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
961
Colin Cross8bf6cad2022-02-28 13:07:03 -0800962 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700963 "'" + strings.Join(errorProneFlags, " ") + "'"
964 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
965 }
966
967 // classpath
968 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
969 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700970 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700971 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
972 flags.processorPath = append(flags.processorPath, deps.processorPath...)
973 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
974
975 flags.processors = append(flags.processors, deps.processorClasses...)
976 flags.processors = android.FirstUniqueStrings(flags.processors)
977
978 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900979 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700980 // Give host-side tools a version of OpenJDK's standard libraries
981 // close to what they're targeting. As of Dec 2017, AOSP is only
982 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
983 //
984 // When building with OpenJDK 8, the following should have no
985 // effect since those jars would be available by default.
986 //
987 // When building with OpenJDK 9 but targeting a version < 1.8,
988 // putting them on the bootclasspath means that:
989 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
990 // b) references to existing APIs are not reinterpreted in an
991 // OpenJDK 9-specific way, eg. calls to subclasses of
992 // java.nio.Buffer as in http://b/70862583
993 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
994 flags.bootClasspath = append(flags.bootClasspath,
995 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
996 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
997 if Bool(j.properties.Use_tools_jar) {
998 flags.bootClasspath = append(flags.bootClasspath,
999 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
1000 }
1001 }
1002
1003 // systemModules
1004 flags.systemModules = deps.systemModules
1005
Jaewoong Jung26342642021-03-17 15:56:23 -07001006 return flags
1007}
1008
1009func (j *Module) collectJavacFlags(
1010 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
1011 // javac flags.
1012 javacFlags := j.properties.Javacflags
Mythri Alle4b9f6182023-10-25 15:17:11 +00001013 var needsDebugInfo bool
Jaewoong Jung26342642021-03-17 15:56:23 -07001014
Mythri Alle4b9f6182023-10-25 15:17:11 +00001015 needsDebugInfo = false
1016 for _, flag := range javacFlags {
1017 if strings.HasPrefix(flag, "-g") {
1018 needsDebugInfo = true
1019 }
1020 }
1021
1022 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() && !needsDebugInfo {
Jaewoong Jung26342642021-03-17 15:56:23 -07001023 // For non-host binaries, override the -g flag passed globally to remove
1024 // local variable debug info to reduce disk and memory usage.
1025 javacFlags = append(javacFlags, "-g:source,lines")
1026 }
1027 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
1028
1029 if flags.javaVersion.usesJavaModules() {
1030 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001031 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1032 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1033 ctx.PropertyErrorf("openjdk9.javacflags", "JDK version defaults to higher than 9")
1034 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001035
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001036 if flags.javaVersion.usesJavaModules() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001037 if j.properties.Patch_module != nil {
1038 // Manually specify build directory in case it is not under the repo root.
1039 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1040 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001041 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001042
Jaewoong Jung26342642021-03-17 15:56:23 -07001043 classPath := flags.classpath.FormJavaClassPath("")
1044 if classPath != "" {
1045 patchPaths = append(patchPaths, classPath)
1046 }
1047 javacFlags = append(
1048 javacFlags,
1049 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1050 }
1051 }
1052
1053 if len(javacFlags) > 0 {
1054 // optimization.
1055 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1056 flags.javacFlags = "$javacFlags"
1057 }
1058
1059 return flags
1060}
1061
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001062func (j *Module) AddJSONData(d *map[string]interface{}) {
1063 (&j.ModuleBase).AddJSONData(d)
1064 (*d)["Java"] = map[string]interface{}{
1065 "SourceExtensions": j.sourceExtensions,
1066 }
1067
1068}
1069
usta0391ca42023-09-19 15:51:59 -04001070func (j *Module) addGeneratedSrcJars(path android.Path) {
1071 j.properties.Generated_srcjars = append(j.properties.Generated_srcjars, path)
Joe Onorato175073c2023-06-01 14:42:59 -07001072}
1073
Colin Cross4eae06d2023-06-20 22:40:02 -07001074func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001075 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1076
1077 deps := j.collectDeps(ctx)
1078 flags := j.collectBuilderFlags(ctx, deps)
1079
1080 if flags.javaVersion.usesJavaModules() {
1081 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
Liz Kammer9f52f6b2023-10-06 16:47:00 -04001082 } else if len(j.properties.Openjdk9.Javacflags) > 0 {
1083 // java version defaults higher than openjdk 9, these conditionals should no longer be necessary
1084 ctx.PropertyErrorf("openjdk9.srcs", "JDK version defaults to higher than 9")
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001086
Jaewoong Jung26342642021-03-17 15:56:23 -07001087 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001088 j.sourceExtensions = []string{}
1089 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1090 if hasSrcExt(srcFiles.Strings(), ext) {
1091 j.sourceExtensions = append(j.sourceExtensions, ext)
1092 }
1093 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001094 if hasSrcExt(srcFiles.Strings(), ".proto") {
1095 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1096 }
1097
1098 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1099 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1100 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1101 }
1102
Sam Delmerico2351eac2022-05-24 17:10:02 +00001103 aidlSrcs := srcFiles.FilterByExt(".aidl")
1104 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1105
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001106 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 srcFiles = j.genSources(ctx, srcFiles, flags)
1108
1109 // Collect javac flags only after computing the full set of srcFiles to
1110 // ensure that the --patch-module lookup paths are complete.
1111 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1112
1113 srcJars := srcFiles.FilterByExt(".srcjar")
1114 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001115 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001116 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001117 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001118
1119 if j.properties.Jarjar_rules != nil {
1120 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1121 }
1122
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001123 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001124
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001125 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001127 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001128 if _, found := set[v.String()]; !found {
1129 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001130 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001131 }
1132 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001133 var uniqueKtFiles android.Paths
1134 for _, v := range srcFiles.FilterByExt(".kt") {
1135 if _, found := set[v.String()]; !found {
1136 set[v.String()] = true
1137 uniqueKtFiles = append(uniqueKtFiles, v)
1138 }
1139 }
1140
1141 var uniqueSrcFiles android.Paths
1142 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1143 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1144 j.uniqueSrcFiles = uniqueSrcFiles
Colin Cross40213022023-12-13 15:19:49 -08001145 android.SetProvider(ctx, blueprint.SrcsFileProviderKey, blueprint.SrcsFileProviderData{SrcPaths: uniqueSrcFiles.Strings()})
Jaewoong Jung26342642021-03-17 15:56:23 -07001146
Colin Crossb5db4012022-03-28 17:12:39 -07001147 // We don't currently run annotation processors in turbine, which means we can't use turbine
1148 // generated header jars when an annotation processor that generates API is enabled. One
1149 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1150 // is used to run all of the annotation processors.
1151 disableTurbine := deps.disableTurbine
1152
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001153 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1155
1156 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001157 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001158
Colin Cross4eae06d2023-06-20 22:40:02 -07001159 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1160 // any dependencies so that it can override any non-final R classes from dependencies with the
1161 // final R classes from the app.
1162 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1163
Mark Whitea15790a2023-08-22 21:28:11 +00001164 // If compiling headers then compile them and skip the rest
Liz Kammer60772632023-10-05 17:18:44 -04001165 if proptools.Bool(j.properties.Headers_only) {
Mark Whitea15790a2023-08-22 21:28:11 +00001166 if srcFiles.HasExt(".kt") {
1167 ctx.ModuleErrorf("Compiling headers_only with .kt not supported")
1168 }
1169 if ctx.Config().IsEnvFalse("TURBINE_ENABLED") || disableTurbine {
1170 ctx.ModuleErrorf("headers_only is enabled but Turbine is disabled.")
1171 }
1172
1173 _, j.headerJarFile =
1174 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName,
1175 extraCombinedJars)
1176 if ctx.Failed() {
1177 return
1178 }
1179
Colin Cross40213022023-12-13 15:19:49 -08001180 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Mark Whitea15790a2023-08-22 21:28:11 +00001181 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1182 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1183 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
1184 AidlIncludeDirs: j.exportAidlIncludeDirs,
1185 ExportedPlugins: j.exportedPluginJars,
1186 ExportedPluginClasses: j.exportedPluginClasses,
1187 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1188 })
1189
1190 j.outputFile = j.headerJarFile
1191 return
1192 }
1193
Jaewoong Jung26342642021-03-17 15:56:23 -07001194 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001195 // When using kotlin sources turbine is used to generate annotation processor sources,
1196 // including for annotation processors that generate API, so we can use turbine for
1197 // java sources too.
1198 disableTurbine = false
1199
Jaewoong Jung26342642021-03-17 15:56:23 -07001200 // user defined kotlin flags.
1201 kotlincFlags := j.properties.Kotlincflags
1202 CheckKotlincFlags(ctx, kotlincFlags)
1203
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001204 // Workaround for KT-46512
1205 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001206
1207 // If there are kotlin files, compile them first but pass all the kotlin and java files
1208 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1209 // won't emit any classes for them.
1210 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1211 if ctx.Device() {
1212 kotlincFlags = append(kotlincFlags, "-no-jdk")
1213 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001214
1215 for _, plugin := range deps.kotlinPlugins {
1216 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1217 }
1218 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1219
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 if len(kotlincFlags) > 0 {
1221 // optimization.
1222 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1223 flags.kotlincFlags += "$kotlincFlags"
1224 }
1225
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001226 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001227 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1228
1229 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1230 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1231
1232 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1233 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1234
Isaac Chioua23d9942022-04-06 06:14:38 +00001235 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001236 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001237 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1238 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001239 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001240 srcJars = append(srcJars, kaptSrcJar)
1241 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001242 // Disable annotation processing in javac, it's already been handled by kapt
1243 flags.processorPath = nil
1244 flags.processors = nil
1245 }
1246
1247 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001248 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001249 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001250 if ctx.Failed() {
1251 return
1252 }
1253
Isaac Chioua23d9942022-04-06 06:14:38 +00001254 // Make javac rule depend on the kotlinc rule
1255 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1256
Jaewoong Jung26342642021-03-17 15:56:23 -07001257 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001258 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1259
Jaewoong Jung26342642021-03-17 15:56:23 -07001260 // Jar kotlin classes into the final jar after javac
1261 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1262 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001263 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001264 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001265 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001266 } else {
1267 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001268 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001269 }
1270 }
1271
1272 jars := append(android.Paths(nil), kotlinJars...)
1273
Jaewoong Jung26342642021-03-17 15:56:23 -07001274 j.compiledSrcJars = srcJars
1275
1276 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001277 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001278 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001279 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1280 enableSharding = true
1281 // Formerly, there was a check here that prevented annotation processors
1282 // from being used when sharding was enabled, as some annotation processors
1283 // do not function correctly in sharded environments. It was removed to
1284 // allow for the use of annotation processors that do function correctly
1285 // with sharding enabled. See: b/77284273.
1286 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001287 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001288 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001289 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001290 if ctx.Failed() {
1291 return
1292 }
1293 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001294 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001295 hasErrorproneableFiles := false
1296 for _, ext := range j.sourceExtensions {
1297 if ext != ".proto" && ext != ".aidl" {
1298 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1299 // compile, and it's not useful to have warnings on these generated sources.
1300 hasErrorproneableFiles = true
1301 break
1302 }
1303 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001304 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001305 if Bool(j.properties.Errorprone.Enabled) {
1306 // If error-prone is enabled, enable errorprone flags on the regular
1307 // build.
1308 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001309 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001310 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1311 // a new jar file just for compiling with the errorprone compiler to.
1312 // This is because we don't want to cause the java files to get completely
1313 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1314 // We also don't want to run this if errorprone is enabled by default for
1315 // this module, or else we could have duplicated errorprone messages.
1316 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001317 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001318 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001319
Vadim Spivak3c496f02023-06-08 06:14:59 +00001320 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001321 "errorprone", "errorprone")
1322
Jaewoong Jung26342642021-03-17 15:56:23 -07001323 extraJarDeps = append(extraJarDeps, errorprone)
1324 }
1325
1326 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001327 if headerJarFileWithoutDepsOrJarjar != nil {
1328 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1329 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001330 shardSize := int(*(j.properties.Javac_shard_size))
1331 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001332 if len(uniqueJavaFiles) > 0 {
1333 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001334 for idx, shardSrc := range shardSrcs {
1335 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1336 nil, flags, extraJarDeps)
1337 jars = append(jars, classes)
1338 }
1339 }
Colin Crossa052ddb2023-09-25 21:46:58 -07001340 // Assume approximately 5 sources per srcjar.
1341 // For framework-minus-apex in AOSP at the time this was written, there are 266 srcjars, with a mean
1342 // 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 -07001343 if len(srcJars) > 0 {
Colin Crossa052ddb2023-09-25 21:46:58 -07001344 startIdx := len(shardSrcs)
1345 shardSrcJarsList := android.ShardPaths(srcJars, shardSize/5)
1346 for idx, shardSrcJars := range shardSrcJarsList {
1347 classes := j.compileJavaClasses(ctx, jarName, startIdx+idx,
1348 nil, shardSrcJars, flags, extraJarDeps)
1349 jars = append(jars, classes)
1350 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001351 }
1352 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001353 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001354 jars = append(jars, classes)
1355 }
1356 if ctx.Failed() {
1357 return
1358 }
1359 }
1360
1361 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1362
1363 var includeSrcJar android.WritablePath
1364 if Bool(j.properties.Include_srcs) {
1365 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1366 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1367 }
1368
1369 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1370 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1371 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1372 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1373
1374 var resArgs []string
1375 var resDeps android.Paths
1376
1377 resArgs = append(resArgs, dirArgs...)
1378 resDeps = append(resDeps, dirDeps...)
1379
1380 resArgs = append(resArgs, fileArgs...)
1381 resDeps = append(resDeps, fileDeps...)
1382
1383 resArgs = append(resArgs, extraArgs...)
1384 resDeps = append(resDeps, extraDeps...)
1385
1386 if len(resArgs) > 0 {
1387 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1388 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1389 j.resourceJar = resourceJar
1390 if ctx.Failed() {
1391 return
1392 }
1393 }
1394
1395 var resourceJars android.Paths
1396 if j.resourceJar != nil {
1397 resourceJars = append(resourceJars, j.resourceJar)
1398 }
1399 if Bool(j.properties.Include_srcs) {
1400 resourceJars = append(resourceJars, includeSrcJar)
1401 }
1402 resourceJars = append(resourceJars, deps.staticResourceJars...)
1403
1404 if len(resourceJars) > 1 {
1405 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1406 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1407 false, nil, nil)
1408 j.resourceJar = combinedJar
1409 } else if len(resourceJars) == 1 {
1410 j.resourceJar = resourceJars[0]
1411 }
1412
1413 if len(deps.staticJars) > 0 {
1414 jars = append(jars, deps.staticJars...)
1415 }
1416
1417 manifest := j.overrideManifest
1418 if !manifest.Valid() && j.properties.Manifest != nil {
1419 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1420 }
1421
1422 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1423 if len(services) > 0 {
1424 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1425 var zipargs []string
1426 for _, file := range services {
1427 serviceFile := file.String()
1428 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1429 }
1430 rule := zip
1431 args := map[string]string{
1432 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1433 }
1434 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1435 rule = zipRE
1436 args["implicits"] = strings.Join(services.Strings(), ",")
1437 }
1438 ctx.Build(pctx, android.BuildParams{
1439 Rule: rule,
1440 Output: servicesJar,
1441 Implicits: services,
1442 Args: args,
1443 })
1444 jars = append(jars, servicesJar)
1445 }
1446
Colin Cross4eae06d2023-06-20 22:40:02 -07001447 jars = append(android.CopyOf(extraCombinedJars), jars...)
1448
Jaewoong Jung26342642021-03-17 15:56:23 -07001449 // Combine the classes built from sources, any manifests, and any static libraries into
1450 // classes.jar. If there is only one input jar this step will be skipped.
1451 var outputFile android.OutputPath
1452
1453 if len(jars) == 1 && !manifest.Valid() {
1454 // Optimization: skip the combine step as there is nothing to do
1455 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1456 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1457 // any if len(jars) == 1.
1458
Jihoon Kang1147b312023-06-08 23:25:57 +00001459 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1460 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1461 // either with .from-source or .from-text suffix.
1462 // outputFile should be agnostic to the build configuration,
1463 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1464 // to the copy rules.
1465 stub, _ := moduleStubLinkType(ctx.ModuleName())
1466
Jaewoong Jung26342642021-03-17 15:56:23 -07001467 // Transform the single path to the jar into an OutputPath as that is required by the following
1468 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001469 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001470 // The path contains an embedded OutputPath so reuse that.
1471 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001472 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001473 // The path is an OutputPath so reuse it directly.
1474 outputFile = outputPath
1475 } else {
1476 // The file is not in the out directory so create an OutputPath into which it can be copied
1477 // and which the following code can use to refer to it.
1478 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1479 ctx.Build(pctx, android.BuildParams{
1480 Rule: android.Cp,
1481 Input: jars[0],
1482 Output: combinedJar,
1483 })
1484 outputFile = combinedJar.OutputPath
1485 }
1486 } else {
1487 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1488 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1489 false, nil, nil)
1490 outputFile = combinedJar.OutputPath
1491 }
1492
1493 // jarjar implementation jar if necessary
1494 if j.expandJarjarRules != nil {
1495 // Transform classes.jar into classes-jarjar.jar
1496 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1497 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1498 outputFile = jarjarFile
1499
1500 // jarjar resource jar if necessary
1501 if j.resourceJar != nil {
1502 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1503 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1504 j.resourceJar = resourceJarJarFile
1505 }
1506
1507 if ctx.Failed() {
1508 return
1509 }
1510 }
1511
1512 // Check package restrictions if necessary.
1513 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001514 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001515 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001516
1517 // Create a rule to copy the output jar to another path and add a validate dependency that
1518 // will check that the jar only contains the permitted packages. The new location will become
1519 // the output file of this module.
1520 inputFile := outputFile
1521 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1522 ctx.Build(pctx, android.BuildParams{
1523 Rule: android.Cp,
1524 Input: inputFile,
1525 Output: outputFile,
1526 // Make sure that any dependency on the output file will cause ninja to run the package check
1527 // rule.
1528 Validation: pkgckFile,
1529 })
1530
1531 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001532 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001533
1534 if ctx.Failed() {
1535 return
1536 }
1537 }
1538
1539 j.implementationJarFile = outputFile
1540 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001541 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1542 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1543 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1544 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1545 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1546 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1547 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001548 }
1549
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001550 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1551 specs := j.jacocoModuleToZipCommand(ctx)
1552 if ctx.Failed() {
1553 return
1554 }
1555
Jaewoong Jung26342642021-03-17 15:56:23 -07001556 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001557 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001558 }
1559
1560 // merge implementation jar with resources if necessary
1561 implementationAndResourcesJar := outputFile
1562 if j.resourceJar != nil {
1563 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1564 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1565 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1566 false, nil, nil)
1567 implementationAndResourcesJar = combinedJar
1568 }
1569
1570 j.implementationAndResourcesJar = implementationAndResourcesJar
1571
1572 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001573 compileDex := j.dexProperties.Compile_dex
Colin Crossff694a82023-12-13 15:54:49 -08001574 apexInfo, _ := android.ModuleProvider(ctx, android.ApexInfoProvider)
Jaewoong Jung26342642021-03-17 15:56:23 -07001575 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001576 if compileDex == nil {
1577 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001578 }
1579 if j.deviceProperties.Hostdex == nil {
1580 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1581 }
1582 }
1583
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001584 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001585 if j.hasCode(ctx) {
1586 if j.shouldInstrumentStatic(ctx) {
Colin Cross312634e2023-11-21 15:13:56 -08001587 j.dexer.extraProguardFlagsFiles = append(j.dexer.extraProguardFlagsFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001588 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1589 }
1590 // Dex compilation
1591 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001592 params := &compileDexParams{
1593 flags: flags,
1594 sdkVersion: j.SdkVersion(ctx),
1595 minSdkVersion: j.MinSdkVersion(ctx),
1596 classesJar: implementationAndResourcesJar,
1597 jarName: jarName,
1598 }
1599 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001600 if ctx.Failed() {
1601 return
1602 }
1603
Jaewoong Jung26342642021-03-17 15:56:23 -07001604 // merge dex jar with resources if necessary
1605 if j.resourceJar != nil {
1606 jars := android.Paths{dexOutputFile, j.resourceJar}
1607 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1608 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1609 false, nil, nil)
1610 if *j.dexProperties.Uncompress_dex {
1611 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
Cole Faust51d7bfd2023-09-07 05:31:32 +00001612 TransformZipAlign(ctx, combinedAlignedJar, combinedJar, nil)
Jaewoong Jung26342642021-03-17 15:56:23 -07001613 dexOutputFile = combinedAlignedJar
1614 } else {
1615 dexOutputFile = combinedJar
1616 }
1617 }
1618
Paul Duffin4de94502021-05-16 05:21:16 +01001619 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001620
1621 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001622
1623 // Encode hidden API flags in dex file, if needed.
1624 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1625
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001626 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001627
1628 // Dexpreopting
Spandan Dase21a8d42024-01-23 23:56:29 +00001629 j.dexpreopt(ctx, android.RemoveOptionalPrebuiltPrefix(ctx.ModuleName()), dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001630
1631 outputFile = dexOutputFile
1632 } else {
1633 // There is no code to compile into a dex jar, make sure the resources are propagated
1634 // to the APK if this is an app.
1635 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001636 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001637 }
1638
1639 if ctx.Failed() {
1640 return
1641 }
1642 } else {
1643 outputFile = implementationAndResourcesJar
1644 }
1645
1646 if ctx.Device() {
Zi Wange1166f02023-11-06 11:43:17 -08001647 lintSDKVersion := func(apiLevel android.ApiLevel) android.ApiLevel {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001648 if !apiLevel.IsPreview() {
Zi Wange1166f02023-11-06 11:43:17 -08001649 return apiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -07001650 } else {
Zi Wange1166f02023-11-06 11:43:17 -08001651 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 }
1653 }
1654
1655 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001656 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1657 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001658 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1659 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001660 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001661 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001662 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001663 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001664 j.linter.javaLanguageLevel = flags.javaVersion.String()
1665 j.linter.kotlinLanguageLevel = "1.3"
Cole Faust2b64af82023-12-13 18:22:18 -08001666 j.linter.compile_data = android.PathsForModuleSrc(ctx, j.properties.Compile_data)
Jaewoong Jung26342642021-03-17 15:56:23 -07001667 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1668 j.linter.buildModuleReportZip = true
1669 }
1670 j.linter.lint(ctx)
1671 }
1672
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001673 j.collectTransitiveSrcFiles(ctx, srcFiles)
1674
Jaewoong Jung26342642021-03-17 15:56:23 -07001675 ctx.CheckbuildFile(outputFile)
1676
LaMont Jonesaa005ae2023-12-19 19:01:57 +00001677 android.CollectDependencyAconfigFiles(ctx, &j.mergedAconfigFiles)
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001678
Colin Cross40213022023-12-13 15:19:49 -08001679 android.SetProvider(ctx, JavaInfoProvider, JavaInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07001680 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001681 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1682 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001683 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1684 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1685 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1686 AidlIncludeDirs: j.exportAidlIncludeDirs,
1687 SrcJarArgs: j.srcJarArgs,
1688 SrcJarDeps: j.srcJarDeps,
Anton Hansson0e73f9e2023-09-20 13:39:57 +00001689 TransitiveSrcFiles: j.transitiveSrcFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001690 ExportedPlugins: j.exportedPluginJars,
1691 ExportedPluginClasses: j.exportedPluginClasses,
1692 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1693 JacocoReportClassesFile: j.jacocoReportClassesFile,
1694 })
1695
1696 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1697 j.outputFile = outputFile.WithoutRel()
1698}
1699
Colin Crossa1ff7c62021-09-17 14:11:52 -07001700func (j *Module) useCompose() bool {
1701 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1702}
1703
Sam Delmerico95d70942023-08-02 18:00:35 -04001704func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1705 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1706 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1707
1708 ctx.VisitDirectDeps(func(m android.Module) {
Colin Cross313aa542023-12-13 13:47:44 -08001709 depProguardInfo, _ := android.OtherModuleProvider(ctx, m, ProguardSpecInfoProvider)
Sam Delmerico95d70942023-08-02 18:00:35 -04001710 depTag := ctx.OtherModuleDependencyTag(m)
1711
1712 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1713 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1714 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1715 }
1716
1717 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1718 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1719 }
1720 })
1721
1722 directUnconditionalExportedFlags := android.Paths{}
1723 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1724 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1725 if exportUnconditionally {
1726 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1727 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1728 directUnconditionalExportedFlags = proguardFlagsForThisModule
1729 }
1730
1731 return ProguardSpecInfo{
1732 Export_proguard_flags_files: exportUnconditionally,
1733 ProguardFlagsFiles: android.NewDepSet[android.Path](
1734 android.POSTORDER,
1735 proguardFlagsForThisModule,
1736 transitiveProguardFlags,
1737 ),
1738 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1739 android.POSTORDER,
1740 directUnconditionalExportedFlags,
1741 transitiveUnconditionalExportedFlags,
1742 ),
1743 }
1744
1745}
1746
Cole Faust75fffb12021-06-13 15:23:16 -07001747// Returns a copy of the supplied flags, but with all the errorprone-related
1748// fields copied to the regular build's fields.
1749func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1750 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1751
1752 if len(flags.errorProneExtraJavacFlags) > 0 {
1753 if len(flags.javacFlags) > 0 {
1754 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1755 } else {
1756 flags.javacFlags = flags.errorProneExtraJavacFlags
1757 }
1758 }
1759 return flags
1760}
1761
Jaewoong Jung26342642021-03-17 15:56:23 -07001762func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1763 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1764
1765 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001766 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001767 if idx >= 0 {
1768 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001769 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001770 jarName += strconv.Itoa(idx)
1771 }
1772
1773 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001774 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001775
1776 if ctx.Config().EmitXrefRules() {
1777 extractionFile := android.PathForModuleOut(ctx, kzipName)
1778 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1779 j.kytheFiles = append(j.kytheFiles, extractionFile)
1780 }
1781
Vadim Spivak3c496f02023-06-08 06:14:59 +00001782 if len(flags.processorPath) > 0 {
1783 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1784 }
1785
Jaewoong Jung26342642021-03-17 15:56:23 -07001786 return classes
1787}
1788
1789// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1790// since some of these flags may be used internally.
1791func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1792 for _, flag := range flags {
1793 flag = strings.TrimSpace(flag)
1794
1795 if !strings.HasPrefix(flag, "-") {
1796 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1797 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1798 ctx.PropertyErrorf("kotlincflags",
1799 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1800 } else if inList(flag, config.KotlincIllegalFlags) {
1801 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1802 } else if flag == "-include-runtime" {
1803 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1804 } else {
1805 args := strings.Split(flag, " ")
1806 if args[0] == "-kotlin-home" {
1807 ctx.PropertyErrorf("kotlincflags",
1808 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1809 }
1810 }
1811 }
1812}
1813
1814func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1815 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001816 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001817
1818 var jars android.Paths
1819 if len(srcFiles) > 0 || len(srcJars) > 0 {
1820 // Compile java sources into turbine.jar.
1821 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1822 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1823 if ctx.Failed() {
1824 return nil, nil
1825 }
1826 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001827 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001828 }
1829
1830 jars = append(jars, extraJars...)
1831
1832 // Combine any static header libraries into classes-header.jar. If there is only
1833 // one input jar this step will be skipped.
1834 jars = append(jars, deps.staticHeaderJars...)
1835
1836 // we cannot skip the combine step for now if there is only one jar
1837 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1838 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1839 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1840 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001841 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001842
1843 if j.expandJarjarRules != nil {
1844 // Transform classes.jar into classes-jarjar.jar
1845 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001846 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1847 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001848 if ctx.Failed() {
1849 return nil, nil
1850 }
1851 }
1852
Colin Cross3d56ed52021-11-18 22:23:12 -08001853 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001854}
1855
1856func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001857 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001858
1859 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1860 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1861
1862 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1863
1864 j.jacocoReportClassesFile = jacocoReportClassesFile
1865
1866 return instrumentedJar
1867}
1868
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001869type providesTransitiveHeaderJars struct {
1870 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001871 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001872 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001873 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001874}
1875
Colin Crossc85750b2022-04-21 12:50:51 -07001876func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001877 return j.transitiveLibsHeaderJars
1878}
1879
Colin Crossc85750b2022-04-21 12:50:51 -07001880func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001881 return j.transitiveStaticLibsHeaderJars
1882}
1883
1884func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1885 directLibs := android.Paths{}
1886 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001887 transitiveLibs := []*android.DepSet[android.Path]{}
1888 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001889 ctx.VisitDirectDeps(func(module android.Module) {
1890 // don't add deps of the prebuilt version of the same library
1891 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1892 return
1893 }
1894
Colin Cross313aa542023-12-13 13:47:44 -08001895 dep, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001896 tag := ctx.OtherModuleDependencyTag(module)
1897 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1898 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1899 directLibs = append(directLibs, dep.HeaderJars...)
1900 } else if tag == staticLibTag {
1901 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
Jared Dukeefb6d602023-10-27 18:47:10 +00001902 } else {
1903 // Don't propagate transitive libs for other kinds of dependencies.
1904 return
1905 }
1906
1907 if dep.TransitiveLibsHeaderJars != nil {
1908 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1909 }
1910 if dep.TransitiveStaticLibsHeaderJars != nil {
1911 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001912 }
1913 })
1914 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1915 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1916}
1917
Jaewoong Jung26342642021-03-17 15:56:23 -07001918func (j *Module) HeaderJars() android.Paths {
1919 if j.headerJarFile == nil {
1920 return nil
1921 }
1922 return android.Paths{j.headerJarFile}
1923}
1924
1925func (j *Module) ImplementationJars() android.Paths {
1926 if j.implementationJarFile == nil {
1927 return nil
1928 }
1929 return android.Paths{j.implementationJarFile}
1930}
1931
Spandan Das59a4a2b2024-01-09 21:35:56 +00001932func (j *Module) DexJarBuildPath(ctx android.ModuleErrorfContext) OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001933 return j.dexJarFile
1934}
1935
1936func (j *Module) DexJarInstallPath() android.Path {
1937 return j.installFile
1938}
1939
1940func (j *Module) ImplementationAndResourcesJars() android.Paths {
1941 if j.implementationAndResourcesJar == nil {
1942 return nil
1943 }
1944 return android.Paths{j.implementationAndResourcesJar}
1945}
1946
1947func (j *Module) AidlIncludeDirs() android.Paths {
1948 // exportAidlIncludeDirs is type android.Paths already
1949 return j.exportAidlIncludeDirs
1950}
1951
1952func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1953 return j.classLoaderContexts
1954}
1955
1956// Collect information for opening IDE project files in java/jdeps.go.
1957func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1958 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1959 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1960 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1961 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1962 if j.expandJarjarRules != nil {
1963 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1964 }
Yikef6282022022-04-13 20:41:01 +08001965 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1966 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001967 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001968}
1969
1970func (j *Module) CompilerDeps() []string {
1971 jdeps := []string{}
1972 jdeps = append(jdeps, j.properties.Libs...)
1973 jdeps = append(jdeps, j.properties.Static_libs...)
1974 return jdeps
1975}
1976
1977func (j *Module) hasCode(ctx android.ModuleContext) bool {
1978 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1979 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1980}
1981
1982// Implements android.ApexModule
1983func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1984 return j.depIsInSameApex(ctx, dep)
1985}
1986
1987// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001988func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001989 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001990 minSdkVersion := j.MinSdkVersion(ctx)
1991 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001992 return fmt.Errorf("min_sdk_version is not specified")
1993 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001994 // If the module is compiling against core (via sdk_version), skip comparison check.
1995 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001996 return nil
1997 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001998 if minSdkVersion.GreaterThan(sdkVersion) {
1999 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07002000 }
2001 return nil
2002}
2003
2004func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00002005 if j.stem == "" {
2006 panic("Stem() called before stem property was set")
2007 }
2008 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07002009}
2010
Jaewoong Jung26342642021-03-17 15:56:23 -07002011func (j *Module) JacocoReportClassesFile() android.Path {
2012 return j.jacocoReportClassesFile
2013}
2014
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002015func (j *Module) collectTransitiveSrcFiles(ctx android.ModuleContext, mine android.Paths) {
2016 var fromDeps []*android.DepSet[android.Path]
2017 ctx.VisitDirectDeps(func(module android.Module) {
2018 tag := ctx.OtherModuleDependencyTag(module)
2019 if tag == staticLibTag {
Colin Cross313aa542023-12-13 13:47:44 -08002020 depInfo, _ := android.OtherModuleProvider(ctx, module, JavaInfoProvider)
Anton Hansson0e73f9e2023-09-20 13:39:57 +00002021 if depInfo.TransitiveSrcFiles != nil {
2022 fromDeps = append(fromDeps, depInfo.TransitiveSrcFiles)
2023 }
2024 }
2025 })
2026
2027 j.transitiveSrcFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2028}
2029
Jaewoong Jung26342642021-03-17 15:56:23 -07002030func (j *Module) IsInstallable() bool {
2031 return Bool(j.properties.Installable)
2032}
2033
2034type sdkLinkType int
2035
2036const (
2037 // TODO(jiyong) rename these for better readability. Make the allowed
2038 // and disallowed link types explicit
2039 // order is important here. See rank()
2040 javaCore sdkLinkType = iota
2041 javaSdk
2042 javaSystem
2043 javaModule
2044 javaSystemServer
2045 javaPlatform
2046)
2047
2048func (lt sdkLinkType) String() string {
2049 switch lt {
2050 case javaCore:
2051 return "core Java API"
2052 case javaSdk:
2053 return "Android API"
2054 case javaSystem:
2055 return "system API"
2056 case javaModule:
2057 return "module API"
2058 case javaSystemServer:
2059 return "system server API"
2060 case javaPlatform:
2061 return "private API"
2062 default:
2063 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2064 }
2065}
2066
2067// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2068// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2069// can't statically depend on modules that use Platform API.
2070func (lt sdkLinkType) rank() int {
2071 return int(lt)
2072}
2073
2074type moduleWithSdkDep interface {
2075 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002076 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002077}
2078
Jiyong Park92315372021-04-02 08:45:46 +09002079func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002080 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002081 case android.SdkCore.DefaultJavaLibraryName(),
2082 "legacy.core.platform.api.stubs",
2083 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002084 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002085 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002086 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002087 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002088 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002089 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002090 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002091 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002092 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002093 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002094 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002095 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002096 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002097 return javaSystem, true
2098 }
2099
2100 if stub, linkType := moduleStubLinkType(name); stub {
2101 return linkType, true
2102 }
2103
Jiyong Park92315372021-04-02 08:45:46 +09002104 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002105 switch ver.Kind {
2106 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002107 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002108 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002109 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002110 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002111 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002112 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002113 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002114 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002115 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002116 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002117 return javaPlatform, false
2118 }
2119
Jiyong Parkf1691d22021-03-29 20:11:58 +09002120 if !ver.Valid() {
2121 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002122 }
2123 return javaSdk, false
2124}
2125
2126// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2127// this module's. See the comment on rank() for details and an example.
2128func (j *Module) checkSdkLinkType(
2129 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2130 if ctx.Host() {
2131 return
2132 }
2133
Jiyong Park92315372021-04-02 08:45:46 +09002134 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002135 if stubs {
2136 return
2137 }
Jiyong Park92315372021-04-02 08:45:46 +09002138 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002139
2140 if myLinkType.rank() < depLinkType.rank() {
2141 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2142 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2143 "property of the source or target module so that target module is built "+
2144 "with the same or smaller API set when compared to the source.",
2145 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2146 }
2147}
2148
2149func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2150 var deps deps
2151
2152 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002153 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002154 if sdkDep.invalidVersion {
2155 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2156 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2157 } else if sdkDep.useFiles {
2158 // sdkDep.jar is actually equivalent to turbine header.jar.
2159 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002160 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002161 deps.aidlPreprocess = sdkDep.aidl
2162 } else {
2163 deps.aidlPreprocess = sdkDep.aidl
2164 }
2165 }
2166
Jiyong Park92315372021-04-02 08:45:46 +09002167 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002168
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002169 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002170 ctx.VisitDirectDeps(func(module android.Module) {
2171 otherName := ctx.OtherModuleName(module)
2172 tag := ctx.OtherModuleDependencyTag(module)
2173
2174 if IsJniDepTag(tag) {
2175 // Handled by AndroidApp.collectAppDeps
2176 return
2177 }
2178 if tag == certificateTag {
2179 // Handled by AndroidApp.collectAppDeps
2180 return
2181 }
2182
2183 if dep, ok := module.(SdkLibraryDependency); ok {
2184 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002185 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002186 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2187 deps.classpath = append(deps.classpath, depHeaderJars...)
2188 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002189 case staticLibTag:
2190 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2191 }
Colin Cross313aa542023-12-13 13:47:44 -08002192 } else if dep, ok := android.OtherModuleProvider(ctx, module, JavaInfoProvider); ok {
2193 if sdkLinkType != javaPlatform {
2194 if syspropDep, ok := android.OtherModuleProvider(ctx, module, SyspropPublicStubInfoProvider); ok {
2195 // dep is a sysprop implementation library, but this module is not linking against
2196 // the platform, so it gets the sysprop public stubs library instead. Replace
2197 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2198 dep = syspropDep.JavaInfo
2199 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002200 }
2201 switch tag {
2202 case bootClasspathTag:
2203 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002204 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002205 if _, ok := module.(*Plugin); ok {
2206 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2207 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002208 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002209 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002210 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2211 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2212 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2213 case java9LibTag:
2214 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2215 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002216 if _, ok := module.(*Plugin); ok {
2217 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2218 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002219 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2220 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2221 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2222 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2223 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2224 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2225 // Turbine doesn't run annotation processors, so any module that uses an
2226 // annotation processor that generates API is incompatible with the turbine
2227 // optimization.
2228 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2229 case pluginTag:
2230 if plugin, ok := module.(*Plugin); ok {
2231 if plugin.pluginProperties.Processor_class != nil {
2232 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2233 } else {
2234 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2235 }
2236 // Turbine doesn't run annotation processors, so any module that uses an
2237 // annotation processor that generates API is incompatible with the turbine
2238 // optimization.
2239 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2240 } else {
2241 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2242 }
2243 case errorpronePluginTag:
2244 if _, ok := module.(*Plugin); ok {
2245 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2246 } else {
2247 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2248 }
2249 case exportedPluginTag:
2250 if plugin, ok := module.(*Plugin); ok {
2251 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2252 if plugin.pluginProperties.Processor_class != nil {
2253 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2254 }
2255 // Turbine doesn't run annotation processors, so any module that uses an
2256 // annotation processor that generates API is incompatible with the turbine
2257 // optimization.
2258 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2259 } else {
2260 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2261 }
2262 case kotlinStdlibTag:
2263 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2264 case kotlinAnnotationsTag:
2265 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002266 case kotlinPluginTag:
2267 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002268 case syspropPublicStubDepTag:
2269 // This is a sysprop implementation library, forward the JavaInfoProvider from
2270 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
Colin Cross40213022023-12-13 15:19:49 -08002271 android.SetProvider(ctx, SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
Jaewoong Jung26342642021-03-17 15:56:23 -07002272 JavaInfo: dep,
2273 })
2274 }
2275 } else if dep, ok := module.(android.SourceFileProducer); ok {
2276 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002277 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002278 checkProducesJars(ctx, dep)
2279 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002280 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002281 case staticLibTag:
2282 checkProducesJars(ctx, dep)
2283 deps.classpath = append(deps.classpath, dep.Srcs()...)
2284 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2285 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2286 }
2287 } else {
2288 switch tag {
2289 case bootClasspathTag:
2290 // If a system modules dependency has been added to the bootclasspath
2291 // then add its libs to the bootclasspath.
2292 sm := module.(SystemModulesProvider)
2293 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2294
2295 case systemModulesTag:
2296 if deps.systemModules != nil {
2297 panic("Found two system module dependencies")
2298 }
2299 sm := module.(SystemModulesProvider)
2300 outputDir, outputDeps := sm.OutputDirAndDeps()
2301 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002302
2303 case instrumentationForTag:
2304 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 -07002305 }
2306 }
2307
2308 addCLCFromDep(ctx, module, j.classLoaderContexts)
2309 })
2310
2311 return deps
2312}
2313
2314func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2315 deps.processorPath = append(deps.processorPath, pluginJars...)
2316 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2317}
2318
2319// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2320// this interface.
2321type ProvidesUsesLib interface {
2322 ProvidesUsesLib() *string
2323}
2324
2325func (j *Module) ProvidesUsesLib() *string {
2326 return j.usesLibraryProperties.Provides_uses_lib
2327}
satayev1c564cc2021-05-25 19:50:30 +01002328
2329type ModuleWithStem interface {
2330 Stem() string
2331}
2332
2333var _ ModuleWithStem = (*Module)(nil)