blob: a9b986b56488a4630f96f846ba04f7c46e1de32f [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
Chris Parsons39a16972023-06-08 14:28:51 +000023 "android/soong/ui/metrics/bp2build_metrics_proto"
Jihoon Kang1bfb6f22023-07-01 00:13:47 +000024
Jaewoong Jung26342642021-03-17 15:56:23 -070025 "github.com/google/blueprint/pathtools"
26 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
29 "android/soong/dexpreopt"
30 "android/soong/java/config"
31)
32
33// This file contains the definition and the implementation of the base module that most
34// source-based Java module structs embed.
35
36// TODO:
37// Autogenerated files:
38// Renderscript
39// Post-jar passes:
40// Proguard
41// Rmtypedefs
42// DroidDoc
43// Findbugs
44
45// Properties that are common to most Java modules, i.e. whether it's a host or device module.
46type CommonProperties struct {
47 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
48 // or .aidl files.
49 Srcs []string `android:"path,arch_variant"`
50
51 // list Kotlin of source files containing Kotlin code that should be treated as common code in
52 // a codebase that supports Kotlin multiplatform. See
53 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
54 Common_srcs []string `android:"path,arch_variant"`
55
56 // list of source files that should not be used to build the Java module.
57 // This is most useful in the arch/multilib variants to remove non-common files
58 Exclude_srcs []string `android:"path,arch_variant"`
59
60 // list of directories containing Java resources
61 Java_resource_dirs []string `android:"arch_variant"`
62
63 // list of directories that should be excluded from java_resource_dirs
64 Exclude_java_resource_dirs []string `android:"arch_variant"`
65
66 // list of files to use as Java resources
67 Java_resources []string `android:"path,arch_variant"`
68
69 // list of files that should be excluded from java_resources and java_resource_dirs
70 Exclude_java_resources []string `android:"path,arch_variant"`
71
72 // list of module-specific flags that will be used for javac compiles
73 Javacflags []string `android:"arch_variant"`
74
75 // list of module-specific flags that will be used for kotlinc compiles
76 Kotlincflags []string `android:"arch_variant"`
77
78 // list of java libraries that will be in the classpath
79 Libs []string `android:"arch_variant"`
80
81 // list of java libraries that will be compiled into the resulting jar
82 Static_libs []string `android:"arch_variant"`
83
Jihoon Kang381c2fa2023-06-01 22:17:32 +000084 // list of java libraries that should not be used to build this module
85 Exclude_static_libs []string `android:"arch_variant"`
86
Jaewoong Jung26342642021-03-17 15:56:23 -070087 // manifest file to be included in resulting jar
88 Manifest *string `android:"path"`
89
90 // if not blank, run jarjar using the specified rules file
91 Jarjar_rules *string `android:"path,arch_variant"`
92
93 // If not blank, set the java version passed to javac as -source and -target
94 Java_version *string
95
96 // If set to true, allow this module to be dexed and installed on devices. Has no
97 // effect on host modules, which are always considered installable.
98 Installable *bool
99
100 // If set to true, include sources used to compile the module in to the final jar
101 Include_srcs *bool
102
103 // If not empty, classes are restricted to the specified packages and their sub-packages.
104 // This restriction is checked after applying jarjar rules and including static libs.
105 Permitted_packages []string
106
107 // List of modules to use as annotation processors
108 Plugins []string
109
110 // List of modules to export to libraries that directly depend on this library as annotation
111 // processors. Note that if the plugins set generates_api: true this will disable the turbine
112 // optimization on modules that depend on this module, which will reduce parallelism and cause
113 // more recompilation.
114 Exported_plugins []string
115
116 // The number of Java source entries each Javac instance can process
117 Javac_shard_size *int64
118
119 // Add host jdk tools.jar to bootclasspath
120 Use_tools_jar *bool
121
122 Openjdk9 struct {
123 // List of source files that should only be used when passing -source 1.9 or higher
124 Srcs []string `android:"path"`
125
126 // List of javac flags that should only be used when passing -source 1.9 or higher
127 Javacflags []string
128 }
129
130 // When compiling language level 9+ .java code in packages that are part of
131 // a system module, patch_module names the module that your sources and
132 // dependencies should be patched into. The Android runtime currently
133 // doesn't implement the JEP 261 module system so this option is only
134 // supported at compile time. It should only be needed to compile tests in
135 // packages that exist in libcore and which are inconvenient to move
136 // elsewhere.
137 Patch_module *string `android:"arch_variant"`
138
139 Jacoco struct {
140 // List of classes to include for instrumentation with jacoco to collect coverage
141 // information at runtime when building with coverage enabled. If unset defaults to all
142 // classes.
143 // Supports '*' as the last character of an entry in the list as a wildcard match.
144 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
145 // it matches classes in the package that have the class name as a prefix.
146 Include_filter []string
147
148 // List of classes to exclude from instrumentation with jacoco to collect coverage
149 // information at runtime when building with coverage enabled. Overrides classes selected
150 // by the include_filter property.
151 // Supports '*' as the last character of an entry in the list as a wildcard match.
152 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
153 // it matches classes in the package that have the class name as a prefix.
154 Exclude_filter []string
155 }
156
157 Errorprone struct {
158 // List of javac flags that should only be used when running errorprone.
159 Javacflags []string
160
161 // List of java_plugin modules that provide extra errorprone checks.
162 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700163
Cole Faust2b1536e2021-06-18 12:25:54 -0700164 // This property can be in 3 states. When set to true, errorprone will
165 // be run during the regular build. When set to false, errorprone will
166 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
167 // environment variable is true. Setting this to false will improve build
168 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700169 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700170 }
171
172 Proto struct {
173 // List of extra options that will be passed to the proto generator.
174 Output_params []string
175 }
176
Sam Delmericoc7593722022-08-31 15:57:52 -0400177 // If true, then jacocoagent is automatically added as a libs dependency so that
178 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700179 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000180 // If true, then the module supports statically including the jacocoagent
181 // into the library.
182 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700183
184 // List of files to include in the META-INF/services folder of the resulting jar.
185 Services []string `android:"path,arch_variant"`
186
187 // If true, package the kotlin stdlib into the jar. Defaults to true.
188 Static_kotlin_stdlib *bool `android:"arch_variant"`
189
190 // A list of java_library instances that provide additional hiddenapi annotations for the library.
191 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700192
193 // Additional srcJars tacked in by GeneratedJavaLibraryModule
194 Generated_srcjars []android.Path `android:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700195}
196
197// Properties that are specific to device modules. Host module factories should not add these when
198// constructing a new module.
199type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000200 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000201 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000202 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000203 // 1) numerical API level, "current", "none", or "core_platform"
204 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
205 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
206 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700207 Sdk_version *string
208
209 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000210 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 Min_sdk_version *string
212
satayev0a420e72021-11-29 17:25:52 +0000213 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
214 // Defaults to empty string "". See sdk_version for possible values.
215 Max_sdk_version *string
216
William Loh5a082f92022-05-17 20:21:50 +0000217 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
218 // Defaults to empty string "". See sdk_version for possible values.
219 Replace_max_sdk_version_placeholder *string
220
Jaewoong Jung26342642021-03-17 15:56:23 -0700221 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000222 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700223 Target_sdk_version *string
224
225 // Whether to compile against the platform APIs instead of an SDK.
226 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000227 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700228 Platform_apis *bool
229
230 Aidl struct {
231 // Top level directories to pass to aidl tool
232 Include_dirs []string
233
234 // Directories rooted at the Android.bp file to pass to aidl tool
235 Local_include_dirs []string
236
237 // directories that should be added as include directories for any aidl sources of modules
238 // that depend on this module, as well as to aidl for this module.
239 Export_include_dirs []string
240
241 // whether to generate traces (for systrace) for this interface
242 Generate_traces *bool
243
244 // whether to generate Binder#GetTransaction name method.
245 Generate_get_transaction_name *bool
246
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100247 // whether all interfaces should be annotated with required permissions.
248 Enforce_permissions *bool
249
250 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
251 Enforce_permissions_exceptions []string `android:"path"`
252
Jaewoong Jung26342642021-03-17 15:56:23 -0700253 // list of flags that will be passed to the AIDL compiler
254 Flags []string
255 }
256
257 // If true, export a copy of the module as a -hostdex module for host testing.
258 Hostdex *bool
259
260 Target struct {
261 Hostdex struct {
262 // Additional required dependencies to add to -hostdex modules.
263 Required []string
264 }
265 }
266
267 // When targeting 1.9 and above, override the modules to use with --system,
268 // otherwise provides defaults libraries to add to the bootclasspath.
269 System_modules *string
270
Jaewoong Jung26342642021-03-17 15:56:23 -0700271 IsSDKLibrary bool `blueprint:"mutated"`
272
273 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
274 // Defaults to false.
275 V4_signature *bool
276
277 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
278 // public stubs library.
279 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000280
281 HiddenAPIPackageProperties
282 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700283}
284
Jooyung Han01d80d82022-01-08 12:16:32 +0900285// Device properties that can be overridden by overriding module (e.g. override_android_app)
286type OverridableDeviceProperties struct {
287 // set the name of the output. If not set, `name` is used.
288 // To override a module with this property set, overriding module might need to set this as well.
289 // Otherwise, both the overridden and the overriding modules will have the same output name, which
290 // can cause the duplicate output error.
291 Stem *string
292}
293
Jaewoong Jung26342642021-03-17 15:56:23 -0700294// Functionality common to Module and Import
295//
296// It is embedded in Module so its functionality can be used by methods in Module
297// but it is currently only initialized by Import and Library.
298type embeddableInModuleAndImport struct {
299
300 // Functionality related to this being used as a component of a java_sdk_library.
301 EmbeddableSdkLibraryComponent
302}
303
Paul Duffin71b33cc2021-06-23 11:39:47 +0100304func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
305 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700306}
307
308// Module/Import's DepIsInSameApex(...) delegates to this method.
309//
310// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
311// the one provided by ApexModuleBase.
312func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
313 // dependencies other than the static linkage are all considered crossing APEX boundary
314 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
315 return true
316 }
317 return false
318}
319
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100320// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
321// or an invalid path describing the reason it is invalid.
322//
323// It is unset if a dex jar isn't applicable, i.e. no build rule has been
324// requested to create one.
325//
326// If a dex jar has been requested to be built then it is set, and it may be
327// either a valid android.Path, or invalid with a reason message. The latter
328// happens if the source that should produce the dex file isn't able to.
329//
330// E.g. it is invalid with a reason message if there is a prebuilt APEX that
331// could produce the dex jar through a deapexer module, but the APEX isn't
332// installable so doing so wouldn't be safe.
333type OptionalDexJarPath struct {
334 isSet bool
335 path android.OptionalPath
336}
337
338// IsSet returns true if a path has been set, either invalid or valid.
339func (o OptionalDexJarPath) IsSet() bool {
340 return o.isSet
341}
342
343// Valid returns true if there is a path that is valid.
344func (o OptionalDexJarPath) Valid() bool {
345 return o.isSet && o.path.Valid()
346}
347
348// Path returns the valid path, or panics if it's either not set or is invalid.
349func (o OptionalDexJarPath) Path() android.Path {
350 if !o.isSet {
351 panic("path isn't set")
352 }
353 return o.path.Path()
354}
355
356// PathOrNil returns the path if it's set and valid, or else nil.
357func (o OptionalDexJarPath) PathOrNil() android.Path {
358 if o.Valid() {
359 return o.Path()
360 }
361 return nil
362}
363
364// InvalidReason returns the reason for an invalid path, which is never "". It
365// returns "" for an unset or valid path.
366func (o OptionalDexJarPath) InvalidReason() string {
367 if !o.isSet {
368 return ""
369 }
370 return o.path.InvalidReason()
371}
372
373func (o OptionalDexJarPath) String() string {
374 if !o.isSet {
375 return "<unset>"
376 }
377 return o.path.String()
378}
379
380// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
381func makeUnsetDexJarPath() OptionalDexJarPath {
382 return OptionalDexJarPath{isSet: false}
383}
384
385// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
386// the given OptionalPath, which may be valid or invalid.
387func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
388 return OptionalDexJarPath{isSet: true, path: path}
389}
390
391// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
392// valid given path. It returns an unset OptionalDexJarPath if the given path is
393// nil.
394func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
395 if path == nil {
396 return makeUnsetDexJarPath()
397 }
398 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
399}
400
Jaewoong Jung26342642021-03-17 15:56:23 -0700401// Module contains the properties and members used by all java module types
402type Module struct {
403 android.ModuleBase
404 android.DefaultableModuleBase
405 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800406 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700407
408 // Functionality common to Module and Import.
409 embeddableInModuleAndImport
410
411 properties CommonProperties
412 protoProperties android.ProtoProperties
413 deviceProperties DeviceProperties
414
Jooyung Han01d80d82022-01-08 12:16:32 +0900415 overridableDeviceProperties OverridableDeviceProperties
416
Jaewoong Jung26342642021-03-17 15:56:23 -0700417 // jar file containing header classes including static library dependencies, suitable for
418 // inserting into the bootclasspath/classpath of another compile
419 headerJarFile android.Path
420
421 // jar file containing implementation classes including static library dependencies but no
422 // resources
423 implementationJarFile android.Path
424
425 // jar file containing only resources including from static library dependencies
426 resourceJar android.Path
427
428 // args and dependencies to package source files into a srcjar
429 srcJarArgs []string
430 srcJarDeps android.Paths
431
432 // jar file containing implementation classes and resources including static library
433 // dependencies
434 implementationAndResourcesJar android.Path
435
436 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100437 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700438
439 // output file containing uninstrumented classes that will be instrumented by jacoco
440 jacocoReportClassesFile android.Path
441
442 // output file of the module, which may be a classes jar or a dex jar
443 outputFile android.Path
444 extraOutputFiles android.Paths
445
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100446 exportAidlIncludeDirs android.Paths
447 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700448
449 logtagsSrcs android.Paths
450
451 // installed file for binary dependency
452 installFile android.Path
453
Colin Cross3108ce12021-11-10 14:38:50 -0800454 // installed file for hostdex copy
455 hostdexInstallFile android.InstallPath
456
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800457 // list of unique .java and .kt source files
458 uniqueSrcFiles android.Paths
459
460 // list of srcjars that was passed to javac
461 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700462
463 // manifest file to use instead of properties.Manifest
464 overrideManifest android.OptionalPath
465
Jaewoong Jung26342642021-03-17 15:56:23 -0700466 // list of plugins that this java module is exporting
467 exportedPluginJars android.Paths
468
469 // list of plugins that this java module is exporting
470 exportedPluginClasses []string
471
472 // if true, the exported plugins generate API and require disabling turbine.
473 exportedDisableTurbine bool
474
475 // list of source files, collected from srcFiles with unique java and all kt files,
476 // will be used by android.IDEInfo struct
477 expandIDEInfoCompiledSrcs []string
478
479 // expanded Jarjar_rules
480 expandJarjarRules android.Path
481
Jaewoong Jung26342642021-03-17 15:56:23 -0700482 // Extra files generated by the module type to be added as java resources.
483 extraResources android.Paths
484
485 hiddenAPI
486 dexer
487 dexpreopter
488 usesLibrary
489 linter
490
491 // list of the xref extraction files
492 kytheFiles android.Paths
493
494 // Collect the module directory for IDE info in java/jdeps.go.
495 modulePaths []string
496
497 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900498
499 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000500 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000501 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400502
503 sourceExtensions []string
Vadim Spivak3c496f02023-06-08 06:14:59 +0000504
505 annoSrcJars android.Paths
Jihoon Kang1bfb6f22023-07-01 00:13:47 +0000506
507 // output file name based on Stem property.
508 // This should be set in every ModuleWithStem's GenerateAndroidBuildActions
509 // or the module should override Stem().
510 stem string
Joe Onorato6fe59eb2023-07-16 13:20:33 -0700511
512 // Aconfig "cache files" that went directly into this module. Transitive ones are
513 // tracked via JavaInfo.TransitiveAconfigFiles
514 // TODO: Extract to something standalone to propagate tags via GeneratedJavaLibraryModule
515 aconfigIntermediates android.Paths
516
517 // Aconfig files for all transitive deps. Also exposed via JavaInfo
518 transitiveAconfigFiles *android.DepSet[android.Path]
Jaewoong Jung26342642021-03-17 15:56:23 -0700519}
520
Jiyong Park92315372021-04-02 08:45:46 +0900521func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
522 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900523 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700524 return nil
525 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900526 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000527 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700528 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
529 } else {
530 // Treat stable core platform as stable.
531 return nil
532 }
533 } else {
534 return fmt.Errorf("non stable SDK %v", sdkVersion)
535 }
536}
537
538// checkSdkVersions enforces restrictions around SDK dependencies.
539func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
540 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900541 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900542 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700543 ctx.PropertyErrorf("sdk_version",
544 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
545 }
546 }
547 }
548
549 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
550 // See rank() for details.
551 ctx.VisitDirectDeps(func(module android.Module) {
552 tag := ctx.OtherModuleDependencyTag(module)
553 switch module.(type) {
554 // TODO(satayev): cover other types as well, e.g. imports
555 case *Library, *AndroidLibrary:
556 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400557 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700558 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
559 }
560 }
561 })
562}
563
564func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900565 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700566 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900567 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700568 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000569 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
Jaewoong Jung26342642021-03-17 15:56:23 -0700570 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000571 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
Jaewoong Jung26342642021-03-17 15:56:23 -0700572 }
573
574 }
575}
576
577func (j *Module) addHostProperties() {
578 j.AddProperties(
579 &j.properties,
580 &j.protoProperties,
581 &j.usesLibraryProperties,
582 )
583}
584
585func (j *Module) addHostAndDeviceProperties() {
586 j.addHostProperties()
587 j.AddProperties(
588 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900589 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700590 &j.dexer.dexProperties,
591 &j.dexpreoptProperties,
592 &j.linter.properties,
593 )
594}
595
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000596// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
597// makes it available through the hiddenAPIPropertyInfoProvider.
598func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
599 hiddenAPIInfo := newHiddenAPIPropertyInfo()
600
601 // Populate with flag file paths from the properties.
602 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
603
604 // Populate with package rules from the properties.
605 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
606
607 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
608}
609
Jaewoong Jung26342642021-03-17 15:56:23 -0700610func (j *Module) OutputFiles(tag string) (android.Paths, error) {
611 switch tag {
612 case "":
613 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
614 case android.DefaultDistTag:
615 return android.Paths{j.outputFile}, nil
616 case ".jar":
617 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700618 case ".hjar":
619 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700620 case ".proguard_map":
621 if j.dexer.proguardDictionary.Valid() {
622 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
623 }
624 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
625 default:
626 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
627 }
628}
629
630var _ android.OutputFileProducer = (*Module)(nil)
631
632func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
633 initJavaModule(module, hod, false)
634}
635
636func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
637 initJavaModule(module, hod, true)
638}
639
640func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
641 multilib := android.MultilibCommon
642 if multiTargets {
643 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
644 } else {
645 android.InitAndroidArchModule(module, hod, multilib)
646 }
647 android.InitDefaultableModule(module)
648}
649
650func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
651 return j.properties.Instrument &&
652 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
653 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
654}
655
656func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000657 return j.properties.Supports_static_instrumentation &&
658 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700659 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
660 ctx.Config().UnbundledBuild())
661}
662
663func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
664 // Force enable the instrumentation for java code that is built for APEXes ...
665 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
666 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
667 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
668 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
669 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
670 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
671 return true
672 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
673 return true
674 }
675 }
676 return false
677}
678
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400679func (j *Module) setInstrument(value bool) {
680 j.properties.Instrument = value
681}
682
Jiyong Park92315372021-04-02 08:45:46 +0900683func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
684 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700685}
686
Jiyong Parkf1691d22021-03-29 20:11:58 +0900687func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700688 return proptools.String(j.deviceProperties.System_modules)
689}
690
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000691func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700692 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000693 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700694 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000695 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700696}
697
Spandan Dasa26eda72023-03-02 00:56:06 +0000698func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
699 if j.deviceProperties.Max_sdk_version != nil {
700 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
701 }
702 // Default is PrivateApiLevel
703 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000704}
705
Spandan Dasa26eda72023-03-02 00:56:06 +0000706func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
707 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
708 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
709 }
710 // Default is PrivateApiLevel
711 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000712}
713
Jiyong Parkf1691d22021-03-29 20:11:58 +0900714func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000715 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900716}
717
Spandan Dasca70fc42023-03-01 23:38:49 +0000718func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900719 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000720 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900721 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000722 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700723}
724
725func (j *Module) AvailableFor(what string) bool {
726 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
727 // Exception: for hostdex: true libraries, the platform variant is created
728 // even if it's not marked as available to platform. In that case, the platform
729 // variant is used only for the hostdex and not installed to the device.
730 return true
731 }
732 return j.ApexModuleBase.AvailableFor(what)
733}
734
735func (j *Module) deps(ctx android.BottomUpMutatorContext) {
736 if ctx.Device() {
737 j.linter.deps(ctx)
738
Jiyong Parkf1691d22021-03-29 20:11:58 +0900739 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700740
741 if j.deviceProperties.SyspropPublicStub != "" {
742 // This is a sysprop implementation library that has a corresponding sysprop public
743 // stubs library, and a dependency on it so that dependencies on the implementation can
744 // be forwarded to the public stubs library when necessary.
745 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
746 }
747 }
748
749 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000750
751 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700752 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
753
754 // Add dependency on libraries that provide additional hidden api annotations.
755 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
756
757 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
758 // Require java_sdk_library at inter-partition java dependency to ensure stable
759 // interface between partitions. If inter-partition java_library dependency is detected,
760 // raise build error because java_library doesn't have a stable interface.
761 //
762 // Inputs:
763 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
764 // if true, enable enforcement
765 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
766 // exception list of java_library names to allow inter-partition dependency
767 for idx := range j.properties.Libs {
768 if libDeps[idx] == nil {
769 continue
770 }
771
772 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
773 // java_sdk_library is always allowed at inter-partition dependency.
774 // So, skip check.
775 if _, ok := javaDep.(*SdkLibrary); ok {
776 continue
777 }
778
779 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
780 }
781 }
782 }
783
784 // For library dependencies that are component libraries (like stubs), add the implementation
785 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
786 for _, dep := range libDeps {
787 if dep != nil {
788 if component, ok := dep.(SdkLibraryComponentDependency); ok {
789 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100790 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100791 tag := usesLibReqTag
792 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
793 tag = usesLibOptTag
794 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100795 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700796 }
797 }
798 }
799 }
800
801 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
802 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
803 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
804
805 android.ProtoDeps(ctx, &j.protoProperties)
806 if j.hasSrcExt(".proto") {
807 protoDeps(ctx, &j.protoProperties)
808 }
809
810 if j.hasSrcExt(".kt") {
811 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
812 // Kotlin files
813 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
814 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700815 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700816 }
817
818 // Framework libraries need special handling in static coverage builds: they should not have
819 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
820 // the same jacoco classes coming from different bootclasspath jars.
821 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
822 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
823 j.properties.Instrument = true
824 }
825 } else if j.shouldInstrumentStatic(ctx) {
826 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
827 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700828
829 if j.useCompose() {
830 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
831 "androidx.compose.compiler_compiler-hosted")
832 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700833}
834
835func hasSrcExt(srcs []string, ext string) bool {
836 for _, src := range srcs {
837 if filepath.Ext(src) == ext {
838 return true
839 }
840 }
841
842 return false
843}
844
845func (j *Module) hasSrcExt(ext string) bool {
846 return hasSrcExt(j.properties.Srcs, ext)
847}
848
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100849func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
850 var flags string
851
852 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
853 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
854 flags = "-Wmissing-permission-annotation -Werror"
855 }
856 }
857 return flags
858}
859
Jaewoong Jung26342642021-03-17 15:56:23 -0700860func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000861 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700862
863 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
864 aidlIncludes = append(aidlIncludes,
865 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
866 aidlIncludes = append(aidlIncludes,
867 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
868
869 var flags []string
870 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000871 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700872
873 flags = append(flags, j.deviceProperties.Aidl.Flags...)
874
875 if aidlPreprocess.Valid() {
876 flags = append(flags, "-p"+aidlPreprocess.String())
877 deps = append(deps, aidlPreprocess.Path())
878 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000879 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700880 }
881
882 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000883 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 }
885
886 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000887 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700888 }
889
Sam Delmerico2351eac2022-05-24 17:10:02 +0000890 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700891 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000892 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700893 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000894 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
895 // add flags for dirs containing AIDL srcs that haven't been specified yet
896 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700897
Zim8774ae12022-08-17 11:46:34 +0100898 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000899 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100900 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700901 flags = append(flags, "-t")
902 }
903
904 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
905 flags = append(flags, "--transaction_names")
906 }
907
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100908 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
909 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
910 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
911 }
912
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000913 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900914 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
915
Jaewoong Jung26342642021-03-17 15:56:23 -0700916 return strings.Join(flags, " "), deps
917}
918
919func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
920
921 var flags javaBuilderFlags
922
923 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900924 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700925
Cole Faust2b1536e2021-06-18 12:25:54 -0700926 epEnabled := j.properties.Errorprone.Enabled
927 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100928 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700929 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
930 }
931
932 errorProneFlags := []string{
933 "-Xplugin:ErrorProne",
934 "${config.ErrorProneChecks}",
935 }
936 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
937
Colin Cross8bf6cad2022-02-28 13:07:03 -0800938 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700939 "'" + strings.Join(errorProneFlags, " ") + "'"
940 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
941 }
942
943 // classpath
944 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
945 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700946 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700947 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
948 flags.processorPath = append(flags.processorPath, deps.processorPath...)
949 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
950
951 flags.processors = append(flags.processors, deps.processorClasses...)
952 flags.processors = android.FirstUniqueStrings(flags.processors)
953
954 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900955 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700956 // Give host-side tools a version of OpenJDK's standard libraries
957 // close to what they're targeting. As of Dec 2017, AOSP is only
958 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
959 //
960 // When building with OpenJDK 8, the following should have no
961 // effect since those jars would be available by default.
962 //
963 // When building with OpenJDK 9 but targeting a version < 1.8,
964 // putting them on the bootclasspath means that:
965 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
966 // b) references to existing APIs are not reinterpreted in an
967 // OpenJDK 9-specific way, eg. calls to subclasses of
968 // java.nio.Buffer as in http://b/70862583
969 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
970 flags.bootClasspath = append(flags.bootClasspath,
971 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
972 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
973 if Bool(j.properties.Use_tools_jar) {
974 flags.bootClasspath = append(flags.bootClasspath,
975 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
976 }
977 }
978
979 // systemModules
980 flags.systemModules = deps.systemModules
981
Jaewoong Jung26342642021-03-17 15:56:23 -0700982 return flags
983}
984
985func (j *Module) collectJavacFlags(
986 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
987 // javac flags.
988 javacFlags := j.properties.Javacflags
989
990 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
991 // For non-host binaries, override the -g flag passed globally to remove
992 // local variable debug info to reduce disk and memory usage.
993 javacFlags = append(javacFlags, "-g:source,lines")
994 }
995 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
996
997 if flags.javaVersion.usesJavaModules() {
998 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
999
1000 if j.properties.Patch_module != nil {
1001 // Manually specify build directory in case it is not under the repo root.
1002 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
1003 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001004 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -07001005
1006 // b/150878007
1007 //
1008 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
1009 // execution root for --patch-module. If this javac command line is
1010 // invoked within Bazel's execution root working directory, the top
1011 // level directories (e.g. libcore/, tools/, frameworks/) are all
1012 // symlinks. JDK9 javac does not traverse into symlinks, which causes
1013 // --patch-module to fail source file lookups when invoked in the
1014 // execution root.
1015 //
1016 // Short of patching javac or enumerating *all* directories as possible
1017 // input dirs, manually add the top level dir of the source files to be
1018 // compiled.
1019 topLevelDirs := map[string]bool{}
1020 for _, srcFilePath := range srcFiles {
1021 srcFileParts := strings.Split(srcFilePath.String(), "/")
1022 // Ignore source files that are already in the top level directory
1023 // as well as generated files in the out directory. The out
1024 // directory may be an absolute path, which means srcFileParts[0] is the
1025 // empty string, so check that as well. Note that "out" in Bazel's execution
1026 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1027 // anyway, so it's fine to not apply this workaround for generated
1028 // source files.
1029 if len(srcFileParts) > 1 &&
1030 srcFileParts[0] != "" &&
1031 srcFileParts[0] != "out" {
1032 topLevelDirs[srcFileParts[0]] = true
1033 }
1034 }
Cole Faust18994c72023-02-28 16:02:16 -08001035 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001036
1037 classPath := flags.classpath.FormJavaClassPath("")
1038 if classPath != "" {
1039 patchPaths = append(patchPaths, classPath)
1040 }
1041 javacFlags = append(
1042 javacFlags,
1043 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1044 }
1045 }
1046
1047 if len(javacFlags) > 0 {
1048 // optimization.
1049 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1050 flags.javacFlags = "$javacFlags"
1051 }
1052
1053 return flags
1054}
1055
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001056func (j *Module) AddJSONData(d *map[string]interface{}) {
1057 (&j.ModuleBase).AddJSONData(d)
1058 (*d)["Java"] = map[string]interface{}{
1059 "SourceExtensions": j.sourceExtensions,
1060 }
1061
1062}
1063
Joe Onorato175073c2023-06-01 14:42:59 -07001064func (module *Module) addGeneratedSrcJars(path android.Path) {
1065 module.properties.Generated_srcjars = append(module.properties.Generated_srcjars, path)
1066}
1067
Colin Cross4eae06d2023-06-20 22:40:02 -07001068func (j *Module) compile(ctx android.ModuleContext, extraSrcJars, extraClasspathJars, extraCombinedJars android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001069 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1070
1071 deps := j.collectDeps(ctx)
1072 flags := j.collectBuilderFlags(ctx, deps)
1073
1074 if flags.javaVersion.usesJavaModules() {
1075 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1076 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001077
Jaewoong Jung26342642021-03-17 15:56:23 -07001078 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001079 j.sourceExtensions = []string{}
1080 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1081 if hasSrcExt(srcFiles.Strings(), ext) {
1082 j.sourceExtensions = append(j.sourceExtensions, ext)
1083 }
1084 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 if hasSrcExt(srcFiles.Strings(), ".proto") {
1086 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1087 }
1088
1089 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1090 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1091 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1092 }
1093
Sam Delmerico2351eac2022-05-24 17:10:02 +00001094 aidlSrcs := srcFiles.FilterByExt(".aidl")
1095 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1096
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001097 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001098 srcFiles = j.genSources(ctx, srcFiles, flags)
1099
1100 // Collect javac flags only after computing the full set of srcFiles to
1101 // ensure that the --patch-module lookup paths are complete.
1102 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1103
1104 srcJars := srcFiles.FilterByExt(".srcjar")
1105 srcJars = append(srcJars, deps.srcJars...)
Colin Cross4eae06d2023-06-20 22:40:02 -07001106 srcJars = append(srcJars, extraSrcJars...)
Joe Onorato175073c2023-06-01 14:42:59 -07001107 srcJars = append(srcJars, j.properties.Generated_srcjars...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001108 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001109
1110 if j.properties.Jarjar_rules != nil {
1111 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1112 }
1113
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001114 jarName := j.Stem() + ".jar"
Jaewoong Jung26342642021-03-17 15:56:23 -07001115
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001116 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001117 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001118 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001119 if _, found := set[v.String()]; !found {
1120 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001121 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001122 }
1123 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001124 var uniqueKtFiles android.Paths
1125 for _, v := range srcFiles.FilterByExt(".kt") {
1126 if _, found := set[v.String()]; !found {
1127 set[v.String()] = true
1128 uniqueKtFiles = append(uniqueKtFiles, v)
1129 }
1130 }
1131
1132 var uniqueSrcFiles android.Paths
1133 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1134 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1135 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001136
Colin Crossb5db4012022-03-28 17:12:39 -07001137 // We don't currently run annotation processors in turbine, which means we can't use turbine
1138 // generated header jars when an annotation processor that generates API is enabled. One
1139 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1140 // is used to run all of the annotation processors.
1141 disableTurbine := deps.disableTurbine
1142
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001143 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1145
1146 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001147 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001148
Colin Cross4eae06d2023-06-20 22:40:02 -07001149 // Prepend extraClasspathJars to classpath so that the resource processor R.jar comes before
1150 // any dependencies so that it can override any non-final R classes from dependencies with the
1151 // final R classes from the app.
1152 flags.classpath = append(android.CopyOf(extraClasspathJars), flags.classpath...)
1153
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001155 // When using kotlin sources turbine is used to generate annotation processor sources,
1156 // including for annotation processors that generate API, so we can use turbine for
1157 // java sources too.
1158 disableTurbine = false
1159
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 // user defined kotlin flags.
1161 kotlincFlags := j.properties.Kotlincflags
1162 CheckKotlincFlags(ctx, kotlincFlags)
1163
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001164 // Workaround for KT-46512
1165 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001166
1167 // If there are kotlin files, compile them first but pass all the kotlin and java files
1168 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1169 // won't emit any classes for them.
1170 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1171 if ctx.Device() {
1172 kotlincFlags = append(kotlincFlags, "-no-jdk")
1173 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001174
1175 for _, plugin := range deps.kotlinPlugins {
1176 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1177 }
1178 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1179
Jaewoong Jung26342642021-03-17 15:56:23 -07001180 if len(kotlincFlags) > 0 {
1181 // optimization.
1182 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1183 flags.kotlincFlags += "$kotlincFlags"
1184 }
1185
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001186 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001187 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1188
1189 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1190 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1191
1192 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1193 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1194
Isaac Chioua23d9942022-04-06 06:14:38 +00001195 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001196 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001197 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1198 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001199 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001200 srcJars = append(srcJars, kaptSrcJar)
1201 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001202 // Disable annotation processing in javac, it's already been handled by kapt
1203 flags.processorPath = nil
1204 flags.processors = nil
1205 }
1206
1207 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001208 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001209 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001210 if ctx.Failed() {
1211 return
1212 }
1213
Isaac Chioua23d9942022-04-06 06:14:38 +00001214 // Make javac rule depend on the kotlinc rule
1215 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1216
Jaewoong Jung26342642021-03-17 15:56:23 -07001217 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001218 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1219
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 // Jar kotlin classes into the final jar after javac
1221 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1222 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001223 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001224 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001225 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001226 } else {
1227 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001228 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001229 }
1230 }
1231
1232 jars := append(android.Paths(nil), kotlinJars...)
1233
Jaewoong Jung26342642021-03-17 15:56:23 -07001234 j.compiledSrcJars = srcJars
1235
1236 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001237 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001238 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001239 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1240 enableSharding = true
1241 // Formerly, there was a check here that prevented annotation processors
1242 // from being used when sharding was enabled, as some annotation processors
1243 // do not function correctly in sharded environments. It was removed to
1244 // allow for the use of annotation processors that do function correctly
1245 // with sharding enabled. See: b/77284273.
1246 }
Colin Cross4eae06d2023-06-20 22:40:02 -07001247 extraJars := append(android.CopyOf(extraCombinedJars), kotlinHeaderJars...)
Colin Cross3d56ed52021-11-18 22:23:12 -08001248 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross4eae06d2023-06-20 22:40:02 -07001249 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, extraJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001250 if ctx.Failed() {
1251 return
1252 }
1253 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001254 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001255 hasErrorproneableFiles := false
1256 for _, ext := range j.sourceExtensions {
1257 if ext != ".proto" && ext != ".aidl" {
1258 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1259 // compile, and it's not useful to have warnings on these generated sources.
1260 hasErrorproneableFiles = true
1261 break
1262 }
1263 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001265 if Bool(j.properties.Errorprone.Enabled) {
1266 // If error-prone is enabled, enable errorprone flags on the regular
1267 // build.
1268 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001269 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001270 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1271 // a new jar file just for compiling with the errorprone compiler to.
1272 // This is because we don't want to cause the java files to get completely
1273 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1274 // We also don't want to run this if errorprone is enabled by default for
1275 // this module, or else we could have duplicated errorprone messages.
1276 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001277 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001278 errorproneAnnoSrcJar := android.PathForModuleOut(ctx, "errorprone", "anno.srcjar")
Cole Faust75fffb12021-06-13 15:23:16 -07001279
Vadim Spivak3c496f02023-06-08 06:14:59 +00001280 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneAnnoSrcJar, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001281 "errorprone", "errorprone")
1282
Jaewoong Jung26342642021-03-17 15:56:23 -07001283 extraJarDeps = append(extraJarDeps, errorprone)
1284 }
1285
1286 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001287 if headerJarFileWithoutDepsOrJarjar != nil {
1288 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1289 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001290 shardSize := int(*(j.properties.Javac_shard_size))
1291 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001292 if len(uniqueJavaFiles) > 0 {
1293 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001294 for idx, shardSrc := range shardSrcs {
1295 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1296 nil, flags, extraJarDeps)
1297 jars = append(jars, classes)
1298 }
1299 }
1300 if len(srcJars) > 0 {
1301 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1302 nil, srcJars, flags, extraJarDeps)
1303 jars = append(jars, classes)
1304 }
1305 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001306 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001307 jars = append(jars, classes)
1308 }
1309 if ctx.Failed() {
1310 return
1311 }
1312 }
1313
1314 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1315
1316 var includeSrcJar android.WritablePath
1317 if Bool(j.properties.Include_srcs) {
1318 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1319 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1320 }
1321
1322 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1323 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1324 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1325 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1326
1327 var resArgs []string
1328 var resDeps android.Paths
1329
1330 resArgs = append(resArgs, dirArgs...)
1331 resDeps = append(resDeps, dirDeps...)
1332
1333 resArgs = append(resArgs, fileArgs...)
1334 resDeps = append(resDeps, fileDeps...)
1335
1336 resArgs = append(resArgs, extraArgs...)
1337 resDeps = append(resDeps, extraDeps...)
1338
1339 if len(resArgs) > 0 {
1340 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1341 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1342 j.resourceJar = resourceJar
1343 if ctx.Failed() {
1344 return
1345 }
1346 }
1347
1348 var resourceJars android.Paths
1349 if j.resourceJar != nil {
1350 resourceJars = append(resourceJars, j.resourceJar)
1351 }
1352 if Bool(j.properties.Include_srcs) {
1353 resourceJars = append(resourceJars, includeSrcJar)
1354 }
1355 resourceJars = append(resourceJars, deps.staticResourceJars...)
1356
1357 if len(resourceJars) > 1 {
1358 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1359 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1360 false, nil, nil)
1361 j.resourceJar = combinedJar
1362 } else if len(resourceJars) == 1 {
1363 j.resourceJar = resourceJars[0]
1364 }
1365
1366 if len(deps.staticJars) > 0 {
1367 jars = append(jars, deps.staticJars...)
1368 }
1369
1370 manifest := j.overrideManifest
1371 if !manifest.Valid() && j.properties.Manifest != nil {
1372 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1373 }
1374
1375 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1376 if len(services) > 0 {
1377 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1378 var zipargs []string
1379 for _, file := range services {
1380 serviceFile := file.String()
1381 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1382 }
1383 rule := zip
1384 args := map[string]string{
1385 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1386 }
1387 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1388 rule = zipRE
1389 args["implicits"] = strings.Join(services.Strings(), ",")
1390 }
1391 ctx.Build(pctx, android.BuildParams{
1392 Rule: rule,
1393 Output: servicesJar,
1394 Implicits: services,
1395 Args: args,
1396 })
1397 jars = append(jars, servicesJar)
1398 }
1399
Colin Cross4eae06d2023-06-20 22:40:02 -07001400 jars = append(android.CopyOf(extraCombinedJars), jars...)
1401
Jaewoong Jung26342642021-03-17 15:56:23 -07001402 // Combine the classes built from sources, any manifests, and any static libraries into
1403 // classes.jar. If there is only one input jar this step will be skipped.
1404 var outputFile android.OutputPath
1405
1406 if len(jars) == 1 && !manifest.Valid() {
1407 // Optimization: skip the combine step as there is nothing to do
1408 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1409 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1410 // any if len(jars) == 1.
1411
Jihoon Kang1147b312023-06-08 23:25:57 +00001412 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1413 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1414 // either with .from-source or .from-text suffix.
1415 // outputFile should be agnostic to the build configuration,
1416 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1417 // to the copy rules.
1418 stub, _ := moduleStubLinkType(ctx.ModuleName())
1419
Jaewoong Jung26342642021-03-17 15:56:23 -07001420 // Transform the single path to the jar into an OutputPath as that is required by the following
1421 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001422 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001423 // The path contains an embedded OutputPath so reuse that.
1424 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001425 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001426 // The path is an OutputPath so reuse it directly.
1427 outputFile = outputPath
1428 } else {
1429 // The file is not in the out directory so create an OutputPath into which it can be copied
1430 // and which the following code can use to refer to it.
1431 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1432 ctx.Build(pctx, android.BuildParams{
1433 Rule: android.Cp,
1434 Input: jars[0],
1435 Output: combinedJar,
1436 })
1437 outputFile = combinedJar.OutputPath
1438 }
1439 } else {
1440 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1441 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1442 false, nil, nil)
1443 outputFile = combinedJar.OutputPath
1444 }
1445
1446 // jarjar implementation jar if necessary
1447 if j.expandJarjarRules != nil {
1448 // Transform classes.jar into classes-jarjar.jar
1449 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1450 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1451 outputFile = jarjarFile
1452
1453 // jarjar resource jar if necessary
1454 if j.resourceJar != nil {
1455 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1456 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1457 j.resourceJar = resourceJarJarFile
1458 }
1459
1460 if ctx.Failed() {
1461 return
1462 }
1463 }
1464
1465 // Check package restrictions if necessary.
1466 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001467 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001468 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001469
1470 // Create a rule to copy the output jar to another path and add a validate dependency that
1471 // will check that the jar only contains the permitted packages. The new location will become
1472 // the output file of this module.
1473 inputFile := outputFile
1474 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1475 ctx.Build(pctx, android.BuildParams{
1476 Rule: android.Cp,
1477 Input: inputFile,
1478 Output: outputFile,
1479 // Make sure that any dependency on the output file will cause ninja to run the package check
1480 // rule.
1481 Validation: pkgckFile,
1482 })
1483
1484 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001486
1487 if ctx.Failed() {
1488 return
1489 }
1490 }
1491
1492 j.implementationJarFile = outputFile
1493 if j.headerJarFile == nil {
Colin Crossf06d8dc2023-07-18 22:11:07 -07001494 // If this module couldn't generate a header jar (for example due to api generating annotation processors)
1495 // then use the implementation jar. Run it through zip2zip first to remove any files in META-INF/services
1496 // so that javac on modules that depend on this module don't pick up annotation processors (which may be
1497 // missing their implementations) from META-INF/services/javax.annotation.processing.Processor.
1498 headerJarFile := android.PathForModuleOut(ctx, "javac-header", jarName)
1499 convertImplementationJarToHeaderJar(ctx, j.implementationJarFile, headerJarFile)
1500 j.headerJarFile = headerJarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 }
1502
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001503 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1504 specs := j.jacocoModuleToZipCommand(ctx)
1505 if ctx.Failed() {
1506 return
1507 }
1508
Jaewoong Jung26342642021-03-17 15:56:23 -07001509 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001510 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 }
1512
1513 // merge implementation jar with resources if necessary
1514 implementationAndResourcesJar := outputFile
1515 if j.resourceJar != nil {
1516 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1517 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1518 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1519 false, nil, nil)
1520 implementationAndResourcesJar = combinedJar
1521 }
1522
1523 j.implementationAndResourcesJar = implementationAndResourcesJar
1524
1525 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001526 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001527 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1528 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001529 if compileDex == nil {
1530 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001531 }
1532 if j.deviceProperties.Hostdex == nil {
1533 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1534 }
1535 }
1536
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001537 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001538 if j.hasCode(ctx) {
1539 if j.shouldInstrumentStatic(ctx) {
1540 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1541 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1542 }
1543 // Dex compilation
1544 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001545 params := &compileDexParams{
1546 flags: flags,
1547 sdkVersion: j.SdkVersion(ctx),
1548 minSdkVersion: j.MinSdkVersion(ctx),
1549 classesJar: implementationAndResourcesJar,
1550 jarName: jarName,
1551 }
1552 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001553 if ctx.Failed() {
1554 return
1555 }
1556
Jaewoong Jung26342642021-03-17 15:56:23 -07001557 // merge dex jar with resources if necessary
1558 if j.resourceJar != nil {
1559 jars := android.Paths{dexOutputFile, j.resourceJar}
1560 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1561 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1562 false, nil, nil)
1563 if *j.dexProperties.Uncompress_dex {
1564 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1565 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1566 dexOutputFile = combinedAlignedJar
1567 } else {
1568 dexOutputFile = combinedJar
1569 }
1570 }
1571
Paul Duffin4de94502021-05-16 05:21:16 +01001572 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001573
1574 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001575
1576 // Encode hidden API flags in dex file, if needed.
1577 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1578
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001579 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001580
1581 // Dexpreopting
1582 j.dexpreopt(ctx, dexOutputFile)
1583
1584 outputFile = dexOutputFile
1585 } else {
1586 // There is no code to compile into a dex jar, make sure the resources are propagated
1587 // to the APK if this is an app.
1588 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001589 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001590 }
1591
1592 if ctx.Failed() {
1593 return
1594 }
1595 } else {
1596 outputFile = implementationAndResourcesJar
1597 }
1598
1599 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001600 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1601 if !apiLevel.IsPreview() {
1602 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001604 // When running metalava, we pass --version-codename. When that value
1605 // is not REL, metalava will add 1 to the --current-version argument.
1606 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1607 // branch) and the codename is REL, except potentially on the most
1608 // recent non-master branch. On that branch, it goes through two other
1609 // phases before it gets to the phase previously described:
1610 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1611 // is not rel. This happens for most of the internal branch's life
1612 // while the branch has been cut but is still under active development.
1613 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1614 // REL. This happens briefly during the release process. During this
1615 // state the code to add --current-version is commented out, and then
1616 // that commenting out is reverted after the codename is set to REL.
1617 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1618 // prior version and the codename is always non-REL.
1619 //
1620 // We need to add one here to match metalava adding 1. Technically
1621 // this means that in the state described in the second bullet point
1622 // above, this number is 1 higher than it should be.
1623 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001624 }
1625 }
1626
1627 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001628 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1629 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001630 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1631 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001632 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001633 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001634 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001635 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001636 j.linter.javaLanguageLevel = flags.javaVersion.String()
1637 j.linter.kotlinLanguageLevel = "1.3"
1638 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1639 j.linter.buildModuleReportZip = true
1640 }
1641 j.linter.lint(ctx)
1642 }
1643
1644 ctx.CheckbuildFile(outputFile)
1645
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001646 j.collectTransitiveAconfigFiles(ctx)
1647
Jaewoong Jung26342642021-03-17 15:56:23 -07001648 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1649 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001650 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1651 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1653 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1654 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1655 AidlIncludeDirs: j.exportAidlIncludeDirs,
1656 SrcJarArgs: j.srcJarArgs,
1657 SrcJarDeps: j.srcJarDeps,
1658 ExportedPlugins: j.exportedPluginJars,
1659 ExportedPluginClasses: j.exportedPluginClasses,
1660 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1661 JacocoReportClassesFile: j.jacocoReportClassesFile,
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001662 TransitiveAconfigFiles: j.transitiveAconfigFiles,
Jaewoong Jung26342642021-03-17 15:56:23 -07001663 })
1664
1665 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1666 j.outputFile = outputFile.WithoutRel()
1667}
1668
Colin Crossa1ff7c62021-09-17 14:11:52 -07001669func (j *Module) useCompose() bool {
1670 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1671}
1672
Sam Delmerico95d70942023-08-02 18:00:35 -04001673func (j *Module) collectProguardSpecInfo(ctx android.ModuleContext) ProguardSpecInfo {
1674 transitiveUnconditionalExportedFlags := []*android.DepSet[android.Path]{}
1675 transitiveProguardFlags := []*android.DepSet[android.Path]{}
1676
1677 ctx.VisitDirectDeps(func(m android.Module) {
1678 depProguardInfo := ctx.OtherModuleProvider(m, ProguardSpecInfoProvider).(ProguardSpecInfo)
1679 depTag := ctx.OtherModuleDependencyTag(m)
1680
1681 if depProguardInfo.UnconditionallyExportedProguardFlags != nil {
1682 transitiveUnconditionalExportedFlags = append(transitiveUnconditionalExportedFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1683 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.UnconditionallyExportedProguardFlags)
1684 }
1685
1686 if depTag == staticLibTag && depProguardInfo.ProguardFlagsFiles != nil {
1687 transitiveProguardFlags = append(transitiveProguardFlags, depProguardInfo.ProguardFlagsFiles)
1688 }
1689 })
1690
1691 directUnconditionalExportedFlags := android.Paths{}
1692 proguardFlagsForThisModule := android.PathsForModuleSrc(ctx, j.dexProperties.Optimize.Proguard_flags_files)
1693 exportUnconditionally := proptools.Bool(j.dexProperties.Optimize.Export_proguard_flags_files)
1694 if exportUnconditionally {
1695 // if we explicitly export, then our unconditional exports are the same as our transitive flags
1696 transitiveUnconditionalExportedFlags = transitiveProguardFlags
1697 directUnconditionalExportedFlags = proguardFlagsForThisModule
1698 }
1699
1700 return ProguardSpecInfo{
1701 Export_proguard_flags_files: exportUnconditionally,
1702 ProguardFlagsFiles: android.NewDepSet[android.Path](
1703 android.POSTORDER,
1704 proguardFlagsForThisModule,
1705 transitiveProguardFlags,
1706 ),
1707 UnconditionallyExportedProguardFlags: android.NewDepSet[android.Path](
1708 android.POSTORDER,
1709 directUnconditionalExportedFlags,
1710 transitiveUnconditionalExportedFlags,
1711 ),
1712 }
1713
1714}
1715
Cole Faust75fffb12021-06-13 15:23:16 -07001716// Returns a copy of the supplied flags, but with all the errorprone-related
1717// fields copied to the regular build's fields.
1718func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1719 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1720
1721 if len(flags.errorProneExtraJavacFlags) > 0 {
1722 if len(flags.javacFlags) > 0 {
1723 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1724 } else {
1725 flags.javacFlags = flags.errorProneExtraJavacFlags
1726 }
1727 }
1728 return flags
1729}
1730
Jaewoong Jung26342642021-03-17 15:56:23 -07001731func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1732 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1733
1734 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
Vadim Spivak3c496f02023-06-08 06:14:59 +00001735 annoSrcJar := android.PathForModuleOut(ctx, "javac", "anno.srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001736 if idx >= 0 {
1737 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
Vadim Spivak3c496f02023-06-08 06:14:59 +00001738 annoSrcJar = android.PathForModuleOut(ctx, "javac", "anno-"+strconv.Itoa(idx)+".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001739 jarName += strconv.Itoa(idx)
1740 }
1741
1742 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
Vadim Spivak3c496f02023-06-08 06:14:59 +00001743 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, annoSrcJar, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001744
1745 if ctx.Config().EmitXrefRules() {
1746 extractionFile := android.PathForModuleOut(ctx, kzipName)
1747 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1748 j.kytheFiles = append(j.kytheFiles, extractionFile)
1749 }
1750
Vadim Spivak3c496f02023-06-08 06:14:59 +00001751 if len(flags.processorPath) > 0 {
1752 j.annoSrcJars = append(j.annoSrcJars, annoSrcJar)
1753 }
1754
Jaewoong Jung26342642021-03-17 15:56:23 -07001755 return classes
1756}
1757
1758// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1759// since some of these flags may be used internally.
1760func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1761 for _, flag := range flags {
1762 flag = strings.TrimSpace(flag)
1763
1764 if !strings.HasPrefix(flag, "-") {
1765 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1766 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1767 ctx.PropertyErrorf("kotlincflags",
1768 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1769 } else if inList(flag, config.KotlincIllegalFlags) {
1770 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1771 } else if flag == "-include-runtime" {
1772 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1773 } else {
1774 args := strings.Split(flag, " ")
1775 if args[0] == "-kotlin-home" {
1776 ctx.PropertyErrorf("kotlincflags",
1777 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1778 }
1779 }
1780 }
1781}
1782
1783func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1784 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001785 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001786
1787 var jars android.Paths
1788 if len(srcFiles) > 0 || len(srcJars) > 0 {
1789 // Compile java sources into turbine.jar.
1790 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1791 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1792 if ctx.Failed() {
1793 return nil, nil
1794 }
1795 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001796 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001797 }
1798
1799 jars = append(jars, extraJars...)
1800
1801 // Combine any static header libraries into classes-header.jar. If there is only
1802 // one input jar this step will be skipped.
1803 jars = append(jars, deps.staticHeaderJars...)
1804
1805 // we cannot skip the combine step for now if there is only one jar
1806 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1807 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1808 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1809 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001810 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001811
1812 if j.expandJarjarRules != nil {
1813 // Transform classes.jar into classes-jarjar.jar
1814 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001815 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1816 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 if ctx.Failed() {
1818 return nil, nil
1819 }
1820 }
1821
Colin Cross3d56ed52021-11-18 22:23:12 -08001822 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001823}
1824
1825func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001826 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001827
1828 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1829 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1830
1831 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1832
1833 j.jacocoReportClassesFile = jacocoReportClassesFile
1834
1835 return instrumentedJar
1836}
1837
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001838type providesTransitiveHeaderJars struct {
1839 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001840 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001841 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001842 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001843}
1844
Colin Crossc85750b2022-04-21 12:50:51 -07001845func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001846 return j.transitiveLibsHeaderJars
1847}
1848
Colin Crossc85750b2022-04-21 12:50:51 -07001849func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001850 return j.transitiveStaticLibsHeaderJars
1851}
1852
1853func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1854 directLibs := android.Paths{}
1855 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001856 transitiveLibs := []*android.DepSet[android.Path]{}
1857 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001858 ctx.VisitDirectDeps(func(module android.Module) {
1859 // don't add deps of the prebuilt version of the same library
1860 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1861 return
1862 }
1863
1864 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1865 if dep.TransitiveLibsHeaderJars != nil {
1866 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1867 }
1868 if dep.TransitiveStaticLibsHeaderJars != nil {
1869 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1870 }
1871
1872 tag := ctx.OtherModuleDependencyTag(module)
1873 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1874 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1875 directLibs = append(directLibs, dep.HeaderJars...)
1876 } else if tag == staticLibTag {
1877 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1878 }
1879 })
1880 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1881 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1882}
1883
Jaewoong Jung26342642021-03-17 15:56:23 -07001884func (j *Module) HeaderJars() android.Paths {
1885 if j.headerJarFile == nil {
1886 return nil
1887 }
1888 return android.Paths{j.headerJarFile}
1889}
1890
1891func (j *Module) ImplementationJars() android.Paths {
1892 if j.implementationJarFile == nil {
1893 return nil
1894 }
1895 return android.Paths{j.implementationJarFile}
1896}
1897
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001898func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001899 return j.dexJarFile
1900}
1901
1902func (j *Module) DexJarInstallPath() android.Path {
1903 return j.installFile
1904}
1905
1906func (j *Module) ImplementationAndResourcesJars() android.Paths {
1907 if j.implementationAndResourcesJar == nil {
1908 return nil
1909 }
1910 return android.Paths{j.implementationAndResourcesJar}
1911}
1912
1913func (j *Module) AidlIncludeDirs() android.Paths {
1914 // exportAidlIncludeDirs is type android.Paths already
1915 return j.exportAidlIncludeDirs
1916}
1917
1918func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1919 return j.classLoaderContexts
1920}
1921
1922// Collect information for opening IDE project files in java/jdeps.go.
1923func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1924 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1925 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1926 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1927 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1928 if j.expandJarjarRules != nil {
1929 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1930 }
1931 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001932 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1933 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Vadim Spivak3c496f02023-06-08 06:14:59 +00001934 dpInfo.SrcJars = append(dpInfo.SrcJars, j.annoSrcJars.Strings()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001935}
1936
1937func (j *Module) CompilerDeps() []string {
1938 jdeps := []string{}
1939 jdeps = append(jdeps, j.properties.Libs...)
1940 jdeps = append(jdeps, j.properties.Static_libs...)
1941 return jdeps
1942}
1943
1944func (j *Module) hasCode(ctx android.ModuleContext) bool {
1945 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1946 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1947}
1948
1949// Implements android.ApexModule
1950func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1951 return j.depIsInSameApex(ctx, dep)
1952}
1953
1954// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001955func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001956 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001957 minSdkVersion := j.MinSdkVersion(ctx)
1958 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001959 return fmt.Errorf("min_sdk_version is not specified")
1960 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001961 // If the module is compiling against core (via sdk_version), skip comparison check.
1962 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001963 return nil
1964 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001965 if minSdkVersion.GreaterThan(sdkVersion) {
1966 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001967 }
1968 return nil
1969}
1970
1971func (j *Module) Stem() string {
Jihoon Kang1bfb6f22023-07-01 00:13:47 +00001972 if j.stem == "" {
1973 panic("Stem() called before stem property was set")
1974 }
1975 return j.stem
Jaewoong Jung26342642021-03-17 15:56:23 -07001976}
1977
Jaewoong Jung26342642021-03-17 15:56:23 -07001978func (j *Module) JacocoReportClassesFile() android.Path {
1979 return j.jacocoReportClassesFile
1980}
1981
1982func (j *Module) IsInstallable() bool {
1983 return Bool(j.properties.Installable)
1984}
1985
Joe Onorato6fe59eb2023-07-16 13:20:33 -07001986func (j *Module) collectTransitiveAconfigFiles(ctx android.ModuleContext) {
1987 // Aconfig files from this module
1988 mine := j.aconfigIntermediates
1989
1990 // Aconfig files from transitive dependencies
1991 fromDeps := []*android.DepSet[android.Path]{}
1992 ctx.VisitDirectDeps(func(module android.Module) {
1993 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1994 if dep.TransitiveAconfigFiles != nil {
1995 fromDeps = append(fromDeps, dep.TransitiveAconfigFiles)
1996 }
1997 })
1998
1999 // DepSet containing aconfig files myself and from dependencies
2000 j.transitiveAconfigFiles = android.NewDepSet(android.POSTORDER, mine, fromDeps)
2001}
2002
2003func (j *Module) AddAconfigIntermediate(path android.Path) {
2004 j.aconfigIntermediates = append(j.aconfigIntermediates, path)
2005}
2006
2007func (j *Module) getTransitiveAconfigFiles() *android.DepSet[android.Path] {
2008 if j.transitiveAconfigFiles == nil {
2009 panic(fmt.Errorf("java.Moduile: getTransitiveAconfigFiles called before collectTransitiveAconfigFiles module=%s", j.Name()))
2010 }
2011 return j.transitiveAconfigFiles
2012}
2013
Jaewoong Jung26342642021-03-17 15:56:23 -07002014type sdkLinkType int
2015
2016const (
2017 // TODO(jiyong) rename these for better readability. Make the allowed
2018 // and disallowed link types explicit
2019 // order is important here. See rank()
2020 javaCore sdkLinkType = iota
2021 javaSdk
2022 javaSystem
2023 javaModule
2024 javaSystemServer
2025 javaPlatform
2026)
2027
2028func (lt sdkLinkType) String() string {
2029 switch lt {
2030 case javaCore:
2031 return "core Java API"
2032 case javaSdk:
2033 return "Android API"
2034 case javaSystem:
2035 return "system API"
2036 case javaModule:
2037 return "module API"
2038 case javaSystemServer:
2039 return "system server API"
2040 case javaPlatform:
2041 return "private API"
2042 default:
2043 panic(fmt.Errorf("unrecognized linktype: %d", lt))
2044 }
2045}
2046
2047// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
2048// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
2049// can't statically depend on modules that use Platform API.
2050func (lt sdkLinkType) rank() int {
2051 return int(lt)
2052}
2053
2054type moduleWithSdkDep interface {
2055 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09002056 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07002057}
2058
Jiyong Park92315372021-04-02 08:45:46 +09002059func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07002060 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00002061 case android.SdkCore.DefaultJavaLibraryName(),
2062 "legacy.core.platform.api.stubs",
2063 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07002064 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00002065 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00002066 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07002067 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002068 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002069 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002070 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002071 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002072 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002073 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002074 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002075 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00002076 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07002077 return javaSystem, true
2078 }
2079
2080 if stub, linkType := moduleStubLinkType(name); stub {
2081 return linkType, true
2082 }
2083
Jiyong Park92315372021-04-02 08:45:46 +09002084 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09002085 switch ver.Kind {
2086 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07002087 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002088 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07002089 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002090 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07002091 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002092 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07002093 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002094 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07002095 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09002096 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07002097 return javaPlatform, false
2098 }
2099
Jiyong Parkf1691d22021-03-29 20:11:58 +09002100 if !ver.Valid() {
2101 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07002102 }
2103 return javaSdk, false
2104}
2105
2106// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
2107// this module's. See the comment on rank() for details and an example.
2108func (j *Module) checkSdkLinkType(
2109 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
2110 if ctx.Host() {
2111 return
2112 }
2113
Jiyong Park92315372021-04-02 08:45:46 +09002114 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002115 if stubs {
2116 return
2117 }
Jiyong Park92315372021-04-02 08:45:46 +09002118 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002119
2120 if myLinkType.rank() < depLinkType.rank() {
2121 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2122 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2123 "property of the source or target module so that target module is built "+
2124 "with the same or smaller API set when compared to the source.",
2125 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2126 }
2127}
2128
2129func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2130 var deps deps
2131
2132 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002133 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002134 if sdkDep.invalidVersion {
2135 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2136 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2137 } else if sdkDep.useFiles {
2138 // sdkDep.jar is actually equivalent to turbine header.jar.
2139 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002140 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002141 deps.aidlPreprocess = sdkDep.aidl
2142 } else {
2143 deps.aidlPreprocess = sdkDep.aidl
2144 }
2145 }
2146
Jiyong Park92315372021-04-02 08:45:46 +09002147 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002148
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002149 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002150 ctx.VisitDirectDeps(func(module android.Module) {
2151 otherName := ctx.OtherModuleName(module)
2152 tag := ctx.OtherModuleDependencyTag(module)
2153
2154 if IsJniDepTag(tag) {
2155 // Handled by AndroidApp.collectAppDeps
2156 return
2157 }
2158 if tag == certificateTag {
2159 // Handled by AndroidApp.collectAppDeps
2160 return
2161 }
2162
2163 if dep, ok := module.(SdkLibraryDependency); ok {
2164 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002165 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002166 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2167 deps.classpath = append(deps.classpath, depHeaderJars...)
2168 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002169 case staticLibTag:
2170 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2171 }
2172 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2173 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2174 if sdkLinkType != javaPlatform &&
2175 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2176 // dep is a sysprop implementation library, but this module is not linking against
2177 // the platform, so it gets the sysprop public stubs library instead. Replace
2178 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2179 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2180 dep = syspropDep.JavaInfo
2181 }
2182 switch tag {
2183 case bootClasspathTag:
2184 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002185 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002186 if _, ok := module.(*Plugin); ok {
2187 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2188 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002189 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002190 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002191 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2192 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2193 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2194 case java9LibTag:
2195 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2196 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002197 if _, ok := module.(*Plugin); ok {
2198 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2199 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002200 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2201 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2202 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2203 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2204 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2205 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2206 // Turbine doesn't run annotation processors, so any module that uses an
2207 // annotation processor that generates API is incompatible with the turbine
2208 // optimization.
2209 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2210 case pluginTag:
2211 if plugin, ok := module.(*Plugin); ok {
2212 if plugin.pluginProperties.Processor_class != nil {
2213 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2214 } else {
2215 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2216 }
2217 // Turbine doesn't run annotation processors, so any module that uses an
2218 // annotation processor that generates API is incompatible with the turbine
2219 // optimization.
2220 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2221 } else {
2222 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2223 }
2224 case errorpronePluginTag:
2225 if _, ok := module.(*Plugin); ok {
2226 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2227 } else {
2228 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2229 }
2230 case exportedPluginTag:
2231 if plugin, ok := module.(*Plugin); ok {
2232 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2233 if plugin.pluginProperties.Processor_class != nil {
2234 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
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 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2240 } else {
2241 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2242 }
2243 case kotlinStdlibTag:
2244 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2245 case kotlinAnnotationsTag:
2246 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002247 case kotlinPluginTag:
2248 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002249 case syspropPublicStubDepTag:
2250 // This is a sysprop implementation library, forward the JavaInfoProvider from
2251 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2252 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2253 JavaInfo: dep,
2254 })
2255 }
2256 } else if dep, ok := module.(android.SourceFileProducer); ok {
2257 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002258 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002259 checkProducesJars(ctx, dep)
2260 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002261 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002262 case staticLibTag:
2263 checkProducesJars(ctx, dep)
2264 deps.classpath = append(deps.classpath, dep.Srcs()...)
2265 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2266 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2267 }
2268 } else {
2269 switch tag {
2270 case bootClasspathTag:
2271 // If a system modules dependency has been added to the bootclasspath
2272 // then add its libs to the bootclasspath.
2273 sm := module.(SystemModulesProvider)
2274 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2275
2276 case systemModulesTag:
2277 if deps.systemModules != nil {
2278 panic("Found two system module dependencies")
2279 }
2280 sm := module.(SystemModulesProvider)
2281 outputDir, outputDeps := sm.OutputDirAndDeps()
2282 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002283
2284 case instrumentationForTag:
2285 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 -07002286 }
2287 }
2288
2289 addCLCFromDep(ctx, module, j.classLoaderContexts)
2290 })
2291
2292 return deps
2293}
2294
2295func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2296 deps.processorPath = append(deps.processorPath, pluginJars...)
2297 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2298}
2299
2300// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2301// this interface.
2302type ProvidesUsesLib interface {
2303 ProvidesUsesLib() *string
2304}
2305
2306func (j *Module) ProvidesUsesLib() *string {
2307 return j.usesLibraryProperties.Provides_uses_lib
2308}
satayev1c564cc2021-05-25 19:50:30 +01002309
2310type ModuleWithStem interface {
2311 Stem() string
2312}
2313
2314var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002315
2316func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2317 switch ctx.ModuleType() {
Zi Wang3096e682023-06-27 15:44:10 -07002318 case "java_library", "java_library_host", "java_library_static", "tradefed_java_library_host":
Wei Libafb6d62021-12-10 03:14:59 -08002319 if lib, ok := ctx.Module().(*Library); ok {
2320 javaLibraryBp2Build(ctx, lib)
2321 }
2322 case "java_binary_host":
2323 if binary, ok := ctx.Module().(*Binary); ok {
2324 javaBinaryHostBp2Build(ctx, binary)
2325 }
Zi Wang65b36722023-05-23 15:18:33 -07002326 case "java_test_host":
2327 if testHost, ok := ctx.Module().(*TestHost); ok {
2328 javaTestHostBp2Build(ctx, testHost)
2329 }
Chris Parsons39a16972023-06-08 14:28:51 +00002330 default:
2331 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_TYPE_UNSUPPORTED, "")
Wei Libafb6d62021-12-10 03:14:59 -08002332 }
Wei Libafb6d62021-12-10 03:14:59 -08002333}