blob: 58c16492df065a164cbd75298b8b790d08592dc4 [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
Sam Delmericocfd0caa2022-08-31 15:57:52 -0400172 // If true, then jacocoagent is automatically added as a libs dependency so that
173 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700174 Instrument bool `blueprint:"mutated"`
Paul Duffin39531532022-05-03 00:28:40 +0000175 // If true, then the module supports statically including the jacocoagent
176 // into the library.
177 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700178
179 // List of files to include in the META-INF/services folder of the resulting jar.
180 Services []string `android:"path,arch_variant"`
181
182 // If true, package the kotlin stdlib into the jar. Defaults to true.
183 Static_kotlin_stdlib *bool `android:"arch_variant"`
184
185 // A list of java_library instances that provide additional hiddenapi annotations for the library.
186 Hiddenapi_additional_annotations []string
187}
188
189// Properties that are specific to device modules. Host module factories should not add these when
190// constructing a new module.
191type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000192 // If not blank, set to the version of the sdk to compile against.
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000193 // Defaults to private.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000194 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000195 // 1) numerical API level, "current", "none", or "core_platform"
196 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
197 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
198 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700199 Sdk_version *string
200
201 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000202 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700203 Min_sdk_version *string
204
satayev0a420e72021-11-29 17:25:52 +0000205 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
206 // Defaults to empty string "". See sdk_version for possible values.
207 Max_sdk_version *string
208
Jaewoong Jung26342642021-03-17 15:56:23 -0700209 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000210 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 Target_sdk_version *string
212
213 // Whether to compile against the platform APIs instead of an SDK.
214 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000215 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700216 Platform_apis *bool
217
218 Aidl struct {
219 // Top level directories to pass to aidl tool
220 Include_dirs []string
221
222 // Directories rooted at the Android.bp file to pass to aidl tool
223 Local_include_dirs []string
224
225 // directories that should be added as include directories for any aidl sources of modules
226 // that depend on this module, as well as to aidl for this module.
227 Export_include_dirs []string
228
229 // whether to generate traces (for systrace) for this interface
230 Generate_traces *bool
231
232 // whether to generate Binder#GetTransaction name method.
233 Generate_get_transaction_name *bool
234
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100235 // whether all interfaces should be annotated with required permissions.
236 Enforce_permissions *bool
237
238 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
239 Enforce_permissions_exceptions []string `android:"path"`
240
Jaewoong Jung26342642021-03-17 15:56:23 -0700241 // list of flags that will be passed to the AIDL compiler
242 Flags []string
243 }
244
245 // If true, export a copy of the module as a -hostdex module for host testing.
246 Hostdex *bool
247
248 Target struct {
249 Hostdex struct {
250 // Additional required dependencies to add to -hostdex modules.
251 Required []string
252 }
253 }
254
255 // When targeting 1.9 and above, override the modules to use with --system,
256 // otherwise provides defaults libraries to add to the bootclasspath.
257 System_modules *string
258
Jaewoong Jung26342642021-03-17 15:56:23 -0700259 IsSDKLibrary bool `blueprint:"mutated"`
260
261 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
262 // Defaults to false.
263 V4_signature *bool
264
265 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
266 // public stubs library.
267 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffinb5e3c982022-07-27 16:27:42 +0000268
269 HiddenAPIPackageProperties
270 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700271}
272
Jooyung Han01d80d82022-01-08 12:16:32 +0900273// Device properties that can be overridden by overriding module (e.g. override_android_app)
274type OverridableDeviceProperties struct {
275 // set the name of the output. If not set, `name` is used.
276 // To override a module with this property set, overriding module might need to set this as well.
277 // Otherwise, both the overridden and the overriding modules will have the same output name, which
278 // can cause the duplicate output error.
279 Stem *string
280}
281
Jaewoong Jung26342642021-03-17 15:56:23 -0700282// Functionality common to Module and Import
283//
284// It is embedded in Module so its functionality can be used by methods in Module
285// but it is currently only initialized by Import and Library.
286type embeddableInModuleAndImport struct {
287
288 // Functionality related to this being used as a component of a java_sdk_library.
289 EmbeddableSdkLibraryComponent
290}
291
Paul Duffin71b33cc2021-06-23 11:39:47 +0100292func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
293 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700294}
295
296// Module/Import's DepIsInSameApex(...) delegates to this method.
297//
298// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
299// the one provided by ApexModuleBase.
300func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
301 // dependencies other than the static linkage are all considered crossing APEX boundary
302 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
303 return true
304 }
305 return false
306}
307
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100308// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
309// or an invalid path describing the reason it is invalid.
310//
311// It is unset if a dex jar isn't applicable, i.e. no build rule has been
312// requested to create one.
313//
314// If a dex jar has been requested to be built then it is set, and it may be
315// either a valid android.Path, or invalid with a reason message. The latter
316// happens if the source that should produce the dex file isn't able to.
317//
318// E.g. it is invalid with a reason message if there is a prebuilt APEX that
319// could produce the dex jar through a deapexer module, but the APEX isn't
320// installable so doing so wouldn't be safe.
321type OptionalDexJarPath struct {
322 isSet bool
323 path android.OptionalPath
324}
325
326// IsSet returns true if a path has been set, either invalid or valid.
327func (o OptionalDexJarPath) IsSet() bool {
328 return o.isSet
329}
330
331// Valid returns true if there is a path that is valid.
332func (o OptionalDexJarPath) Valid() bool {
333 return o.isSet && o.path.Valid()
334}
335
336// Path returns the valid path, or panics if it's either not set or is invalid.
337func (o OptionalDexJarPath) Path() android.Path {
338 if !o.isSet {
339 panic("path isn't set")
340 }
341 return o.path.Path()
342}
343
344// PathOrNil returns the path if it's set and valid, or else nil.
345func (o OptionalDexJarPath) PathOrNil() android.Path {
346 if o.Valid() {
347 return o.Path()
348 }
349 return nil
350}
351
352// InvalidReason returns the reason for an invalid path, which is never "". It
353// returns "" for an unset or valid path.
354func (o OptionalDexJarPath) InvalidReason() string {
355 if !o.isSet {
356 return ""
357 }
358 return o.path.InvalidReason()
359}
360
361func (o OptionalDexJarPath) String() string {
362 if !o.isSet {
363 return "<unset>"
364 }
365 return o.path.String()
366}
367
368// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
369func makeUnsetDexJarPath() OptionalDexJarPath {
370 return OptionalDexJarPath{isSet: false}
371}
372
373// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
374// the given OptionalPath, which may be valid or invalid.
375func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
376 return OptionalDexJarPath{isSet: true, path: path}
377}
378
379// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
380// valid given path. It returns an unset OptionalDexJarPath if the given path is
381// nil.
382func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
383 if path == nil {
384 return makeUnsetDexJarPath()
385 }
386 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
387}
388
Jaewoong Jung26342642021-03-17 15:56:23 -0700389// Module contains the properties and members used by all java module types
390type Module struct {
391 android.ModuleBase
392 android.DefaultableModuleBase
393 android.ApexModuleBase
394 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800395 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700396
397 // Functionality common to Module and Import.
398 embeddableInModuleAndImport
399
400 properties CommonProperties
401 protoProperties android.ProtoProperties
402 deviceProperties DeviceProperties
403
Jooyung Han01d80d82022-01-08 12:16:32 +0900404 overridableDeviceProperties OverridableDeviceProperties
405
Jaewoong Jung26342642021-03-17 15:56:23 -0700406 // jar file containing header classes including static library dependencies, suitable for
407 // inserting into the bootclasspath/classpath of another compile
408 headerJarFile android.Path
409
410 // jar file containing implementation classes including static library dependencies but no
411 // resources
412 implementationJarFile android.Path
413
414 // jar file containing only resources including from static library dependencies
415 resourceJar android.Path
416
417 // args and dependencies to package source files into a srcjar
418 srcJarArgs []string
419 srcJarDeps android.Paths
420
421 // jar file containing implementation classes and resources including static library
422 // dependencies
423 implementationAndResourcesJar android.Path
424
425 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100426 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700427
428 // output file containing uninstrumented classes that will be instrumented by jacoco
429 jacocoReportClassesFile android.Path
430
431 // output file of the module, which may be a classes jar or a dex jar
432 outputFile android.Path
433 extraOutputFiles android.Paths
434
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100435 exportAidlIncludeDirs android.Paths
436 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700437
438 logtagsSrcs android.Paths
439
440 // installed file for binary dependency
441 installFile android.Path
442
Colin Cross3108ce12021-11-10 14:38:50 -0800443 // installed file for hostdex copy
444 hostdexInstallFile android.InstallPath
445
Jaewoong Jung26342642021-03-17 15:56:23 -0700446 // list of .java files and srcjars that was passed to javac
447 compiledJavaSrcs android.Paths
448 compiledSrcJars android.Paths
449
450 // manifest file to use instead of properties.Manifest
451 overrideManifest android.OptionalPath
452
453 // map of SDK version to class loader context
454 classLoaderContexts dexpreopt.ClassLoaderContextMap
455
456 // list of plugins that this java module is exporting
457 exportedPluginJars android.Paths
458
459 // list of plugins that this java module is exporting
460 exportedPluginClasses []string
461
462 // if true, the exported plugins generate API and require disabling turbine.
463 exportedDisableTurbine bool
464
465 // list of source files, collected from srcFiles with unique java and all kt files,
466 // will be used by android.IDEInfo struct
467 expandIDEInfoCompiledSrcs []string
468
469 // expanded Jarjar_rules
470 expandJarjarRules android.Path
471
Jaewoong Jung26342642021-03-17 15:56:23 -0700472 // Extra files generated by the module type to be added as java resources.
473 extraResources android.Paths
474
475 hiddenAPI
476 dexer
477 dexpreopter
478 usesLibrary
479 linter
480
481 // list of the xref extraction files
482 kytheFiles android.Paths
483
484 // Collect the module directory for IDE info in java/jdeps.go.
485 modulePaths []string
486
487 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900488
489 sdkVersion android.SdkSpec
490 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000491 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400492
493 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700494}
495
Jiyong Park92315372021-04-02 08:45:46 +0900496func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
497 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900498 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700499 return nil
500 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900501 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000502 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700503 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
504 } else {
505 // Treat stable core platform as stable.
506 return nil
507 }
508 } else {
509 return fmt.Errorf("non stable SDK %v", sdkVersion)
510 }
511}
512
513// checkSdkVersions enforces restrictions around SDK dependencies.
514func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
515 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900516 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900517 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700518 ctx.PropertyErrorf("sdk_version",
519 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
520 }
521 }
522 }
523
524 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
525 // See rank() for details.
526 ctx.VisitDirectDeps(func(module android.Module) {
527 tag := ctx.OtherModuleDependencyTag(module)
528 switch module.(type) {
529 // TODO(satayev): cover other types as well, e.g. imports
530 case *Library, *AndroidLibrary:
531 switch tag {
532 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
533 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
534 }
535 }
536 })
537}
538
539func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900540 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700541 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900542 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700543 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000544 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 -0700545 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000546 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 -0700547 }
548
549 }
550}
551
552func (j *Module) addHostProperties() {
553 j.AddProperties(
554 &j.properties,
555 &j.protoProperties,
556 &j.usesLibraryProperties,
557 )
558}
559
560func (j *Module) addHostAndDeviceProperties() {
561 j.addHostProperties()
562 j.AddProperties(
563 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900564 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700565 &j.dexer.dexProperties,
566 &j.dexpreoptProperties,
567 &j.linter.properties,
568 )
569}
570
Paul Duffinb5e3c982022-07-27 16:27:42 +0000571// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
572// makes it available through the hiddenAPIPropertyInfoProvider.
573func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
574 hiddenAPIInfo := newHiddenAPIPropertyInfo()
575
576 // Populate with flag file paths from the properties.
577 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
578
579 // Populate with package rules from the properties.
580 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
581
582 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
583}
584
Jaewoong Jung26342642021-03-17 15:56:23 -0700585func (j *Module) OutputFiles(tag string) (android.Paths, error) {
586 switch tag {
587 case "":
588 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
589 case android.DefaultDistTag:
590 return android.Paths{j.outputFile}, nil
591 case ".jar":
592 return android.Paths{j.implementationAndResourcesJar}, nil
593 case ".proguard_map":
594 if j.dexer.proguardDictionary.Valid() {
595 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
596 }
597 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
598 default:
599 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
600 }
601}
602
603var _ android.OutputFileProducer = (*Module)(nil)
604
605func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
606 initJavaModule(module, hod, false)
607}
608
609func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
610 initJavaModule(module, hod, true)
611}
612
613func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
614 multilib := android.MultilibCommon
615 if multiTargets {
616 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
617 } else {
618 android.InitAndroidArchModule(module, hod, multilib)
619 }
620 android.InitDefaultableModule(module)
621}
622
623func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
624 return j.properties.Instrument &&
625 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
626 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
627}
628
629func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin39531532022-05-03 00:28:40 +0000630 return j.properties.Supports_static_instrumentation &&
631 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700632 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
633 ctx.Config().UnbundledBuild())
634}
635
636func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
637 // Force enable the instrumentation for java code that is built for APEXes ...
638 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
639 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
640 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
641 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
642 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
643 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
644 return true
645 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
646 return true
647 }
648 }
649 return false
650}
651
Jiyong Park92315372021-04-02 08:45:46 +0900652func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
653 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700654}
655
Jiyong Parkf1691d22021-03-29 20:11:58 +0900656func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700657 return proptools.String(j.deviceProperties.System_modules)
658}
659
Jiyong Park92315372021-04-02 08:45:46 +0900660func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700661 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900662 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700663 }
Jiyong Park92315372021-04-02 08:45:46 +0900664 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700665}
666
satayev0a420e72021-11-29 17:25:52 +0000667func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
668 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
669 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
670 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
671 return android.SdkSpecFrom(ctx, maxSdkVersion)
672}
673
Jiyong Parkf1691d22021-03-29 20:11:58 +0900674func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900675 return j.minSdkVersion.Raw
676}
677
678func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
679 if j.deviceProperties.Target_sdk_version != nil {
680 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
681 }
682 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700683}
684
685func (j *Module) AvailableFor(what string) bool {
686 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
687 // Exception: for hostdex: true libraries, the platform variant is created
688 // even if it's not marked as available to platform. In that case, the platform
689 // variant is used only for the hostdex and not installed to the device.
690 return true
691 }
692 return j.ApexModuleBase.AvailableFor(what)
693}
694
695func (j *Module) deps(ctx android.BottomUpMutatorContext) {
696 if ctx.Device() {
697 j.linter.deps(ctx)
698
Jiyong Parkf1691d22021-03-29 20:11:58 +0900699 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700700
701 if j.deviceProperties.SyspropPublicStub != "" {
702 // This is a sysprop implementation library that has a corresponding sysprop public
703 // stubs library, and a dependency on it so that dependencies on the implementation can
704 // be forwarded to the public stubs library when necessary.
705 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
706 }
707 }
708
709 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
710 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
711
712 // Add dependency on libraries that provide additional hidden api annotations.
713 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
714
715 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
716 // Require java_sdk_library at inter-partition java dependency to ensure stable
717 // interface between partitions. If inter-partition java_library dependency is detected,
718 // raise build error because java_library doesn't have a stable interface.
719 //
720 // Inputs:
721 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
722 // if true, enable enforcement
723 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
724 // exception list of java_library names to allow inter-partition dependency
725 for idx := range j.properties.Libs {
726 if libDeps[idx] == nil {
727 continue
728 }
729
730 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
731 // java_sdk_library is always allowed at inter-partition dependency.
732 // So, skip check.
733 if _, ok := javaDep.(*SdkLibrary); ok {
734 continue
735 }
736
737 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
738 }
739 }
740 }
741
742 // For library dependencies that are component libraries (like stubs), add the implementation
743 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
744 for _, dep := range libDeps {
745 if dep != nil {
746 if component, ok := dep.(SdkLibraryComponentDependency); ok {
747 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100748 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100749 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
750 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100751 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700752 }
753 }
754 }
755 }
756
757 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
758 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
759 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
760
761 android.ProtoDeps(ctx, &j.protoProperties)
762 if j.hasSrcExt(".proto") {
763 protoDeps(ctx, &j.protoProperties)
764 }
765
766 if j.hasSrcExt(".kt") {
767 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
768 // Kotlin files
769 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
770 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
771 if len(j.properties.Plugins) > 0 {
772 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
773 }
774 }
775
776 // Framework libraries need special handling in static coverage builds: they should not have
777 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
778 // the same jacoco classes coming from different bootclasspath jars.
779 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
780 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
781 j.properties.Instrument = true
782 }
783 } else if j.shouldInstrumentStatic(ctx) {
784 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
785 }
Sam Delmericocfd0caa2022-08-31 15:57:52 -0400786 if j.shouldInstrument(ctx) {
787 ctx.AddVariationDependencies(nil, libTag, "jacocoagent")
788 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700789
790 if j.useCompose() {
791 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
792 "androidx.compose.compiler_compiler-hosted")
793 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700794}
795
796func hasSrcExt(srcs []string, ext string) bool {
797 for _, src := range srcs {
798 if filepath.Ext(src) == ext {
799 return true
800 }
801 }
802
803 return false
804}
805
806func (j *Module) hasSrcExt(ext string) bool {
807 return hasSrcExt(j.properties.Srcs, ext)
808}
809
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100810func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
811 var flags string
812
813 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
814 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
815 flags = "-Wmissing-permission-annotation -Werror"
816 }
817 }
818 return flags
819}
820
Jaewoong Jung26342642021-03-17 15:56:23 -0700821func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
822 aidlIncludeDirs android.Paths) (string, android.Paths) {
823
824 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
825 aidlIncludes = append(aidlIncludes,
826 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
827 aidlIncludes = append(aidlIncludes,
828 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
829
830 var flags []string
831 var deps android.Paths
832
833 flags = append(flags, j.deviceProperties.Aidl.Flags...)
834
835 if aidlPreprocess.Valid() {
836 flags = append(flags, "-p"+aidlPreprocess.String())
837 deps = append(deps, aidlPreprocess.Path())
838 } else if len(aidlIncludeDirs) > 0 {
839 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
840 }
841
842 if len(j.exportAidlIncludeDirs) > 0 {
843 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
844 }
845
846 if len(aidlIncludes) > 0 {
847 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
848 }
849
850 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
851 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
852 flags = append(flags, "-I"+src.String())
853 }
854
855 if Bool(j.deviceProperties.Aidl.Generate_traces) {
856 flags = append(flags, "-t")
857 }
858
859 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
860 flags = append(flags, "--transaction_names")
861 }
862
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100863 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
864 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
865 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
866 }
867
Jooyung Han07f70c02021-11-06 07:08:45 +0900868 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
869 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
870
Jaewoong Jung26342642021-03-17 15:56:23 -0700871 return strings.Join(flags, " "), deps
872}
873
874func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
875
876 var flags javaBuilderFlags
877
878 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900879 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700880
Cole Faust2b1536e2021-06-18 12:25:54 -0700881 epEnabled := j.properties.Errorprone.Enabled
882 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700883 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
884 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
885 }
886
887 errorProneFlags := []string{
888 "-Xplugin:ErrorProne",
889 "${config.ErrorProneChecks}",
890 }
891 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
892
Colin Cross8bf6cad2022-02-28 13:07:03 -0800893 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700894 "'" + strings.Join(errorProneFlags, " ") + "'"
895 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
896 }
897
898 // classpath
899 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
900 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700901 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700902 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
903 flags.processorPath = append(flags.processorPath, deps.processorPath...)
904 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
905
906 flags.processors = append(flags.processors, deps.processorClasses...)
907 flags.processors = android.FirstUniqueStrings(flags.processors)
908
909 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900910 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700911 // Give host-side tools a version of OpenJDK's standard libraries
912 // close to what they're targeting. As of Dec 2017, AOSP is only
913 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
914 //
915 // When building with OpenJDK 8, the following should have no
916 // effect since those jars would be available by default.
917 //
918 // When building with OpenJDK 9 but targeting a version < 1.8,
919 // putting them on the bootclasspath means that:
920 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
921 // b) references to existing APIs are not reinterpreted in an
922 // OpenJDK 9-specific way, eg. calls to subclasses of
923 // java.nio.Buffer as in http://b/70862583
924 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
925 flags.bootClasspath = append(flags.bootClasspath,
926 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
927 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
928 if Bool(j.properties.Use_tools_jar) {
929 flags.bootClasspath = append(flags.bootClasspath,
930 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
931 }
932 }
933
934 // systemModules
935 flags.systemModules = deps.systemModules
936
937 // aidl flags.
938 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
939
940 return flags
941}
942
943func (j *Module) collectJavacFlags(
944 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
945 // javac flags.
946 javacFlags := j.properties.Javacflags
947
948 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
949 // For non-host binaries, override the -g flag passed globally to remove
950 // local variable debug info to reduce disk and memory usage.
951 javacFlags = append(javacFlags, "-g:source,lines")
952 }
953 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
954
955 if flags.javaVersion.usesJavaModules() {
956 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
957
958 if j.properties.Patch_module != nil {
959 // Manually specify build directory in case it is not under the repo root.
960 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
961 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200962 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700963
964 // b/150878007
965 //
966 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
967 // execution root for --patch-module. If this javac command line is
968 // invoked within Bazel's execution root working directory, the top
969 // level directories (e.g. libcore/, tools/, frameworks/) are all
970 // symlinks. JDK9 javac does not traverse into symlinks, which causes
971 // --patch-module to fail source file lookups when invoked in the
972 // execution root.
973 //
974 // Short of patching javac or enumerating *all* directories as possible
975 // input dirs, manually add the top level dir of the source files to be
976 // compiled.
977 topLevelDirs := map[string]bool{}
978 for _, srcFilePath := range srcFiles {
979 srcFileParts := strings.Split(srcFilePath.String(), "/")
980 // Ignore source files that are already in the top level directory
981 // as well as generated files in the out directory. The out
982 // directory may be an absolute path, which means srcFileParts[0] is the
983 // empty string, so check that as well. Note that "out" in Bazel's execution
984 // root is *not* a symlink, which doesn't cause problems for --patch-modules
985 // anyway, so it's fine to not apply this workaround for generated
986 // source files.
987 if len(srcFileParts) > 1 &&
988 srcFileParts[0] != "" &&
989 srcFileParts[0] != "out" {
990 topLevelDirs[srcFileParts[0]] = true
991 }
992 }
993 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
994
995 classPath := flags.classpath.FormJavaClassPath("")
996 if classPath != "" {
997 patchPaths = append(patchPaths, classPath)
998 }
999 javacFlags = append(
1000 javacFlags,
1001 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1002 }
1003 }
1004
1005 if len(javacFlags) > 0 {
1006 // optimization.
1007 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1008 flags.javacFlags = "$javacFlags"
1009 }
1010
1011 return flags
1012}
1013
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001014func (j *Module) AddJSONData(d *map[string]interface{}) {
1015 (&j.ModuleBase).AddJSONData(d)
1016 (*d)["Java"] = map[string]interface{}{
1017 "SourceExtensions": j.sourceExtensions,
1018 }
1019
1020}
1021
Jaewoong Jung26342642021-03-17 15:56:23 -07001022func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1023 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1024
1025 deps := j.collectDeps(ctx)
1026 flags := j.collectBuilderFlags(ctx, deps)
1027
1028 if flags.javaVersion.usesJavaModules() {
1029 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1030 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001031
Jaewoong Jung26342642021-03-17 15:56:23 -07001032 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001033 j.sourceExtensions = []string{}
1034 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1035 if hasSrcExt(srcFiles.Strings(), ext) {
1036 j.sourceExtensions = append(j.sourceExtensions, ext)
1037 }
1038 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001039 if hasSrcExt(srcFiles.Strings(), ".proto") {
1040 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1041 }
1042
1043 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1044 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1045 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1046 }
1047
1048 srcFiles = j.genSources(ctx, srcFiles, flags)
1049
1050 // Collect javac flags only after computing the full set of srcFiles to
1051 // ensure that the --patch-module lookup paths are complete.
1052 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1053
1054 srcJars := srcFiles.FilterByExt(".srcjar")
1055 srcJars = append(srcJars, deps.srcJars...)
1056 if aaptSrcJar != nil {
1057 srcJars = append(srcJars, aaptSrcJar)
1058 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001059 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001060
1061 if j.properties.Jarjar_rules != nil {
1062 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1063 }
1064
1065 jarName := ctx.ModuleName() + ".jar"
1066
1067 javaSrcFiles := srcFiles.FilterByExt(".java")
1068 var uniqueSrcFiles android.Paths
1069 set := make(map[string]bool)
1070 for _, v := range javaSrcFiles {
1071 if _, found := set[v.String()]; !found {
1072 set[v.String()] = true
1073 uniqueSrcFiles = append(uniqueSrcFiles, v)
1074 }
1075 }
1076
Colin Crossb5db4012022-03-28 17:12:39 -07001077 // We don't currently run annotation processors in turbine, which means we can't use turbine
1078 // generated header jars when an annotation processor that generates API is enabled. One
1079 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1080 // is used to run all of the annotation processors.
1081 disableTurbine := deps.disableTurbine
1082
Jaewoong Jung26342642021-03-17 15:56:23 -07001083 // Collect .java files for AIDEGen
1084 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1085
1086 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001087 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001088
1089 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001090 // When using kotlin sources turbine is used to generate annotation processor sources,
1091 // including for annotation processors that generate API, so we can use turbine for
1092 // java sources too.
1093 disableTurbine = false
1094
Jaewoong Jung26342642021-03-17 15:56:23 -07001095 // user defined kotlin flags.
1096 kotlincFlags := j.properties.Kotlincflags
1097 CheckKotlincFlags(ctx, kotlincFlags)
1098
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001099 // Workaround for KT-46512
1100 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001101
1102 // If there are kotlin files, compile them first but pass all the kotlin and java files
1103 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1104 // won't emit any classes for them.
1105 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1106 if ctx.Device() {
1107 kotlincFlags = append(kotlincFlags, "-no-jdk")
1108 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001109
1110 for _, plugin := range deps.kotlinPlugins {
1111 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1112 }
1113 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1114
Jaewoong Jung26342642021-03-17 15:56:23 -07001115 if len(kotlincFlags) > 0 {
1116 // optimization.
1117 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1118 flags.kotlincFlags += "$kotlincFlags"
1119 }
1120
1121 var kotlinSrcFiles android.Paths
1122 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1123 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1124
1125 // Collect .kt files for AIDEGen
1126 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1127 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1128
1129 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1130 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1131
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001132 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
1133
Jaewoong Jung26342642021-03-17 15:56:23 -07001134 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1135 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1136
Isaac Chioua23d9942022-04-06 06:14:38 +00001137 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001139 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1140 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1141 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1142 srcJars = append(srcJars, kaptSrcJar)
1143 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 // Disable annotation processing in javac, it's already been handled by kapt
1145 flags.processorPath = nil
1146 flags.processors = nil
1147 }
1148
1149 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001150 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1151 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 if ctx.Failed() {
1153 return
1154 }
1155
Isaac Chioua23d9942022-04-06 06:14:38 +00001156 // Make javac rule depend on the kotlinc rule
1157 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1158
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001160 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1161
Jaewoong Jung26342642021-03-17 15:56:23 -07001162 // Jar kotlin classes into the final jar after javac
1163 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1164 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross220a9a12022-03-28 17:08:01 -07001165 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001166 } else {
1167 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001168 }
1169 }
1170
1171 jars := append(android.Paths(nil), kotlinJars...)
1172
1173 // Store the list of .java files that was passed to javac
1174 j.compiledJavaSrcs = uniqueSrcFiles
1175 j.compiledSrcJars = srcJars
1176
1177 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001178 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001179 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001180 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1181 enableSharding = true
1182 // Formerly, there was a check here that prevented annotation processors
1183 // from being used when sharding was enabled, as some annotation processors
1184 // do not function correctly in sharded environments. It was removed to
1185 // allow for the use of annotation processors that do function correctly
1186 // with sharding enabled. See: b/77284273.
1187 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001188 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001189 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001190 if ctx.Failed() {
1191 return
1192 }
1193 }
1194 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1195 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001196 if Bool(j.properties.Errorprone.Enabled) {
1197 // If error-prone is enabled, enable errorprone flags on the regular
1198 // build.
1199 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001200 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001201 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1202 // a new jar file just for compiling with the errorprone compiler to.
1203 // This is because we don't want to cause the java files to get completely
1204 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1205 // We also don't want to run this if errorprone is enabled by default for
1206 // this module, or else we could have duplicated errorprone messages.
1207 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001208 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001209
1210 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1211 "errorprone", "errorprone")
1212
Jaewoong Jung26342642021-03-17 15:56:23 -07001213 extraJarDeps = append(extraJarDeps, errorprone)
1214 }
1215
1216 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001217 if headerJarFileWithoutDepsOrJarjar != nil {
1218 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1219 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 shardSize := int(*(j.properties.Javac_shard_size))
1221 var shardSrcs []android.Paths
1222 if len(uniqueSrcFiles) > 0 {
1223 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1224 for idx, shardSrc := range shardSrcs {
1225 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1226 nil, flags, extraJarDeps)
1227 jars = append(jars, classes)
1228 }
1229 }
1230 if len(srcJars) > 0 {
1231 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1232 nil, srcJars, flags, extraJarDeps)
1233 jars = append(jars, classes)
1234 }
1235 } else {
1236 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1237 jars = append(jars, classes)
1238 }
1239 if ctx.Failed() {
1240 return
1241 }
1242 }
1243
1244 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1245
1246 var includeSrcJar android.WritablePath
1247 if Bool(j.properties.Include_srcs) {
1248 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1249 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1250 }
1251
1252 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1253 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1254 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1255 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1256
1257 var resArgs []string
1258 var resDeps android.Paths
1259
1260 resArgs = append(resArgs, dirArgs...)
1261 resDeps = append(resDeps, dirDeps...)
1262
1263 resArgs = append(resArgs, fileArgs...)
1264 resDeps = append(resDeps, fileDeps...)
1265
1266 resArgs = append(resArgs, extraArgs...)
1267 resDeps = append(resDeps, extraDeps...)
1268
1269 if len(resArgs) > 0 {
1270 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1271 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1272 j.resourceJar = resourceJar
1273 if ctx.Failed() {
1274 return
1275 }
1276 }
1277
1278 var resourceJars android.Paths
1279 if j.resourceJar != nil {
1280 resourceJars = append(resourceJars, j.resourceJar)
1281 }
1282 if Bool(j.properties.Include_srcs) {
1283 resourceJars = append(resourceJars, includeSrcJar)
1284 }
1285 resourceJars = append(resourceJars, deps.staticResourceJars...)
1286
1287 if len(resourceJars) > 1 {
1288 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1289 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1290 false, nil, nil)
1291 j.resourceJar = combinedJar
1292 } else if len(resourceJars) == 1 {
1293 j.resourceJar = resourceJars[0]
1294 }
1295
1296 if len(deps.staticJars) > 0 {
1297 jars = append(jars, deps.staticJars...)
1298 }
1299
1300 manifest := j.overrideManifest
1301 if !manifest.Valid() && j.properties.Manifest != nil {
1302 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1303 }
1304
1305 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1306 if len(services) > 0 {
1307 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1308 var zipargs []string
1309 for _, file := range services {
1310 serviceFile := file.String()
1311 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1312 }
1313 rule := zip
1314 args := map[string]string{
1315 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1316 }
1317 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1318 rule = zipRE
1319 args["implicits"] = strings.Join(services.Strings(), ",")
1320 }
1321 ctx.Build(pctx, android.BuildParams{
1322 Rule: rule,
1323 Output: servicesJar,
1324 Implicits: services,
1325 Args: args,
1326 })
1327 jars = append(jars, servicesJar)
1328 }
1329
1330 // Combine the classes built from sources, any manifests, and any static libraries into
1331 // classes.jar. If there is only one input jar this step will be skipped.
1332 var outputFile android.OutputPath
1333
1334 if len(jars) == 1 && !manifest.Valid() {
1335 // Optimization: skip the combine step as there is nothing to do
1336 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1337 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1338 // any if len(jars) == 1.
1339
1340 // Transform the single path to the jar into an OutputPath as that is required by the following
1341 // code.
1342 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1343 // The path contains an embedded OutputPath so reuse that.
1344 outputFile = moduleOutPath.OutputPath
1345 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1346 // The path is an OutputPath so reuse it directly.
1347 outputFile = outputPath
1348 } else {
1349 // The file is not in the out directory so create an OutputPath into which it can be copied
1350 // and which the following code can use to refer to it.
1351 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1352 ctx.Build(pctx, android.BuildParams{
1353 Rule: android.Cp,
1354 Input: jars[0],
1355 Output: combinedJar,
1356 })
1357 outputFile = combinedJar.OutputPath
1358 }
1359 } else {
1360 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1361 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1362 false, nil, nil)
1363 outputFile = combinedJar.OutputPath
1364 }
1365
1366 // jarjar implementation jar if necessary
1367 if j.expandJarjarRules != nil {
1368 // Transform classes.jar into classes-jarjar.jar
1369 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1370 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1371 outputFile = jarjarFile
1372
1373 // jarjar resource jar if necessary
1374 if j.resourceJar != nil {
1375 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1376 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1377 j.resourceJar = resourceJarJarFile
1378 }
1379
1380 if ctx.Failed() {
1381 return
1382 }
1383 }
1384
1385 // Check package restrictions if necessary.
1386 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001387 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001388 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001389
1390 // Create a rule to copy the output jar to another path and add a validate dependency that
1391 // will check that the jar only contains the permitted packages. The new location will become
1392 // the output file of this module.
1393 inputFile := outputFile
1394 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1395 ctx.Build(pctx, android.BuildParams{
1396 Rule: android.Cp,
1397 Input: inputFile,
1398 Output: outputFile,
1399 // Make sure that any dependency on the output file will cause ninja to run the package check
1400 // rule.
1401 Validation: pkgckFile,
1402 })
1403
1404 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001405 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001406
1407 if ctx.Failed() {
1408 return
1409 }
1410 }
1411
1412 j.implementationJarFile = outputFile
1413 if j.headerJarFile == nil {
1414 j.headerJarFile = j.implementationJarFile
1415 }
1416
1417 if j.shouldInstrumentInApex(ctx) {
1418 j.properties.Instrument = true
1419 }
1420
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001421 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1422 specs := j.jacocoModuleToZipCommand(ctx)
1423 if ctx.Failed() {
1424 return
1425 }
1426
Jaewoong Jung26342642021-03-17 15:56:23 -07001427 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001428 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001429 }
1430
1431 // merge implementation jar with resources if necessary
1432 implementationAndResourcesJar := outputFile
1433 if j.resourceJar != nil {
1434 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1435 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1436 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1437 false, nil, nil)
1438 implementationAndResourcesJar = combinedJar
1439 }
1440
1441 j.implementationAndResourcesJar = implementationAndResourcesJar
1442
1443 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffin029d7202022-06-29 10:15:52 +00001444 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001445 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1446 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffin029d7202022-06-29 10:15:52 +00001447 if compileDex == nil {
1448 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001449 }
1450 if j.deviceProperties.Hostdex == nil {
1451 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1452 }
1453 }
1454
Paul Duffin029d7202022-06-29 10:15:52 +00001455 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 if j.hasCode(ctx) {
1457 if j.shouldInstrumentStatic(ctx) {
1458 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1459 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1460 }
1461 // Dex compilation
1462 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001463 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001464 if ctx.Failed() {
1465 return
1466 }
1467
Jaewoong Jung26342642021-03-17 15:56:23 -07001468 // merge dex jar with resources if necessary
1469 if j.resourceJar != nil {
1470 jars := android.Paths{dexOutputFile, j.resourceJar}
1471 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1472 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1473 false, nil, nil)
1474 if *j.dexProperties.Uncompress_dex {
1475 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1476 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1477 dexOutputFile = combinedAlignedJar
1478 } else {
1479 dexOutputFile = combinedJar
1480 }
1481 }
1482
Paul Duffin4de94502021-05-16 05:21:16 +01001483 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001484
1485 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001486
1487 // Encode hidden API flags in dex file, if needed.
1488 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1489
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001490 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001491
1492 // Dexpreopting
1493 j.dexpreopt(ctx, dexOutputFile)
1494
1495 outputFile = dexOutputFile
1496 } else {
1497 // There is no code to compile into a dex jar, make sure the resources are propagated
1498 // to the APK if this is an app.
1499 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001500 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 }
1502
1503 if ctx.Failed() {
1504 return
1505 }
1506 } else {
1507 outputFile = implementationAndResourcesJar
1508 }
1509
1510 if ctx.Device() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001511 lintSDKVersion := func(sdkSpec android.SdkSpec) android.ApiLevel {
Jiyong Park54105c42021-03-31 18:17:53 +09001512 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001513 return v
Jaewoong Jung26342642021-03-17 15:56:23 -07001514 } else {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001515 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001516 }
1517 }
1518
1519 j.linter.name = ctx.ModuleName()
1520 j.linter.srcs = srcFiles
1521 j.linter.srcJars = srcJars
1522 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1523 j.linter.classes = j.implementationJarFile
Spandan Dasa3264ef2022-04-22 17:28:25 +00001524 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1525 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1526 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001527 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001528 j.linter.javaLanguageLevel = flags.javaVersion.String()
1529 j.linter.kotlinLanguageLevel = "1.3"
1530 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1531 j.linter.buildModuleReportZip = true
1532 }
1533 j.linter.lint(ctx)
1534 }
1535
1536 ctx.CheckbuildFile(outputFile)
1537
1538 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1539 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1540 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1541 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1542 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1543 AidlIncludeDirs: j.exportAidlIncludeDirs,
1544 SrcJarArgs: j.srcJarArgs,
1545 SrcJarDeps: j.srcJarDeps,
1546 ExportedPlugins: j.exportedPluginJars,
1547 ExportedPluginClasses: j.exportedPluginClasses,
1548 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1549 JacocoReportClassesFile: j.jacocoReportClassesFile,
1550 })
1551
1552 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1553 j.outputFile = outputFile.WithoutRel()
1554}
1555
Colin Crossa1ff7c62021-09-17 14:11:52 -07001556func (j *Module) useCompose() bool {
1557 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1558}
1559
Cole Faust75fffb12021-06-13 15:23:16 -07001560// Returns a copy of the supplied flags, but with all the errorprone-related
1561// fields copied to the regular build's fields.
1562func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1563 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1564
1565 if len(flags.errorProneExtraJavacFlags) > 0 {
1566 if len(flags.javacFlags) > 0 {
1567 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1568 } else {
1569 flags.javacFlags = flags.errorProneExtraJavacFlags
1570 }
1571 }
1572 return flags
1573}
1574
Jaewoong Jung26342642021-03-17 15:56:23 -07001575func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1576 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1577
1578 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1579 if idx >= 0 {
1580 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1581 jarName += strconv.Itoa(idx)
1582 }
1583
1584 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1585 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1586
1587 if ctx.Config().EmitXrefRules() {
1588 extractionFile := android.PathForModuleOut(ctx, kzipName)
1589 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1590 j.kytheFiles = append(j.kytheFiles, extractionFile)
1591 }
1592
1593 return classes
1594}
1595
1596// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1597// since some of these flags may be used internally.
1598func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1599 for _, flag := range flags {
1600 flag = strings.TrimSpace(flag)
1601
1602 if !strings.HasPrefix(flag, "-") {
1603 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1604 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1605 ctx.PropertyErrorf("kotlincflags",
1606 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1607 } else if inList(flag, config.KotlincIllegalFlags) {
1608 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1609 } else if flag == "-include-runtime" {
1610 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1611 } else {
1612 args := strings.Split(flag, " ")
1613 if args[0] == "-kotlin-home" {
1614 ctx.PropertyErrorf("kotlincflags",
1615 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1616 }
1617 }
1618 }
1619}
1620
1621func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1622 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001623 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001624
1625 var jars android.Paths
1626 if len(srcFiles) > 0 || len(srcJars) > 0 {
1627 // Compile java sources into turbine.jar.
1628 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1629 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1630 if ctx.Failed() {
1631 return nil, nil
1632 }
1633 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001634 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001635 }
1636
1637 jars = append(jars, extraJars...)
1638
1639 // Combine any static header libraries into classes-header.jar. If there is only
1640 // one input jar this step will be skipped.
1641 jars = append(jars, deps.staticHeaderJars...)
1642
1643 // we cannot skip the combine step for now if there is only one jar
1644 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1645 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1646 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1647 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001648 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001649
1650 if j.expandJarjarRules != nil {
1651 // Transform classes.jar into classes-jarjar.jar
1652 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001653 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1654 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001655 if ctx.Failed() {
1656 return nil, nil
1657 }
1658 }
1659
Colin Cross3d56ed52021-11-18 22:23:12 -08001660 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001661}
1662
1663func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001664 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001665
1666 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1667 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1668
1669 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1670
1671 j.jacocoReportClassesFile = jacocoReportClassesFile
1672
1673 return instrumentedJar
1674}
1675
1676func (j *Module) HeaderJars() android.Paths {
1677 if j.headerJarFile == nil {
1678 return nil
1679 }
1680 return android.Paths{j.headerJarFile}
1681}
1682
1683func (j *Module) ImplementationJars() android.Paths {
1684 if j.implementationJarFile == nil {
1685 return nil
1686 }
1687 return android.Paths{j.implementationJarFile}
1688}
1689
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001690func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001691 return j.dexJarFile
1692}
1693
1694func (j *Module) DexJarInstallPath() android.Path {
1695 return j.installFile
1696}
1697
1698func (j *Module) ImplementationAndResourcesJars() android.Paths {
1699 if j.implementationAndResourcesJar == nil {
1700 return nil
1701 }
1702 return android.Paths{j.implementationAndResourcesJar}
1703}
1704
1705func (j *Module) AidlIncludeDirs() android.Paths {
1706 // exportAidlIncludeDirs is type android.Paths already
1707 return j.exportAidlIncludeDirs
1708}
1709
1710func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1711 return j.classLoaderContexts
1712}
1713
1714// Collect information for opening IDE project files in java/jdeps.go.
1715func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1716 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1717 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1718 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1719 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1720 if j.expandJarjarRules != nil {
1721 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1722 }
1723 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001724 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1725 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001726}
1727
1728func (j *Module) CompilerDeps() []string {
1729 jdeps := []string{}
1730 jdeps = append(jdeps, j.properties.Libs...)
1731 jdeps = append(jdeps, j.properties.Static_libs...)
1732 return jdeps
1733}
1734
1735func (j *Module) hasCode(ctx android.ModuleContext) bool {
1736 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1737 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1738}
1739
1740// Implements android.ApexModule
1741func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1742 return j.depIsInSameApex(ctx, dep)
1743}
1744
1745// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001746func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001747 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001748 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001749 return fmt.Errorf("min_sdk_version is not specified")
1750 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001751 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001752 return nil
1753 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001754 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1755 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001756 }
1757 return nil
1758}
1759
1760func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001761 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001762}
1763
Jaewoong Jung26342642021-03-17 15:56:23 -07001764func (j *Module) JacocoReportClassesFile() android.Path {
1765 return j.jacocoReportClassesFile
1766}
1767
1768func (j *Module) IsInstallable() bool {
1769 return Bool(j.properties.Installable)
1770}
1771
1772type sdkLinkType int
1773
1774const (
1775 // TODO(jiyong) rename these for better readability. Make the allowed
1776 // and disallowed link types explicit
1777 // order is important here. See rank()
1778 javaCore sdkLinkType = iota
1779 javaSdk
1780 javaSystem
1781 javaModule
1782 javaSystemServer
1783 javaPlatform
1784)
1785
1786func (lt sdkLinkType) String() string {
1787 switch lt {
1788 case javaCore:
1789 return "core Java API"
1790 case javaSdk:
1791 return "Android API"
1792 case javaSystem:
1793 return "system API"
1794 case javaModule:
1795 return "module API"
1796 case javaSystemServer:
1797 return "system server API"
1798 case javaPlatform:
1799 return "private API"
1800 default:
1801 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1802 }
1803}
1804
1805// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1806// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1807// can't statically depend on modules that use Platform API.
1808func (lt sdkLinkType) rank() int {
1809 return int(lt)
1810}
1811
1812type moduleWithSdkDep interface {
1813 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001814 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001815}
1816
Jiyong Park92315372021-04-02 08:45:46 +09001817func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001818 switch name {
1819 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1820 "stub-annotations", "private-stub-annotations-jar",
1821 "core-lambda-stubs", "core-generated-annotation-stubs":
1822 return javaCore, true
1823 case "android_stubs_current":
1824 return javaSdk, true
1825 case "android_system_stubs_current":
1826 return javaSystem, true
1827 case "android_module_lib_stubs_current":
1828 return javaModule, true
1829 case "android_system_server_stubs_current":
1830 return javaSystemServer, true
1831 case "android_test_stubs_current":
1832 return javaSystem, true
1833 }
1834
1835 if stub, linkType := moduleStubLinkType(name); stub {
1836 return linkType, true
1837 }
1838
Jiyong Park92315372021-04-02 08:45:46 +09001839 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001840 switch ver.Kind {
1841 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001842 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001843 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001844 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001845 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001846 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001847 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001848 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001849 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001850 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001851 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001852 return javaPlatform, false
1853 }
1854
Jiyong Parkf1691d22021-03-29 20:11:58 +09001855 if !ver.Valid() {
1856 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001857 }
1858 return javaSdk, false
1859}
1860
1861// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1862// this module's. See the comment on rank() for details and an example.
1863func (j *Module) checkSdkLinkType(
1864 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1865 if ctx.Host() {
1866 return
1867 }
1868
Jiyong Park92315372021-04-02 08:45:46 +09001869 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001870 if stubs {
1871 return
1872 }
Jiyong Park92315372021-04-02 08:45:46 +09001873 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001874
1875 if myLinkType.rank() < depLinkType.rank() {
1876 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1877 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1878 "property of the source or target module so that target module is built "+
1879 "with the same or smaller API set when compared to the source.",
1880 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1881 }
1882}
1883
1884func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1885 var deps deps
1886
1887 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001888 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001889 if sdkDep.invalidVersion {
1890 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1891 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1892 } else if sdkDep.useFiles {
1893 // sdkDep.jar is actually equivalent to turbine header.jar.
1894 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001895 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001896 deps.aidlPreprocess = sdkDep.aidl
1897 } else {
1898 deps.aidlPreprocess = sdkDep.aidl
1899 }
1900 }
1901
Jiyong Park92315372021-04-02 08:45:46 +09001902 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001903
1904 ctx.VisitDirectDeps(func(module android.Module) {
1905 otherName := ctx.OtherModuleName(module)
1906 tag := ctx.OtherModuleDependencyTag(module)
1907
1908 if IsJniDepTag(tag) {
1909 // Handled by AndroidApp.collectAppDeps
1910 return
1911 }
1912 if tag == certificateTag {
1913 // Handled by AndroidApp.collectAppDeps
1914 return
1915 }
1916
1917 if dep, ok := module.(SdkLibraryDependency); ok {
1918 switch tag {
1919 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001920 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1921 deps.classpath = append(deps.classpath, depHeaderJars...)
1922 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001923 case staticLibTag:
1924 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1925 }
1926 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1927 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1928 if sdkLinkType != javaPlatform &&
1929 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1930 // dep is a sysprop implementation library, but this module is not linking against
1931 // the platform, so it gets the sysprop public stubs library instead. Replace
1932 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1933 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1934 dep = syspropDep.JavaInfo
1935 }
1936 switch tag {
1937 case bootClasspathTag:
1938 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1939 case libTag, instrumentationForTag:
1940 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001941 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001942 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1943 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1944 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1945 case java9LibTag:
1946 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1947 case staticLibTag:
1948 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1949 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1950 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1951 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1952 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1953 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1954 // Turbine doesn't run annotation processors, so any module that uses an
1955 // annotation processor that generates API is incompatible with the turbine
1956 // optimization.
1957 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1958 case pluginTag:
1959 if plugin, ok := module.(*Plugin); ok {
1960 if plugin.pluginProperties.Processor_class != nil {
1961 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1962 } else {
1963 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1964 }
1965 // Turbine doesn't run annotation processors, so any module that uses an
1966 // annotation processor that generates API is incompatible with the turbine
1967 // optimization.
1968 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1969 } else {
1970 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1971 }
1972 case errorpronePluginTag:
1973 if _, ok := module.(*Plugin); ok {
1974 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1975 } else {
1976 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1977 }
1978 case exportedPluginTag:
1979 if plugin, ok := module.(*Plugin); ok {
1980 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1981 if plugin.pluginProperties.Processor_class != nil {
1982 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1983 }
1984 // Turbine doesn't run annotation processors, so any module that uses an
1985 // annotation processor that generates API is incompatible with the turbine
1986 // optimization.
1987 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1988 } else {
1989 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1990 }
1991 case kotlinStdlibTag:
1992 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1993 case kotlinAnnotationsTag:
1994 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001995 case kotlinPluginTag:
1996 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001997 case syspropPublicStubDepTag:
1998 // This is a sysprop implementation library, forward the JavaInfoProvider from
1999 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2000 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2001 JavaInfo: dep,
2002 })
2003 }
2004 } else if dep, ok := module.(android.SourceFileProducer); ok {
2005 switch tag {
2006 case libTag:
2007 checkProducesJars(ctx, dep)
2008 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002009 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002010 case staticLibTag:
2011 checkProducesJars(ctx, dep)
2012 deps.classpath = append(deps.classpath, dep.Srcs()...)
2013 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2014 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2015 }
2016 } else {
2017 switch tag {
2018 case bootClasspathTag:
2019 // If a system modules dependency has been added to the bootclasspath
2020 // then add its libs to the bootclasspath.
2021 sm := module.(SystemModulesProvider)
2022 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2023
2024 case systemModulesTag:
2025 if deps.systemModules != nil {
2026 panic("Found two system module dependencies")
2027 }
2028 sm := module.(SystemModulesProvider)
2029 outputDir, outputDeps := sm.OutputDirAndDeps()
2030 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002031
2032 case instrumentationForTag:
2033 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 -07002034 }
2035 }
2036
2037 addCLCFromDep(ctx, module, j.classLoaderContexts)
2038 })
2039
2040 return deps
2041}
2042
2043func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2044 deps.processorPath = append(deps.processorPath, pluginJars...)
2045 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2046}
2047
2048// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2049// this interface.
2050type ProvidesUsesLib interface {
2051 ProvidesUsesLib() *string
2052}
2053
2054func (j *Module) ProvidesUsesLib() *string {
2055 return j.usesLibraryProperties.Provides_uses_lib
2056}
satayev1c564cc2021-05-25 19:50:30 +01002057
2058type ModuleWithStem interface {
2059 Stem() string
2060}
2061
2062var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002063
2064func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2065 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002066 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002067 if lib, ok := ctx.Module().(*Library); ok {
2068 javaLibraryBp2Build(ctx, lib)
2069 }
2070 case "java_binary_host":
2071 if binary, ok := ctx.Module().(*Binary); ok {
2072 javaBinaryHostBp2Build(ctx, binary)
2073 }
2074 }
Wei Libafb6d62021-12-10 03:14:59 -08002075}