blob: cfbd91b9b4787b3ab9ef3713dd6354beeb64ceea [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
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
Cole Faust2b1536e2021-06-18 12:25:54 -0700159 // This property can be in 3 states. When set to true, errorprone will
160 // be run during the regular build. When set to false, errorprone will
161 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
162 // environment variable is true. Setting this to false will improve build
163 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700164 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700165 }
166
167 Proto struct {
168 // List of extra options that will be passed to the proto generator.
169 Output_params []string
170 }
171
172 Instrument bool `blueprint:"mutated"`
173
174 // List of files to include in the META-INF/services folder of the resulting jar.
175 Services []string `android:"path,arch_variant"`
176
177 // If true, package the kotlin stdlib into the jar. Defaults to true.
178 Static_kotlin_stdlib *bool `android:"arch_variant"`
179
180 // A list of java_library instances that provide additional hiddenapi annotations for the library.
181 Hiddenapi_additional_annotations []string
182}
183
184// Properties that are specific to device modules. Host module factories should not add these when
185// constructing a new module.
186type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000187 // If not blank, set to the version of the sdk to compile against.
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000188 // Defaults to private.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000189 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000190 // 1) numerical API level, "current", "none", or "core_platform"
191 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
192 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
193 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700194 Sdk_version *string
195
196 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000197 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700198 Min_sdk_version *string
199
satayev0a420e72021-11-29 17:25:52 +0000200 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
201 // Defaults to empty string "". See sdk_version for possible values.
202 Max_sdk_version *string
203
Jaewoong Jung26342642021-03-17 15:56:23 -0700204 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Target_sdk_version *string
207
208 // Whether to compile against the platform APIs instead of an SDK.
209 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000210 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 Platform_apis *bool
212
213 Aidl struct {
214 // Top level directories to pass to aidl tool
215 Include_dirs []string
216
217 // Directories rooted at the Android.bp file to pass to aidl tool
218 Local_include_dirs []string
219
220 // directories that should be added as include directories for any aidl sources of modules
221 // that depend on this module, as well as to aidl for this module.
222 Export_include_dirs []string
223
224 // whether to generate traces (for systrace) for this interface
225 Generate_traces *bool
226
227 // whether to generate Binder#GetTransaction name method.
228 Generate_get_transaction_name *bool
229
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100230 // whether all interfaces should be annotated with required permissions.
231 Enforce_permissions *bool
232
233 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
234 Enforce_permissions_exceptions []string `android:"path"`
235
Jaewoong Jung26342642021-03-17 15:56:23 -0700236 // list of flags that will be passed to the AIDL compiler
237 Flags []string
238 }
239
240 // If true, export a copy of the module as a -hostdex module for host testing.
241 Hostdex *bool
242
243 Target struct {
244 Hostdex struct {
245 // Additional required dependencies to add to -hostdex modules.
246 Required []string
247 }
248 }
249
250 // When targeting 1.9 and above, override the modules to use with --system,
251 // otherwise provides defaults libraries to add to the bootclasspath.
252 System_modules *string
253
Jaewoong Jung26342642021-03-17 15:56:23 -0700254 IsSDKLibrary bool `blueprint:"mutated"`
255
256 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
257 // Defaults to false.
258 V4_signature *bool
259
260 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
261 // public stubs library.
262 SyspropPublicStub string `blueprint:"mutated"`
263}
264
Jooyung Han01d80d82022-01-08 12:16:32 +0900265// Device properties that can be overridden by overriding module (e.g. override_android_app)
266type OverridableDeviceProperties struct {
267 // set the name of the output. If not set, `name` is used.
268 // To override a module with this property set, overriding module might need to set this as well.
269 // Otherwise, both the overridden and the overriding modules will have the same output name, which
270 // can cause the duplicate output error.
271 Stem *string
272}
273
Jaewoong Jung26342642021-03-17 15:56:23 -0700274// Functionality common to Module and Import
275//
276// It is embedded in Module so its functionality can be used by methods in Module
277// but it is currently only initialized by Import and Library.
278type embeddableInModuleAndImport struct {
279
280 // Functionality related to this being used as a component of a java_sdk_library.
281 EmbeddableSdkLibraryComponent
282}
283
Paul Duffin71b33cc2021-06-23 11:39:47 +0100284func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
285 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700286}
287
288// Module/Import's DepIsInSameApex(...) delegates to this method.
289//
290// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
291// the one provided by ApexModuleBase.
292func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
293 // dependencies other than the static linkage are all considered crossing APEX boundary
294 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
295 return true
296 }
297 return false
298}
299
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100300// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
301// or an invalid path describing the reason it is invalid.
302//
303// It is unset if a dex jar isn't applicable, i.e. no build rule has been
304// requested to create one.
305//
306// If a dex jar has been requested to be built then it is set, and it may be
307// either a valid android.Path, or invalid with a reason message. The latter
308// happens if the source that should produce the dex file isn't able to.
309//
310// E.g. it is invalid with a reason message if there is a prebuilt APEX that
311// could produce the dex jar through a deapexer module, but the APEX isn't
312// installable so doing so wouldn't be safe.
313type OptionalDexJarPath struct {
314 isSet bool
315 path android.OptionalPath
316}
317
318// IsSet returns true if a path has been set, either invalid or valid.
319func (o OptionalDexJarPath) IsSet() bool {
320 return o.isSet
321}
322
323// Valid returns true if there is a path that is valid.
324func (o OptionalDexJarPath) Valid() bool {
325 return o.isSet && o.path.Valid()
326}
327
328// Path returns the valid path, or panics if it's either not set or is invalid.
329func (o OptionalDexJarPath) Path() android.Path {
330 if !o.isSet {
331 panic("path isn't set")
332 }
333 return o.path.Path()
334}
335
336// PathOrNil returns the path if it's set and valid, or else nil.
337func (o OptionalDexJarPath) PathOrNil() android.Path {
338 if o.Valid() {
339 return o.Path()
340 }
341 return nil
342}
343
344// InvalidReason returns the reason for an invalid path, which is never "". It
345// returns "" for an unset or valid path.
346func (o OptionalDexJarPath) InvalidReason() string {
347 if !o.isSet {
348 return ""
349 }
350 return o.path.InvalidReason()
351}
352
353func (o OptionalDexJarPath) String() string {
354 if !o.isSet {
355 return "<unset>"
356 }
357 return o.path.String()
358}
359
360// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
361func makeUnsetDexJarPath() OptionalDexJarPath {
362 return OptionalDexJarPath{isSet: false}
363}
364
365// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
366// the given OptionalPath, which may be valid or invalid.
367func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
368 return OptionalDexJarPath{isSet: true, path: path}
369}
370
371// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
372// valid given path. It returns an unset OptionalDexJarPath if the given path is
373// nil.
374func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
375 if path == nil {
376 return makeUnsetDexJarPath()
377 }
378 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
379}
380
Jaewoong Jung26342642021-03-17 15:56:23 -0700381// Module contains the properties and members used by all java module types
382type Module struct {
383 android.ModuleBase
384 android.DefaultableModuleBase
385 android.ApexModuleBase
386 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800387 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700388
389 // Functionality common to Module and Import.
390 embeddableInModuleAndImport
391
392 properties CommonProperties
393 protoProperties android.ProtoProperties
394 deviceProperties DeviceProperties
395
Jooyung Han01d80d82022-01-08 12:16:32 +0900396 overridableDeviceProperties OverridableDeviceProperties
397
Jaewoong Jung26342642021-03-17 15:56:23 -0700398 // jar file containing header classes including static library dependencies, suitable for
399 // inserting into the bootclasspath/classpath of another compile
400 headerJarFile android.Path
401
402 // jar file containing implementation classes including static library dependencies but no
403 // resources
404 implementationJarFile android.Path
405
406 // jar file containing only resources including from static library dependencies
407 resourceJar android.Path
408
409 // args and dependencies to package source files into a srcjar
410 srcJarArgs []string
411 srcJarDeps android.Paths
412
413 // jar file containing implementation classes and resources including static library
414 // dependencies
415 implementationAndResourcesJar android.Path
416
417 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100418 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700419
420 // output file containing uninstrumented classes that will be instrumented by jacoco
421 jacocoReportClassesFile android.Path
422
423 // output file of the module, which may be a classes jar or a dex jar
424 outputFile android.Path
425 extraOutputFiles android.Paths
426
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100427 exportAidlIncludeDirs android.Paths
428 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700429
430 logtagsSrcs android.Paths
431
432 // installed file for binary dependency
433 installFile android.Path
434
Colin Cross3108ce12021-11-10 14:38:50 -0800435 // installed file for hostdex copy
436 hostdexInstallFile android.InstallPath
437
Jaewoong Jung26342642021-03-17 15:56:23 -0700438 // list of .java files and srcjars that was passed to javac
439 compiledJavaSrcs android.Paths
440 compiledSrcJars android.Paths
441
442 // manifest file to use instead of properties.Manifest
443 overrideManifest android.OptionalPath
444
Jaewoong Jung26342642021-03-17 15:56:23 -0700445 // list of plugins that this java module is exporting
446 exportedPluginJars android.Paths
447
448 // list of plugins that this java module is exporting
449 exportedPluginClasses []string
450
451 // if true, the exported plugins generate API and require disabling turbine.
452 exportedDisableTurbine bool
453
454 // list of source files, collected from srcFiles with unique java and all kt files,
455 // will be used by android.IDEInfo struct
456 expandIDEInfoCompiledSrcs []string
457
458 // expanded Jarjar_rules
459 expandJarjarRules android.Path
460
Jaewoong Jung26342642021-03-17 15:56:23 -0700461 // Extra files generated by the module type to be added as java resources.
462 extraResources android.Paths
463
464 hiddenAPI
465 dexer
466 dexpreopter
467 usesLibrary
468 linter
469
470 // list of the xref extraction files
471 kytheFiles android.Paths
472
473 // Collect the module directory for IDE info in java/jdeps.go.
474 modulePaths []string
475
476 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900477
478 sdkVersion android.SdkSpec
479 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000480 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400481
482 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700483}
484
Jiyong Park92315372021-04-02 08:45:46 +0900485func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
486 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900487 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700488 return nil
489 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900490 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000491 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700492 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
493 } else {
494 // Treat stable core platform as stable.
495 return nil
496 }
497 } else {
498 return fmt.Errorf("non stable SDK %v", sdkVersion)
499 }
500}
501
502// checkSdkVersions enforces restrictions around SDK dependencies.
503func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
504 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900505 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900506 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700507 ctx.PropertyErrorf("sdk_version",
508 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
509 }
510 }
511 }
512
513 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
514 // See rank() for details.
515 ctx.VisitDirectDeps(func(module android.Module) {
516 tag := ctx.OtherModuleDependencyTag(module)
517 switch module.(type) {
518 // TODO(satayev): cover other types as well, e.g. imports
519 case *Library, *AndroidLibrary:
520 switch tag {
521 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
522 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
523 }
524 }
525 })
526}
527
528func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900529 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700530 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900531 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700532 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000533 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 -0700534 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000535 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 -0700536 }
537
538 }
539}
540
541func (j *Module) addHostProperties() {
542 j.AddProperties(
543 &j.properties,
544 &j.protoProperties,
545 &j.usesLibraryProperties,
546 )
547}
548
549func (j *Module) addHostAndDeviceProperties() {
550 j.addHostProperties()
551 j.AddProperties(
552 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900553 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700554 &j.dexer.dexProperties,
555 &j.dexpreoptProperties,
556 &j.linter.properties,
557 )
558}
559
560func (j *Module) OutputFiles(tag string) (android.Paths, error) {
561 switch tag {
562 case "":
563 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
564 case android.DefaultDistTag:
565 return android.Paths{j.outputFile}, nil
566 case ".jar":
567 return android.Paths{j.implementationAndResourcesJar}, nil
568 case ".proguard_map":
569 if j.dexer.proguardDictionary.Valid() {
570 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
571 }
572 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
573 default:
574 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
575 }
576}
577
578var _ android.OutputFileProducer = (*Module)(nil)
579
580func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
581 initJavaModule(module, hod, false)
582}
583
584func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
585 initJavaModule(module, hod, true)
586}
587
588func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
589 multilib := android.MultilibCommon
590 if multiTargets {
591 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
592 } else {
593 android.InitAndroidArchModule(module, hod, multilib)
594 }
595 android.InitDefaultableModule(module)
596}
597
598func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
599 return j.properties.Instrument &&
600 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
601 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
602}
603
604func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
605 return j.shouldInstrument(ctx) &&
606 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
607 ctx.Config().UnbundledBuild())
608}
609
610func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
611 // Force enable the instrumentation for java code that is built for APEXes ...
612 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
613 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
614 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
615 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
616 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
617 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
618 return true
619 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
620 return true
621 }
622 }
623 return false
624}
625
Jiyong Park92315372021-04-02 08:45:46 +0900626func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
627 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700628}
629
Jiyong Parkf1691d22021-03-29 20:11:58 +0900630func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700631 return proptools.String(j.deviceProperties.System_modules)
632}
633
Jiyong Park92315372021-04-02 08:45:46 +0900634func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700635 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900636 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700637 }
Jiyong Park92315372021-04-02 08:45:46 +0900638 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700639}
640
satayev0a420e72021-11-29 17:25:52 +0000641func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
642 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
643 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
644 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
645 return android.SdkSpecFrom(ctx, maxSdkVersion)
646}
647
Jiyong Parkf1691d22021-03-29 20:11:58 +0900648func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900649 return j.minSdkVersion.Raw
650}
651
652func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
653 if j.deviceProperties.Target_sdk_version != nil {
654 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
655 }
656 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700657}
658
659func (j *Module) AvailableFor(what string) bool {
660 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
661 // Exception: for hostdex: true libraries, the platform variant is created
662 // even if it's not marked as available to platform. In that case, the platform
663 // variant is used only for the hostdex and not installed to the device.
664 return true
665 }
666 return j.ApexModuleBase.AvailableFor(what)
667}
668
669func (j *Module) deps(ctx android.BottomUpMutatorContext) {
670 if ctx.Device() {
671 j.linter.deps(ctx)
672
Jiyong Parkf1691d22021-03-29 20:11:58 +0900673 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700674
675 if j.deviceProperties.SyspropPublicStub != "" {
676 // This is a sysprop implementation library that has a corresponding sysprop public
677 // stubs library, and a dependency on it so that dependencies on the implementation can
678 // be forwarded to the public stubs library when necessary.
679 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
680 }
681 }
682
683 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
684 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
685
686 // Add dependency on libraries that provide additional hidden api annotations.
687 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
688
689 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
690 // Require java_sdk_library at inter-partition java dependency to ensure stable
691 // interface between partitions. If inter-partition java_library dependency is detected,
692 // raise build error because java_library doesn't have a stable interface.
693 //
694 // Inputs:
695 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
696 // if true, enable enforcement
697 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
698 // exception list of java_library names to allow inter-partition dependency
699 for idx := range j.properties.Libs {
700 if libDeps[idx] == nil {
701 continue
702 }
703
704 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
705 // java_sdk_library is always allowed at inter-partition dependency.
706 // So, skip check.
707 if _, ok := javaDep.(*SdkLibrary); ok {
708 continue
709 }
710
711 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
712 }
713 }
714 }
715
716 // For library dependencies that are component libraries (like stubs), add the implementation
717 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
718 for _, dep := range libDeps {
719 if dep != nil {
720 if component, ok := dep.(SdkLibraryComponentDependency); ok {
721 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100722 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100723 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
724 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100725 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700726 }
727 }
728 }
729 }
730
731 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
732 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
733 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
734
735 android.ProtoDeps(ctx, &j.protoProperties)
736 if j.hasSrcExt(".proto") {
737 protoDeps(ctx, &j.protoProperties)
738 }
739
740 if j.hasSrcExt(".kt") {
741 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
742 // Kotlin files
743 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
744 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700745 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700746 }
747
748 // Framework libraries need special handling in static coverage builds: they should not have
749 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
750 // the same jacoco classes coming from different bootclasspath jars.
751 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
752 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
753 j.properties.Instrument = true
754 }
755 } else if j.shouldInstrumentStatic(ctx) {
756 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
757 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700758
759 if j.useCompose() {
760 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
761 "androidx.compose.compiler_compiler-hosted")
762 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700763}
764
765func hasSrcExt(srcs []string, ext string) bool {
766 for _, src := range srcs {
767 if filepath.Ext(src) == ext {
768 return true
769 }
770 }
771
772 return false
773}
774
775func (j *Module) hasSrcExt(ext string) bool {
776 return hasSrcExt(j.properties.Srcs, ext)
777}
778
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100779func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
780 var flags string
781
782 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
783 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
784 flags = "-Wmissing-permission-annotation -Werror"
785 }
786 }
787 return flags
788}
789
Jaewoong Jung26342642021-03-17 15:56:23 -0700790func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
791 aidlIncludeDirs android.Paths) (string, android.Paths) {
792
793 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
794 aidlIncludes = append(aidlIncludes,
795 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
796 aidlIncludes = append(aidlIncludes,
797 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
798
799 var flags []string
800 var deps android.Paths
801
802 flags = append(flags, j.deviceProperties.Aidl.Flags...)
803
804 if aidlPreprocess.Valid() {
805 flags = append(flags, "-p"+aidlPreprocess.String())
806 deps = append(deps, aidlPreprocess.Path())
807 } else if len(aidlIncludeDirs) > 0 {
808 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
809 }
810
811 if len(j.exportAidlIncludeDirs) > 0 {
812 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
813 }
814
815 if len(aidlIncludes) > 0 {
816 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
817 }
818
819 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
820 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
821 flags = append(flags, "-I"+src.String())
822 }
823
824 if Bool(j.deviceProperties.Aidl.Generate_traces) {
825 flags = append(flags, "-t")
826 }
827
828 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
829 flags = append(flags, "--transaction_names")
830 }
831
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100832 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
833 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
834 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
835 }
836
Jooyung Han07f70c02021-11-06 07:08:45 +0900837 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
838 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
839
Jaewoong Jung26342642021-03-17 15:56:23 -0700840 return strings.Join(flags, " "), deps
841}
842
843func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
844
845 var flags javaBuilderFlags
846
847 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900848 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700849
Cole Faust2b1536e2021-06-18 12:25:54 -0700850 epEnabled := j.properties.Errorprone.Enabled
851 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700852 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
853 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
854 }
855
856 errorProneFlags := []string{
857 "-Xplugin:ErrorProne",
858 "${config.ErrorProneChecks}",
859 }
860 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
861
Colin Cross8bf6cad2022-02-28 13:07:03 -0800862 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700863 "'" + strings.Join(errorProneFlags, " ") + "'"
864 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
865 }
866
867 // classpath
868 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
869 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700870 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700871 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
872 flags.processorPath = append(flags.processorPath, deps.processorPath...)
873 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
874
875 flags.processors = append(flags.processors, deps.processorClasses...)
876 flags.processors = android.FirstUniqueStrings(flags.processors)
877
878 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900879 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700880 // Give host-side tools a version of OpenJDK's standard libraries
881 // close to what they're targeting. As of Dec 2017, AOSP is only
882 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
883 //
884 // When building with OpenJDK 8, the following should have no
885 // effect since those jars would be available by default.
886 //
887 // When building with OpenJDK 9 but targeting a version < 1.8,
888 // putting them on the bootclasspath means that:
889 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
890 // b) references to existing APIs are not reinterpreted in an
891 // OpenJDK 9-specific way, eg. calls to subclasses of
892 // java.nio.Buffer as in http://b/70862583
893 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
894 flags.bootClasspath = append(flags.bootClasspath,
895 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
896 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
897 if Bool(j.properties.Use_tools_jar) {
898 flags.bootClasspath = append(flags.bootClasspath,
899 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
900 }
901 }
902
903 // systemModules
904 flags.systemModules = deps.systemModules
905
906 // aidl flags.
907 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
908
909 return flags
910}
911
912func (j *Module) collectJavacFlags(
913 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
914 // javac flags.
915 javacFlags := j.properties.Javacflags
916
917 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
918 // For non-host binaries, override the -g flag passed globally to remove
919 // local variable debug info to reduce disk and memory usage.
920 javacFlags = append(javacFlags, "-g:source,lines")
921 }
922 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
923
924 if flags.javaVersion.usesJavaModules() {
925 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
926
927 if j.properties.Patch_module != nil {
928 // Manually specify build directory in case it is not under the repo root.
929 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
930 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200931 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700932
933 // b/150878007
934 //
935 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
936 // execution root for --patch-module. If this javac command line is
937 // invoked within Bazel's execution root working directory, the top
938 // level directories (e.g. libcore/, tools/, frameworks/) are all
939 // symlinks. JDK9 javac does not traverse into symlinks, which causes
940 // --patch-module to fail source file lookups when invoked in the
941 // execution root.
942 //
943 // Short of patching javac or enumerating *all* directories as possible
944 // input dirs, manually add the top level dir of the source files to be
945 // compiled.
946 topLevelDirs := map[string]bool{}
947 for _, srcFilePath := range srcFiles {
948 srcFileParts := strings.Split(srcFilePath.String(), "/")
949 // Ignore source files that are already in the top level directory
950 // as well as generated files in the out directory. The out
951 // directory may be an absolute path, which means srcFileParts[0] is the
952 // empty string, so check that as well. Note that "out" in Bazel's execution
953 // root is *not* a symlink, which doesn't cause problems for --patch-modules
954 // anyway, so it's fine to not apply this workaround for generated
955 // source files.
956 if len(srcFileParts) > 1 &&
957 srcFileParts[0] != "" &&
958 srcFileParts[0] != "out" {
959 topLevelDirs[srcFileParts[0]] = true
960 }
961 }
962 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
963
964 classPath := flags.classpath.FormJavaClassPath("")
965 if classPath != "" {
966 patchPaths = append(patchPaths, classPath)
967 }
968 javacFlags = append(
969 javacFlags,
970 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
971 }
972 }
973
974 if len(javacFlags) > 0 {
975 // optimization.
976 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
977 flags.javacFlags = "$javacFlags"
978 }
979
980 return flags
981}
982
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400983func (j *Module) AddJSONData(d *map[string]interface{}) {
984 (&j.ModuleBase).AddJSONData(d)
985 (*d)["Java"] = map[string]interface{}{
986 "SourceExtensions": j.sourceExtensions,
987 }
988
989}
990
Jaewoong Jung26342642021-03-17 15:56:23 -0700991func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
992 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
993
994 deps := j.collectDeps(ctx)
995 flags := j.collectBuilderFlags(ctx, deps)
996
997 if flags.javaVersion.usesJavaModules() {
998 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
999 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001000
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001002 j.sourceExtensions = []string{}
1003 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1004 if hasSrcExt(srcFiles.Strings(), ext) {
1005 j.sourceExtensions = append(j.sourceExtensions, ext)
1006 }
1007 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001008 if hasSrcExt(srcFiles.Strings(), ".proto") {
1009 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1010 }
1011
1012 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1013 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1014 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1015 }
1016
1017 srcFiles = j.genSources(ctx, srcFiles, flags)
1018
1019 // Collect javac flags only after computing the full set of srcFiles to
1020 // ensure that the --patch-module lookup paths are complete.
1021 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1022
1023 srcJars := srcFiles.FilterByExt(".srcjar")
1024 srcJars = append(srcJars, deps.srcJars...)
1025 if aaptSrcJar != nil {
1026 srcJars = append(srcJars, aaptSrcJar)
1027 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001028 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001029
1030 if j.properties.Jarjar_rules != nil {
1031 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1032 }
1033
1034 jarName := ctx.ModuleName() + ".jar"
1035
1036 javaSrcFiles := srcFiles.FilterByExt(".java")
1037 var uniqueSrcFiles android.Paths
1038 set := make(map[string]bool)
1039 for _, v := range javaSrcFiles {
1040 if _, found := set[v.String()]; !found {
1041 set[v.String()] = true
1042 uniqueSrcFiles = append(uniqueSrcFiles, v)
1043 }
1044 }
1045
Colin Crossb5db4012022-03-28 17:12:39 -07001046 // We don't currently run annotation processors in turbine, which means we can't use turbine
1047 // generated header jars when an annotation processor that generates API is enabled. One
1048 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1049 // is used to run all of the annotation processors.
1050 disableTurbine := deps.disableTurbine
1051
Jaewoong Jung26342642021-03-17 15:56:23 -07001052 // Collect .java files for AIDEGen
1053 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1054
1055 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001056 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001057
1058 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001059 // When using kotlin sources turbine is used to generate annotation processor sources,
1060 // including for annotation processors that generate API, so we can use turbine for
1061 // java sources too.
1062 disableTurbine = false
1063
Jaewoong Jung26342642021-03-17 15:56:23 -07001064 // user defined kotlin flags.
1065 kotlincFlags := j.properties.Kotlincflags
1066 CheckKotlincFlags(ctx, kotlincFlags)
1067
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001068 // Workaround for KT-46512
1069 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001070
1071 // If there are kotlin files, compile them first but pass all the kotlin and java files
1072 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1073 // won't emit any classes for them.
1074 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1075 if ctx.Device() {
1076 kotlincFlags = append(kotlincFlags, "-no-jdk")
1077 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001078
1079 for _, plugin := range deps.kotlinPlugins {
1080 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1081 }
1082 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1083
Jaewoong Jung26342642021-03-17 15:56:23 -07001084 if len(kotlincFlags) > 0 {
1085 // optimization.
1086 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1087 flags.kotlincFlags += "$kotlincFlags"
1088 }
1089
1090 var kotlinSrcFiles android.Paths
1091 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1092 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1093
1094 // Collect .kt files for AIDEGen
1095 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1096 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1097
1098 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1099 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1100
1101 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1102 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1103
Isaac Chioua23d9942022-04-06 06:14:38 +00001104 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001105 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001106 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1107 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1108 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1109 srcJars = append(srcJars, kaptSrcJar)
1110 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001111 // Disable annotation processing in javac, it's already been handled by kapt
1112 flags.processorPath = nil
1113 flags.processors = nil
1114 }
1115
1116 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001117 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1118 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001119 if ctx.Failed() {
1120 return
1121 }
1122
Isaac Chioua23d9942022-04-06 06:14:38 +00001123 // Make javac rule depend on the kotlinc rule
1124 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1125
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001127 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1128
Jaewoong Jung26342642021-03-17 15:56:23 -07001129 // Jar kotlin classes into the final jar after javac
1130 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1131 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001132 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001133 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001134 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001135 } else {
1136 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001137 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 }
1139 }
1140
1141 jars := append(android.Paths(nil), kotlinJars...)
1142
1143 // Store the list of .java files that was passed to javac
1144 j.compiledJavaSrcs = uniqueSrcFiles
1145 j.compiledSrcJars = srcJars
1146
1147 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001148 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001149 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001150 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1151 enableSharding = true
1152 // Formerly, there was a check here that prevented annotation processors
1153 // from being used when sharding was enabled, as some annotation processors
1154 // do not function correctly in sharded environments. It was removed to
1155 // allow for the use of annotation processors that do function correctly
1156 // with sharding enabled. See: b/77284273.
1157 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001158 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001159 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 if ctx.Failed() {
1161 return
1162 }
1163 }
1164 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1165 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001166 if Bool(j.properties.Errorprone.Enabled) {
1167 // If error-prone is enabled, enable errorprone flags on the regular
1168 // build.
1169 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001170 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001171 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1172 // a new jar file just for compiling with the errorprone compiler to.
1173 // This is because we don't want to cause the java files to get completely
1174 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1175 // We also don't want to run this if errorprone is enabled by default for
1176 // this module, or else we could have duplicated errorprone messages.
1177 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001178 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001179
1180 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1181 "errorprone", "errorprone")
1182
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 extraJarDeps = append(extraJarDeps, errorprone)
1184 }
1185
1186 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001187 if headerJarFileWithoutDepsOrJarjar != nil {
1188 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1189 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001190 shardSize := int(*(j.properties.Javac_shard_size))
1191 var shardSrcs []android.Paths
1192 if len(uniqueSrcFiles) > 0 {
1193 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1194 for idx, shardSrc := range shardSrcs {
1195 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1196 nil, flags, extraJarDeps)
1197 jars = append(jars, classes)
1198 }
1199 }
1200 if len(srcJars) > 0 {
1201 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1202 nil, srcJars, flags, extraJarDeps)
1203 jars = append(jars, classes)
1204 }
1205 } else {
1206 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1207 jars = append(jars, classes)
1208 }
1209 if ctx.Failed() {
1210 return
1211 }
1212 }
1213
1214 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1215
1216 var includeSrcJar android.WritablePath
1217 if Bool(j.properties.Include_srcs) {
1218 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1219 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1220 }
1221
1222 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1223 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1224 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1225 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1226
1227 var resArgs []string
1228 var resDeps android.Paths
1229
1230 resArgs = append(resArgs, dirArgs...)
1231 resDeps = append(resDeps, dirDeps...)
1232
1233 resArgs = append(resArgs, fileArgs...)
1234 resDeps = append(resDeps, fileDeps...)
1235
1236 resArgs = append(resArgs, extraArgs...)
1237 resDeps = append(resDeps, extraDeps...)
1238
1239 if len(resArgs) > 0 {
1240 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1241 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1242 j.resourceJar = resourceJar
1243 if ctx.Failed() {
1244 return
1245 }
1246 }
1247
1248 var resourceJars android.Paths
1249 if j.resourceJar != nil {
1250 resourceJars = append(resourceJars, j.resourceJar)
1251 }
1252 if Bool(j.properties.Include_srcs) {
1253 resourceJars = append(resourceJars, includeSrcJar)
1254 }
1255 resourceJars = append(resourceJars, deps.staticResourceJars...)
1256
1257 if len(resourceJars) > 1 {
1258 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1259 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1260 false, nil, nil)
1261 j.resourceJar = combinedJar
1262 } else if len(resourceJars) == 1 {
1263 j.resourceJar = resourceJars[0]
1264 }
1265
1266 if len(deps.staticJars) > 0 {
1267 jars = append(jars, deps.staticJars...)
1268 }
1269
1270 manifest := j.overrideManifest
1271 if !manifest.Valid() && j.properties.Manifest != nil {
1272 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1273 }
1274
1275 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1276 if len(services) > 0 {
1277 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1278 var zipargs []string
1279 for _, file := range services {
1280 serviceFile := file.String()
1281 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1282 }
1283 rule := zip
1284 args := map[string]string{
1285 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1286 }
1287 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1288 rule = zipRE
1289 args["implicits"] = strings.Join(services.Strings(), ",")
1290 }
1291 ctx.Build(pctx, android.BuildParams{
1292 Rule: rule,
1293 Output: servicesJar,
1294 Implicits: services,
1295 Args: args,
1296 })
1297 jars = append(jars, servicesJar)
1298 }
1299
1300 // Combine the classes built from sources, any manifests, and any static libraries into
1301 // classes.jar. If there is only one input jar this step will be skipped.
1302 var outputFile android.OutputPath
1303
1304 if len(jars) == 1 && !manifest.Valid() {
1305 // Optimization: skip the combine step as there is nothing to do
1306 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1307 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1308 // any if len(jars) == 1.
1309
1310 // Transform the single path to the jar into an OutputPath as that is required by the following
1311 // code.
1312 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1313 // The path contains an embedded OutputPath so reuse that.
1314 outputFile = moduleOutPath.OutputPath
1315 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1316 // The path is an OutputPath so reuse it directly.
1317 outputFile = outputPath
1318 } else {
1319 // The file is not in the out directory so create an OutputPath into which it can be copied
1320 // and which the following code can use to refer to it.
1321 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1322 ctx.Build(pctx, android.BuildParams{
1323 Rule: android.Cp,
1324 Input: jars[0],
1325 Output: combinedJar,
1326 })
1327 outputFile = combinedJar.OutputPath
1328 }
1329 } else {
1330 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1331 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1332 false, nil, nil)
1333 outputFile = combinedJar.OutputPath
1334 }
1335
1336 // jarjar implementation jar if necessary
1337 if j.expandJarjarRules != nil {
1338 // Transform classes.jar into classes-jarjar.jar
1339 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1340 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1341 outputFile = jarjarFile
1342
1343 // jarjar resource jar if necessary
1344 if j.resourceJar != nil {
1345 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1346 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1347 j.resourceJar = resourceJarJarFile
1348 }
1349
1350 if ctx.Failed() {
1351 return
1352 }
1353 }
1354
1355 // Check package restrictions if necessary.
1356 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001357 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001358 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001359
1360 // Create a rule to copy the output jar to another path and add a validate dependency that
1361 // will check that the jar only contains the permitted packages. The new location will become
1362 // the output file of this module.
1363 inputFile := outputFile
1364 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1365 ctx.Build(pctx, android.BuildParams{
1366 Rule: android.Cp,
1367 Input: inputFile,
1368 Output: outputFile,
1369 // Make sure that any dependency on the output file will cause ninja to run the package check
1370 // rule.
1371 Validation: pkgckFile,
1372 })
1373
1374 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001375 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001376
1377 if ctx.Failed() {
1378 return
1379 }
1380 }
1381
1382 j.implementationJarFile = outputFile
1383 if j.headerJarFile == nil {
1384 j.headerJarFile = j.implementationJarFile
1385 }
1386
1387 if j.shouldInstrumentInApex(ctx) {
1388 j.properties.Instrument = true
1389 }
1390
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001391 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1392 specs := j.jacocoModuleToZipCommand(ctx)
1393 if ctx.Failed() {
1394 return
1395 }
1396
Jaewoong Jung26342642021-03-17 15:56:23 -07001397 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001398 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001399 }
1400
1401 // merge implementation jar with resources if necessary
1402 implementationAndResourcesJar := outputFile
1403 if j.resourceJar != nil {
1404 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1405 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1406 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1407 false, nil, nil)
1408 implementationAndResourcesJar = combinedJar
1409 }
1410
1411 j.implementationAndResourcesJar = implementationAndResourcesJar
1412
1413 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1414 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1415 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1416 if j.dexProperties.Compile_dex == nil {
1417 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1418 }
1419 if j.deviceProperties.Hostdex == nil {
1420 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1421 }
1422 }
1423
1424 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1425 if j.hasCode(ctx) {
1426 if j.shouldInstrumentStatic(ctx) {
1427 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1428 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1429 }
1430 // Dex compilation
1431 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001432 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001433 if ctx.Failed() {
1434 return
1435 }
1436
Jaewoong Jung26342642021-03-17 15:56:23 -07001437 // merge dex jar with resources if necessary
1438 if j.resourceJar != nil {
1439 jars := android.Paths{dexOutputFile, j.resourceJar}
1440 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1441 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1442 false, nil, nil)
1443 if *j.dexProperties.Uncompress_dex {
1444 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1445 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1446 dexOutputFile = combinedAlignedJar
1447 } else {
1448 dexOutputFile = combinedJar
1449 }
1450 }
1451
Paul Duffin4de94502021-05-16 05:21:16 +01001452 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001453
1454 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001455
1456 // Encode hidden API flags in dex file, if needed.
1457 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1458
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001459 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001460
1461 // Dexpreopting
1462 j.dexpreopt(ctx, dexOutputFile)
1463
1464 outputFile = dexOutputFile
1465 } else {
1466 // There is no code to compile into a dex jar, make sure the resources are propagated
1467 // to the APK if this is an app.
1468 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001469 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001470 }
1471
1472 if ctx.Failed() {
1473 return
1474 }
1475 } else {
1476 outputFile = implementationAndResourcesJar
1477 }
1478
1479 if ctx.Device() {
Cole Faust8b7f6272022-04-20 18:02:42 -07001480 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001481 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Faust8b7f6272022-04-20 18:02:42 -07001482 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001483 } else {
Cole Faust8b7f6272022-04-20 18:02:42 -07001484 // When running metalava, we pass --version-codename. When that value
1485 // is not REL, metalava will add 1 to the --current-version argument.
1486 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1487 // branch) and the codename is REL, except potentially on the most
1488 // recent non-master branch. On that branch, it goes through two other
1489 // phases before it gets to the phase previously described:
1490 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1491 // is not rel. This happens for most of the internal branch's life
1492 // while the branch has been cut but is still under active development.
1493 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1494 // REL. This happens briefly during the release process. During this
1495 // state the code to add --current-version is commented out, and then
1496 // that commenting out is reverted after the codename is set to REL.
1497 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1498 // prior version and the codename is always non-REL.
1499 //
1500 // We need to add one here to match metalava adding 1. Technically
1501 // this means that in the state described in the second bullet point
1502 // above, this number is 1 higher than it should be.
1503 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 }
1505 }
1506
1507 j.linter.name = ctx.ModuleName()
1508 j.linter.srcs = srcFiles
1509 j.linter.srcJars = srcJars
1510 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1511 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001512 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1513 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1514 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001515 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001516 j.linter.javaLanguageLevel = flags.javaVersion.String()
1517 j.linter.kotlinLanguageLevel = "1.3"
1518 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1519 j.linter.buildModuleReportZip = true
1520 }
1521 j.linter.lint(ctx)
1522 }
1523
1524 ctx.CheckbuildFile(outputFile)
1525
1526 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1527 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1528 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1529 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1530 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1531 AidlIncludeDirs: j.exportAidlIncludeDirs,
1532 SrcJarArgs: j.srcJarArgs,
1533 SrcJarDeps: j.srcJarDeps,
1534 ExportedPlugins: j.exportedPluginJars,
1535 ExportedPluginClasses: j.exportedPluginClasses,
1536 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1537 JacocoReportClassesFile: j.jacocoReportClassesFile,
1538 })
1539
1540 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1541 j.outputFile = outputFile.WithoutRel()
1542}
1543
Colin Crossa1ff7c62021-09-17 14:11:52 -07001544func (j *Module) useCompose() bool {
1545 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1546}
1547
Cole Faust75fffb12021-06-13 15:23:16 -07001548// Returns a copy of the supplied flags, but with all the errorprone-related
1549// fields copied to the regular build's fields.
1550func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1551 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1552
1553 if len(flags.errorProneExtraJavacFlags) > 0 {
1554 if len(flags.javacFlags) > 0 {
1555 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1556 } else {
1557 flags.javacFlags = flags.errorProneExtraJavacFlags
1558 }
1559 }
1560 return flags
1561}
1562
Jaewoong Jung26342642021-03-17 15:56:23 -07001563func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1564 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1565
1566 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1567 if idx >= 0 {
1568 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1569 jarName += strconv.Itoa(idx)
1570 }
1571
1572 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1573 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1574
1575 if ctx.Config().EmitXrefRules() {
1576 extractionFile := android.PathForModuleOut(ctx, kzipName)
1577 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1578 j.kytheFiles = append(j.kytheFiles, extractionFile)
1579 }
1580
1581 return classes
1582}
1583
1584// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1585// since some of these flags may be used internally.
1586func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1587 for _, flag := range flags {
1588 flag = strings.TrimSpace(flag)
1589
1590 if !strings.HasPrefix(flag, "-") {
1591 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1592 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1593 ctx.PropertyErrorf("kotlincflags",
1594 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1595 } else if inList(flag, config.KotlincIllegalFlags) {
1596 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1597 } else if flag == "-include-runtime" {
1598 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1599 } else {
1600 args := strings.Split(flag, " ")
1601 if args[0] == "-kotlin-home" {
1602 ctx.PropertyErrorf("kotlincflags",
1603 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1604 }
1605 }
1606 }
1607}
1608
1609func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1610 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001611 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001612
1613 var jars android.Paths
1614 if len(srcFiles) > 0 || len(srcJars) > 0 {
1615 // Compile java sources into turbine.jar.
1616 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1617 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1618 if ctx.Failed() {
1619 return nil, nil
1620 }
1621 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001622 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001623 }
1624
1625 jars = append(jars, extraJars...)
1626
1627 // Combine any static header libraries into classes-header.jar. If there is only
1628 // one input jar this step will be skipped.
1629 jars = append(jars, deps.staticHeaderJars...)
1630
1631 // we cannot skip the combine step for now if there is only one jar
1632 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1633 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1634 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1635 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001636 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001637
1638 if j.expandJarjarRules != nil {
1639 // Transform classes.jar into classes-jarjar.jar
1640 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001641 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1642 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001643 if ctx.Failed() {
1644 return nil, nil
1645 }
1646 }
1647
Colin Cross3d56ed52021-11-18 22:23:12 -08001648 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001649}
1650
1651func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001652 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001653
1654 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1655 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1656
1657 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1658
1659 j.jacocoReportClassesFile = jacocoReportClassesFile
1660
1661 return instrumentedJar
1662}
1663
1664func (j *Module) HeaderJars() android.Paths {
1665 if j.headerJarFile == nil {
1666 return nil
1667 }
1668 return android.Paths{j.headerJarFile}
1669}
1670
1671func (j *Module) ImplementationJars() android.Paths {
1672 if j.implementationJarFile == nil {
1673 return nil
1674 }
1675 return android.Paths{j.implementationJarFile}
1676}
1677
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001678func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001679 return j.dexJarFile
1680}
1681
1682func (j *Module) DexJarInstallPath() android.Path {
1683 return j.installFile
1684}
1685
1686func (j *Module) ImplementationAndResourcesJars() android.Paths {
1687 if j.implementationAndResourcesJar == nil {
1688 return nil
1689 }
1690 return android.Paths{j.implementationAndResourcesJar}
1691}
1692
1693func (j *Module) AidlIncludeDirs() android.Paths {
1694 // exportAidlIncludeDirs is type android.Paths already
1695 return j.exportAidlIncludeDirs
1696}
1697
1698func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1699 return j.classLoaderContexts
1700}
1701
1702// Collect information for opening IDE project files in java/jdeps.go.
1703func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1704 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1705 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1706 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1707 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1708 if j.expandJarjarRules != nil {
1709 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1710 }
1711 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001712 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1713 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001714}
1715
1716func (j *Module) CompilerDeps() []string {
1717 jdeps := []string{}
1718 jdeps = append(jdeps, j.properties.Libs...)
1719 jdeps = append(jdeps, j.properties.Static_libs...)
1720 return jdeps
1721}
1722
1723func (j *Module) hasCode(ctx android.ModuleContext) bool {
1724 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1725 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1726}
1727
1728// Implements android.ApexModule
1729func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1730 return j.depIsInSameApex(ctx, dep)
1731}
1732
1733// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001734func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001735 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001736 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001737 return fmt.Errorf("min_sdk_version is not specified")
1738 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001739 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001740 return nil
1741 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001742 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1743 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001744 }
1745 return nil
1746}
1747
1748func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001749 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001750}
1751
Jaewoong Jung26342642021-03-17 15:56:23 -07001752func (j *Module) JacocoReportClassesFile() android.Path {
1753 return j.jacocoReportClassesFile
1754}
1755
1756func (j *Module) IsInstallable() bool {
1757 return Bool(j.properties.Installable)
1758}
1759
1760type sdkLinkType int
1761
1762const (
1763 // TODO(jiyong) rename these for better readability. Make the allowed
1764 // and disallowed link types explicit
1765 // order is important here. See rank()
1766 javaCore sdkLinkType = iota
1767 javaSdk
1768 javaSystem
1769 javaModule
1770 javaSystemServer
1771 javaPlatform
1772)
1773
1774func (lt sdkLinkType) String() string {
1775 switch lt {
1776 case javaCore:
1777 return "core Java API"
1778 case javaSdk:
1779 return "Android API"
1780 case javaSystem:
1781 return "system API"
1782 case javaModule:
1783 return "module API"
1784 case javaSystemServer:
1785 return "system server API"
1786 case javaPlatform:
1787 return "private API"
1788 default:
1789 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1790 }
1791}
1792
1793// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1794// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1795// can't statically depend on modules that use Platform API.
1796func (lt sdkLinkType) rank() int {
1797 return int(lt)
1798}
1799
1800type moduleWithSdkDep interface {
1801 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001802 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001803}
1804
Jiyong Park92315372021-04-02 08:45:46 +09001805func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001806 switch name {
1807 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1808 "stub-annotations", "private-stub-annotations-jar",
1809 "core-lambda-stubs", "core-generated-annotation-stubs":
1810 return javaCore, true
1811 case "android_stubs_current":
1812 return javaSdk, true
1813 case "android_system_stubs_current":
1814 return javaSystem, true
1815 case "android_module_lib_stubs_current":
1816 return javaModule, true
1817 case "android_system_server_stubs_current":
1818 return javaSystemServer, true
1819 case "android_test_stubs_current":
1820 return javaSystem, true
1821 }
1822
1823 if stub, linkType := moduleStubLinkType(name); stub {
1824 return linkType, true
1825 }
1826
Jiyong Park92315372021-04-02 08:45:46 +09001827 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001828 switch ver.Kind {
1829 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001830 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001831 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001832 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001833 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001834 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001835 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001836 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001837 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001838 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001839 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001840 return javaPlatform, false
1841 }
1842
Jiyong Parkf1691d22021-03-29 20:11:58 +09001843 if !ver.Valid() {
1844 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001845 }
1846 return javaSdk, false
1847}
1848
1849// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1850// this module's. See the comment on rank() for details and an example.
1851func (j *Module) checkSdkLinkType(
1852 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1853 if ctx.Host() {
1854 return
1855 }
1856
Jiyong Park92315372021-04-02 08:45:46 +09001857 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001858 if stubs {
1859 return
1860 }
Jiyong Park92315372021-04-02 08:45:46 +09001861 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001862
1863 if myLinkType.rank() < depLinkType.rank() {
1864 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1865 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1866 "property of the source or target module so that target module is built "+
1867 "with the same or smaller API set when compared to the source.",
1868 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1869 }
1870}
1871
1872func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1873 var deps deps
1874
1875 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001876 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001877 if sdkDep.invalidVersion {
1878 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1879 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1880 } else if sdkDep.useFiles {
1881 // sdkDep.jar is actually equivalent to turbine header.jar.
1882 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001883 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001884 deps.aidlPreprocess = sdkDep.aidl
1885 } else {
1886 deps.aidlPreprocess = sdkDep.aidl
1887 }
1888 }
1889
Jiyong Park92315372021-04-02 08:45:46 +09001890 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001891
1892 ctx.VisitDirectDeps(func(module android.Module) {
1893 otherName := ctx.OtherModuleName(module)
1894 tag := ctx.OtherModuleDependencyTag(module)
1895
1896 if IsJniDepTag(tag) {
1897 // Handled by AndroidApp.collectAppDeps
1898 return
1899 }
1900 if tag == certificateTag {
1901 // Handled by AndroidApp.collectAppDeps
1902 return
1903 }
1904
1905 if dep, ok := module.(SdkLibraryDependency); ok {
1906 switch tag {
1907 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001908 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1909 deps.classpath = append(deps.classpath, depHeaderJars...)
1910 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001911 case staticLibTag:
1912 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1913 }
1914 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1915 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1916 if sdkLinkType != javaPlatform &&
1917 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1918 // dep is a sysprop implementation library, but this module is not linking against
1919 // the platform, so it gets the sysprop public stubs library instead. Replace
1920 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1921 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1922 dep = syspropDep.JavaInfo
1923 }
1924 switch tag {
1925 case bootClasspathTag:
1926 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1927 case libTag, instrumentationForTag:
1928 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001929 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001930 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1931 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1932 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1933 case java9LibTag:
1934 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1935 case staticLibTag:
1936 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1937 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1938 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1939 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1940 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1941 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1942 // Turbine doesn't run annotation processors, so any module that uses an
1943 // annotation processor that generates API is incompatible with the turbine
1944 // optimization.
1945 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1946 case pluginTag:
1947 if plugin, ok := module.(*Plugin); ok {
1948 if plugin.pluginProperties.Processor_class != nil {
1949 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1950 } else {
1951 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1952 }
1953 // Turbine doesn't run annotation processors, so any module that uses an
1954 // annotation processor that generates API is incompatible with the turbine
1955 // optimization.
1956 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1957 } else {
1958 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1959 }
1960 case errorpronePluginTag:
1961 if _, ok := module.(*Plugin); ok {
1962 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1963 } else {
1964 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1965 }
1966 case exportedPluginTag:
1967 if plugin, ok := module.(*Plugin); ok {
1968 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1969 if plugin.pluginProperties.Processor_class != nil {
1970 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1971 }
1972 // Turbine doesn't run annotation processors, so any module that uses an
1973 // annotation processor that generates API is incompatible with the turbine
1974 // optimization.
1975 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1976 } else {
1977 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1978 }
1979 case kotlinStdlibTag:
1980 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1981 case kotlinAnnotationsTag:
1982 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001983 case kotlinPluginTag:
1984 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001985 case syspropPublicStubDepTag:
1986 // This is a sysprop implementation library, forward the JavaInfoProvider from
1987 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1988 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1989 JavaInfo: dep,
1990 })
1991 }
1992 } else if dep, ok := module.(android.SourceFileProducer); ok {
1993 switch tag {
1994 case libTag:
1995 checkProducesJars(ctx, dep)
1996 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001997 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001998 case staticLibTag:
1999 checkProducesJars(ctx, dep)
2000 deps.classpath = append(deps.classpath, dep.Srcs()...)
2001 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2002 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2003 }
2004 } else {
2005 switch tag {
2006 case bootClasspathTag:
2007 // If a system modules dependency has been added to the bootclasspath
2008 // then add its libs to the bootclasspath.
2009 sm := module.(SystemModulesProvider)
2010 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2011
2012 case systemModulesTag:
2013 if deps.systemModules != nil {
2014 panic("Found two system module dependencies")
2015 }
2016 sm := module.(SystemModulesProvider)
2017 outputDir, outputDeps := sm.OutputDirAndDeps()
2018 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002019
2020 case instrumentationForTag:
2021 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 -07002022 }
2023 }
2024
2025 addCLCFromDep(ctx, module, j.classLoaderContexts)
2026 })
2027
2028 return deps
2029}
2030
2031func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2032 deps.processorPath = append(deps.processorPath, pluginJars...)
2033 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2034}
2035
2036// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2037// this interface.
2038type ProvidesUsesLib interface {
2039 ProvidesUsesLib() *string
2040}
2041
2042func (j *Module) ProvidesUsesLib() *string {
2043 return j.usesLibraryProperties.Provides_uses_lib
2044}
satayev1c564cc2021-05-25 19:50:30 +01002045
2046type ModuleWithStem interface {
2047 Stem() string
2048}
2049
2050var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002051
2052func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2053 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002054 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002055 if lib, ok := ctx.Module().(*Library); ok {
2056 javaLibraryBp2Build(ctx, lib)
2057 }
2058 case "java_binary_host":
2059 if binary, ok := ctx.Module().(*Binary); ok {
2060 javaBinaryHostBp2Build(ctx, binary)
2061 }
2062 }
Wei Libafb6d62021-12-10 03:14:59 -08002063}