blob: 89776d8a5a9831c02cd8085e236fe78d43337218 [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
Sam Delmericof15716f2022-09-07 12:07:07 -0400652func (j *Module) setInstrument(value bool) {
653 j.properties.Instrument = value
654}
655
Jiyong Park92315372021-04-02 08:45:46 +0900656func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
657 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700658}
659
Jiyong Parkf1691d22021-03-29 20:11:58 +0900660func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700661 return proptools.String(j.deviceProperties.System_modules)
662}
663
Jiyong Park92315372021-04-02 08:45:46 +0900664func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700665 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900666 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700667 }
Jiyong Park92315372021-04-02 08:45:46 +0900668 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700669}
670
satayev0a420e72021-11-29 17:25:52 +0000671func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
672 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
673 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
674 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
675 return android.SdkSpecFrom(ctx, maxSdkVersion)
676}
677
Jiyong Parkf1691d22021-03-29 20:11:58 +0900678func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900679 return j.minSdkVersion.Raw
680}
681
682func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
683 if j.deviceProperties.Target_sdk_version != nil {
684 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
685 }
686 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700687}
688
689func (j *Module) AvailableFor(what string) bool {
690 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
691 // Exception: for hostdex: true libraries, the platform variant is created
692 // even if it's not marked as available to platform. In that case, the platform
693 // variant is used only for the hostdex and not installed to the device.
694 return true
695 }
696 return j.ApexModuleBase.AvailableFor(what)
697}
698
699func (j *Module) deps(ctx android.BottomUpMutatorContext) {
700 if ctx.Device() {
701 j.linter.deps(ctx)
702
Jiyong Parkf1691d22021-03-29 20:11:58 +0900703 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700704
705 if j.deviceProperties.SyspropPublicStub != "" {
706 // This is a sysprop implementation library that has a corresponding sysprop public
707 // stubs library, and a dependency on it so that dependencies on the implementation can
708 // be forwarded to the public stubs library when necessary.
709 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
710 }
711 }
712
713 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
714 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
715
716 // Add dependency on libraries that provide additional hidden api annotations.
717 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
718
719 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
720 // Require java_sdk_library at inter-partition java dependency to ensure stable
721 // interface between partitions. If inter-partition java_library dependency is detected,
722 // raise build error because java_library doesn't have a stable interface.
723 //
724 // Inputs:
725 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
726 // if true, enable enforcement
727 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
728 // exception list of java_library names to allow inter-partition dependency
729 for idx := range j.properties.Libs {
730 if libDeps[idx] == nil {
731 continue
732 }
733
734 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
735 // java_sdk_library is always allowed at inter-partition dependency.
736 // So, skip check.
737 if _, ok := javaDep.(*SdkLibrary); ok {
738 continue
739 }
740
741 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
742 }
743 }
744 }
745
746 // For library dependencies that are component libraries (like stubs), add the implementation
747 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
748 for _, dep := range libDeps {
749 if dep != nil {
750 if component, ok := dep.(SdkLibraryComponentDependency); ok {
751 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100752 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100753 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
754 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100755 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700756 }
757 }
758 }
759 }
760
761 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
762 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
763 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
764
765 android.ProtoDeps(ctx, &j.protoProperties)
766 if j.hasSrcExt(".proto") {
767 protoDeps(ctx, &j.protoProperties)
768 }
769
770 if j.hasSrcExt(".kt") {
771 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
772 // Kotlin files
773 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
774 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
775 if len(j.properties.Plugins) > 0 {
776 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
777 }
778 }
779
780 // Framework libraries need special handling in static coverage builds: they should not have
781 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
782 // the same jacoco classes coming from different bootclasspath jars.
783 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
784 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
785 j.properties.Instrument = true
786 }
787 } else if j.shouldInstrumentStatic(ctx) {
788 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
789 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700790
791 if j.useCompose() {
792 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
793 "androidx.compose.compiler_compiler-hosted")
794 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700795}
796
797func hasSrcExt(srcs []string, ext string) bool {
798 for _, src := range srcs {
799 if filepath.Ext(src) == ext {
800 return true
801 }
802 }
803
804 return false
805}
806
807func (j *Module) hasSrcExt(ext string) bool {
808 return hasSrcExt(j.properties.Srcs, ext)
809}
810
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100811func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
812 var flags string
813
814 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
815 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
816 flags = "-Wmissing-permission-annotation -Werror"
817 }
818 }
819 return flags
820}
821
Jaewoong Jung26342642021-03-17 15:56:23 -0700822func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
823 aidlIncludeDirs android.Paths) (string, android.Paths) {
824
825 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
826 aidlIncludes = append(aidlIncludes,
827 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
828 aidlIncludes = append(aidlIncludes,
829 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
830
831 var flags []string
832 var deps android.Paths
833
834 flags = append(flags, j.deviceProperties.Aidl.Flags...)
835
836 if aidlPreprocess.Valid() {
837 flags = append(flags, "-p"+aidlPreprocess.String())
838 deps = append(deps, aidlPreprocess.Path())
839 } else if len(aidlIncludeDirs) > 0 {
840 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
841 }
842
843 if len(j.exportAidlIncludeDirs) > 0 {
844 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
845 }
846
847 if len(aidlIncludes) > 0 {
848 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
849 }
850
851 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
852 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
853 flags = append(flags, "-I"+src.String())
854 }
855
856 if Bool(j.deviceProperties.Aidl.Generate_traces) {
857 flags = append(flags, "-t")
858 }
859
860 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
861 flags = append(flags, "--transaction_names")
862 }
863
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100864 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
865 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
866 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
867 }
868
Jooyung Han07f70c02021-11-06 07:08:45 +0900869 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
870 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
871
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 return strings.Join(flags, " "), deps
873}
874
875func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
876
877 var flags javaBuilderFlags
878
879 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900880 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
Cole Faust2b1536e2021-06-18 12:25:54 -0700882 epEnabled := j.properties.Errorprone.Enabled
883 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
885 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
886 }
887
888 errorProneFlags := []string{
889 "-Xplugin:ErrorProne",
890 "${config.ErrorProneChecks}",
891 }
892 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
893
Colin Cross8bf6cad2022-02-28 13:07:03 -0800894 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700895 "'" + strings.Join(errorProneFlags, " ") + "'"
896 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
897 }
898
899 // classpath
900 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
901 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700902 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700903 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
904 flags.processorPath = append(flags.processorPath, deps.processorPath...)
905 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
906
907 flags.processors = append(flags.processors, deps.processorClasses...)
908 flags.processors = android.FirstUniqueStrings(flags.processors)
909
910 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900911 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 // Give host-side tools a version of OpenJDK's standard libraries
913 // close to what they're targeting. As of Dec 2017, AOSP is only
914 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
915 //
916 // When building with OpenJDK 8, the following should have no
917 // effect since those jars would be available by default.
918 //
919 // When building with OpenJDK 9 but targeting a version < 1.8,
920 // putting them on the bootclasspath means that:
921 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
922 // b) references to existing APIs are not reinterpreted in an
923 // OpenJDK 9-specific way, eg. calls to subclasses of
924 // java.nio.Buffer as in http://b/70862583
925 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
926 flags.bootClasspath = append(flags.bootClasspath,
927 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
928 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
929 if Bool(j.properties.Use_tools_jar) {
930 flags.bootClasspath = append(flags.bootClasspath,
931 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
932 }
933 }
934
935 // systemModules
936 flags.systemModules = deps.systemModules
937
938 // aidl flags.
939 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
940
941 return flags
942}
943
944func (j *Module) collectJavacFlags(
945 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
946 // javac flags.
947 javacFlags := j.properties.Javacflags
948
949 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
950 // For non-host binaries, override the -g flag passed globally to remove
951 // local variable debug info to reduce disk and memory usage.
952 javacFlags = append(javacFlags, "-g:source,lines")
953 }
954 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
955
956 if flags.javaVersion.usesJavaModules() {
957 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
958
959 if j.properties.Patch_module != nil {
960 // Manually specify build directory in case it is not under the repo root.
961 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
962 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200963 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700964
965 // b/150878007
966 //
967 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
968 // execution root for --patch-module. If this javac command line is
969 // invoked within Bazel's execution root working directory, the top
970 // level directories (e.g. libcore/, tools/, frameworks/) are all
971 // symlinks. JDK9 javac does not traverse into symlinks, which causes
972 // --patch-module to fail source file lookups when invoked in the
973 // execution root.
974 //
975 // Short of patching javac or enumerating *all* directories as possible
976 // input dirs, manually add the top level dir of the source files to be
977 // compiled.
978 topLevelDirs := map[string]bool{}
979 for _, srcFilePath := range srcFiles {
980 srcFileParts := strings.Split(srcFilePath.String(), "/")
981 // Ignore source files that are already in the top level directory
982 // as well as generated files in the out directory. The out
983 // directory may be an absolute path, which means srcFileParts[0] is the
984 // empty string, so check that as well. Note that "out" in Bazel's execution
985 // root is *not* a symlink, which doesn't cause problems for --patch-modules
986 // anyway, so it's fine to not apply this workaround for generated
987 // source files.
988 if len(srcFileParts) > 1 &&
989 srcFileParts[0] != "" &&
990 srcFileParts[0] != "out" {
991 topLevelDirs[srcFileParts[0]] = true
992 }
993 }
994 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
995
996 classPath := flags.classpath.FormJavaClassPath("")
997 if classPath != "" {
998 patchPaths = append(patchPaths, classPath)
999 }
1000 javacFlags = append(
1001 javacFlags,
1002 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1003 }
1004 }
1005
1006 if len(javacFlags) > 0 {
1007 // optimization.
1008 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1009 flags.javacFlags = "$javacFlags"
1010 }
1011
1012 return flags
1013}
1014
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001015func (j *Module) AddJSONData(d *map[string]interface{}) {
1016 (&j.ModuleBase).AddJSONData(d)
1017 (*d)["Java"] = map[string]interface{}{
1018 "SourceExtensions": j.sourceExtensions,
1019 }
1020
1021}
1022
Jaewoong Jung26342642021-03-17 15:56:23 -07001023func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1024 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1025
1026 deps := j.collectDeps(ctx)
1027 flags := j.collectBuilderFlags(ctx, deps)
1028
1029 if flags.javaVersion.usesJavaModules() {
1030 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1031 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001032
Jaewoong Jung26342642021-03-17 15:56:23 -07001033 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001034 j.sourceExtensions = []string{}
1035 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1036 if hasSrcExt(srcFiles.Strings(), ext) {
1037 j.sourceExtensions = append(j.sourceExtensions, ext)
1038 }
1039 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001040 if hasSrcExt(srcFiles.Strings(), ".proto") {
1041 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1042 }
1043
1044 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1045 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1046 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1047 }
1048
1049 srcFiles = j.genSources(ctx, srcFiles, flags)
1050
1051 // Collect javac flags only after computing the full set of srcFiles to
1052 // ensure that the --patch-module lookup paths are complete.
1053 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1054
1055 srcJars := srcFiles.FilterByExt(".srcjar")
1056 srcJars = append(srcJars, deps.srcJars...)
1057 if aaptSrcJar != nil {
1058 srcJars = append(srcJars, aaptSrcJar)
1059 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001060 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001061
1062 if j.properties.Jarjar_rules != nil {
1063 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1064 }
1065
1066 jarName := ctx.ModuleName() + ".jar"
1067
1068 javaSrcFiles := srcFiles.FilterByExt(".java")
1069 var uniqueSrcFiles android.Paths
1070 set := make(map[string]bool)
1071 for _, v := range javaSrcFiles {
1072 if _, found := set[v.String()]; !found {
1073 set[v.String()] = true
1074 uniqueSrcFiles = append(uniqueSrcFiles, v)
1075 }
1076 }
1077
Colin Crossb5db4012022-03-28 17:12:39 -07001078 // We don't currently run annotation processors in turbine, which means we can't use turbine
1079 // generated header jars when an annotation processor that generates API is enabled. One
1080 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1081 // is used to run all of the annotation processors.
1082 disableTurbine := deps.disableTurbine
1083
Jaewoong Jung26342642021-03-17 15:56:23 -07001084 // Collect .java files for AIDEGen
1085 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1086
1087 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001088 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001089
1090 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001091 // When using kotlin sources turbine is used to generate annotation processor sources,
1092 // including for annotation processors that generate API, so we can use turbine for
1093 // java sources too.
1094 disableTurbine = false
1095
Jaewoong Jung26342642021-03-17 15:56:23 -07001096 // user defined kotlin flags.
1097 kotlincFlags := j.properties.Kotlincflags
1098 CheckKotlincFlags(ctx, kotlincFlags)
1099
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001100 // Workaround for KT-46512
1101 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001102
1103 // If there are kotlin files, compile them first but pass all the kotlin and java files
1104 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1105 // won't emit any classes for them.
1106 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1107 if ctx.Device() {
1108 kotlincFlags = append(kotlincFlags, "-no-jdk")
1109 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001110
1111 for _, plugin := range deps.kotlinPlugins {
1112 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1113 }
1114 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1115
Jaewoong Jung26342642021-03-17 15:56:23 -07001116 if len(kotlincFlags) > 0 {
1117 // optimization.
1118 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1119 flags.kotlincFlags += "$kotlincFlags"
1120 }
1121
1122 var kotlinSrcFiles android.Paths
1123 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1124 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1125
1126 // Collect .kt files for AIDEGen
1127 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1128 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1129
1130 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1131 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1132
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001133 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
1134
Jaewoong Jung26342642021-03-17 15:56:23 -07001135 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1136 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1137
Isaac Chioua23d9942022-04-06 06:14:38 +00001138 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001139 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001140 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1141 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1142 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1143 srcJars = append(srcJars, kaptSrcJar)
1144 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001145 // Disable annotation processing in javac, it's already been handled by kapt
1146 flags.processorPath = nil
1147 flags.processors = nil
1148 }
1149
1150 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001151 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1152 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001153 if ctx.Failed() {
1154 return
1155 }
1156
Isaac Chioua23d9942022-04-06 06:14:38 +00001157 // Make javac rule depend on the kotlinc rule
1158 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1159
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001161 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1162
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 // Jar kotlin classes into the final jar after javac
1164 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1165 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross220a9a12022-03-28 17:08:01 -07001166 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001167 } else {
1168 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001169 }
1170 }
1171
1172 jars := append(android.Paths(nil), kotlinJars...)
1173
1174 // Store the list of .java files that was passed to javac
1175 j.compiledJavaSrcs = uniqueSrcFiles
1176 j.compiledSrcJars = srcJars
1177
1178 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001179 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001180 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001181 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1182 enableSharding = true
1183 // Formerly, there was a check here that prevented annotation processors
1184 // from being used when sharding was enabled, as some annotation processors
1185 // do not function correctly in sharded environments. It was removed to
1186 // allow for the use of annotation processors that do function correctly
1187 // with sharding enabled. See: b/77284273.
1188 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001189 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001190 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001191 if ctx.Failed() {
1192 return
1193 }
1194 }
1195 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1196 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001197 if Bool(j.properties.Errorprone.Enabled) {
1198 // If error-prone is enabled, enable errorprone flags on the regular
1199 // build.
1200 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001201 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001202 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1203 // a new jar file just for compiling with the errorprone compiler to.
1204 // This is because we don't want to cause the java files to get completely
1205 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1206 // We also don't want to run this if errorprone is enabled by default for
1207 // this module, or else we could have duplicated errorprone messages.
1208 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001209 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001210
1211 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1212 "errorprone", "errorprone")
1213
Jaewoong Jung26342642021-03-17 15:56:23 -07001214 extraJarDeps = append(extraJarDeps, errorprone)
1215 }
1216
1217 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001218 if headerJarFileWithoutDepsOrJarjar != nil {
1219 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1220 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001221 shardSize := int(*(j.properties.Javac_shard_size))
1222 var shardSrcs []android.Paths
1223 if len(uniqueSrcFiles) > 0 {
1224 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1225 for idx, shardSrc := range shardSrcs {
1226 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1227 nil, flags, extraJarDeps)
1228 jars = append(jars, classes)
1229 }
1230 }
1231 if len(srcJars) > 0 {
1232 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1233 nil, srcJars, flags, extraJarDeps)
1234 jars = append(jars, classes)
1235 }
1236 } else {
1237 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1238 jars = append(jars, classes)
1239 }
1240 if ctx.Failed() {
1241 return
1242 }
1243 }
1244
1245 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1246
1247 var includeSrcJar android.WritablePath
1248 if Bool(j.properties.Include_srcs) {
1249 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1250 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1251 }
1252
1253 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1254 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1255 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1256 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1257
1258 var resArgs []string
1259 var resDeps android.Paths
1260
1261 resArgs = append(resArgs, dirArgs...)
1262 resDeps = append(resDeps, dirDeps...)
1263
1264 resArgs = append(resArgs, fileArgs...)
1265 resDeps = append(resDeps, fileDeps...)
1266
1267 resArgs = append(resArgs, extraArgs...)
1268 resDeps = append(resDeps, extraDeps...)
1269
1270 if len(resArgs) > 0 {
1271 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1272 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1273 j.resourceJar = resourceJar
1274 if ctx.Failed() {
1275 return
1276 }
1277 }
1278
1279 var resourceJars android.Paths
1280 if j.resourceJar != nil {
1281 resourceJars = append(resourceJars, j.resourceJar)
1282 }
1283 if Bool(j.properties.Include_srcs) {
1284 resourceJars = append(resourceJars, includeSrcJar)
1285 }
1286 resourceJars = append(resourceJars, deps.staticResourceJars...)
1287
1288 if len(resourceJars) > 1 {
1289 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1290 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1291 false, nil, nil)
1292 j.resourceJar = combinedJar
1293 } else if len(resourceJars) == 1 {
1294 j.resourceJar = resourceJars[0]
1295 }
1296
1297 if len(deps.staticJars) > 0 {
1298 jars = append(jars, deps.staticJars...)
1299 }
1300
1301 manifest := j.overrideManifest
1302 if !manifest.Valid() && j.properties.Manifest != nil {
1303 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1304 }
1305
1306 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1307 if len(services) > 0 {
1308 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1309 var zipargs []string
1310 for _, file := range services {
1311 serviceFile := file.String()
1312 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1313 }
1314 rule := zip
1315 args := map[string]string{
1316 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1317 }
1318 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1319 rule = zipRE
1320 args["implicits"] = strings.Join(services.Strings(), ",")
1321 }
1322 ctx.Build(pctx, android.BuildParams{
1323 Rule: rule,
1324 Output: servicesJar,
1325 Implicits: services,
1326 Args: args,
1327 })
1328 jars = append(jars, servicesJar)
1329 }
1330
1331 // Combine the classes built from sources, any manifests, and any static libraries into
1332 // classes.jar. If there is only one input jar this step will be skipped.
1333 var outputFile android.OutputPath
1334
1335 if len(jars) == 1 && !manifest.Valid() {
1336 // Optimization: skip the combine step as there is nothing to do
1337 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1338 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1339 // any if len(jars) == 1.
1340
1341 // Transform the single path to the jar into an OutputPath as that is required by the following
1342 // code.
1343 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1344 // The path contains an embedded OutputPath so reuse that.
1345 outputFile = moduleOutPath.OutputPath
1346 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1347 // The path is an OutputPath so reuse it directly.
1348 outputFile = outputPath
1349 } else {
1350 // The file is not in the out directory so create an OutputPath into which it can be copied
1351 // and which the following code can use to refer to it.
1352 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1353 ctx.Build(pctx, android.BuildParams{
1354 Rule: android.Cp,
1355 Input: jars[0],
1356 Output: combinedJar,
1357 })
1358 outputFile = combinedJar.OutputPath
1359 }
1360 } else {
1361 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1362 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1363 false, nil, nil)
1364 outputFile = combinedJar.OutputPath
1365 }
1366
1367 // jarjar implementation jar if necessary
1368 if j.expandJarjarRules != nil {
1369 // Transform classes.jar into classes-jarjar.jar
1370 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1371 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1372 outputFile = jarjarFile
1373
1374 // jarjar resource jar if necessary
1375 if j.resourceJar != nil {
1376 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1377 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1378 j.resourceJar = resourceJarJarFile
1379 }
1380
1381 if ctx.Failed() {
1382 return
1383 }
1384 }
1385
1386 // Check package restrictions if necessary.
1387 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001388 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001389 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001390
1391 // Create a rule to copy the output jar to another path and add a validate dependency that
1392 // will check that the jar only contains the permitted packages. The new location will become
1393 // the output file of this module.
1394 inputFile := outputFile
1395 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1396 ctx.Build(pctx, android.BuildParams{
1397 Rule: android.Cp,
1398 Input: inputFile,
1399 Output: outputFile,
1400 // Make sure that any dependency on the output file will cause ninja to run the package check
1401 // rule.
1402 Validation: pkgckFile,
1403 })
1404
1405 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001406 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001407
1408 if ctx.Failed() {
1409 return
1410 }
1411 }
1412
1413 j.implementationJarFile = outputFile
1414 if j.headerJarFile == nil {
1415 j.headerJarFile = j.implementationJarFile
1416 }
1417
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001418 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1419 specs := j.jacocoModuleToZipCommand(ctx)
1420 if ctx.Failed() {
1421 return
1422 }
1423
Jaewoong Jung26342642021-03-17 15:56:23 -07001424 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001425 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001426 }
1427
1428 // merge implementation jar with resources if necessary
1429 implementationAndResourcesJar := outputFile
1430 if j.resourceJar != nil {
1431 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1432 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1433 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1434 false, nil, nil)
1435 implementationAndResourcesJar = combinedJar
1436 }
1437
1438 j.implementationAndResourcesJar = implementationAndResourcesJar
1439
1440 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffin029d7202022-06-29 10:15:52 +00001441 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001442 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1443 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffin029d7202022-06-29 10:15:52 +00001444 if compileDex == nil {
1445 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001446 }
1447 if j.deviceProperties.Hostdex == nil {
1448 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1449 }
1450 }
1451
Paul Duffin029d7202022-06-29 10:15:52 +00001452 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001453 if j.hasCode(ctx) {
1454 if j.shouldInstrumentStatic(ctx) {
1455 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1456 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1457 }
1458 // Dex compilation
1459 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001460 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001461 if ctx.Failed() {
1462 return
1463 }
1464
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 // merge dex jar with resources if necessary
1466 if j.resourceJar != nil {
1467 jars := android.Paths{dexOutputFile, j.resourceJar}
1468 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1469 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1470 false, nil, nil)
1471 if *j.dexProperties.Uncompress_dex {
1472 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1473 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1474 dexOutputFile = combinedAlignedJar
1475 } else {
1476 dexOutputFile = combinedJar
1477 }
1478 }
1479
Paul Duffin4de94502021-05-16 05:21:16 +01001480 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001481
1482 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001483
1484 // Encode hidden API flags in dex file, if needed.
1485 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1486
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001487 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001488
1489 // Dexpreopting
1490 j.dexpreopt(ctx, dexOutputFile)
1491
1492 outputFile = dexOutputFile
1493 } else {
1494 // There is no code to compile into a dex jar, make sure the resources are propagated
1495 // to the APK if this is an app.
1496 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001497 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 }
1499
1500 if ctx.Failed() {
1501 return
1502 }
1503 } else {
1504 outputFile = implementationAndResourcesJar
1505 }
1506
1507 if ctx.Device() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001508 lintSDKVersion := func(sdkSpec android.SdkSpec) android.ApiLevel {
Jiyong Park54105c42021-03-31 18:17:53 +09001509 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001510 return v
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 } else {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001512 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 }
1514 }
1515
1516 j.linter.name = ctx.ModuleName()
1517 j.linter.srcs = srcFiles
1518 j.linter.srcJars = srcJars
1519 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1520 j.linter.classes = j.implementationJarFile
Spandan Dasa3264ef2022-04-22 17:28:25 +00001521 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1522 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1523 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001524 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001525 j.linter.javaLanguageLevel = flags.javaVersion.String()
1526 j.linter.kotlinLanguageLevel = "1.3"
1527 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1528 j.linter.buildModuleReportZip = true
1529 }
1530 j.linter.lint(ctx)
1531 }
1532
1533 ctx.CheckbuildFile(outputFile)
1534
1535 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1536 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1537 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1538 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1539 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1540 AidlIncludeDirs: j.exportAidlIncludeDirs,
1541 SrcJarArgs: j.srcJarArgs,
1542 SrcJarDeps: j.srcJarDeps,
1543 ExportedPlugins: j.exportedPluginJars,
1544 ExportedPluginClasses: j.exportedPluginClasses,
1545 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1546 JacocoReportClassesFile: j.jacocoReportClassesFile,
1547 })
1548
1549 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1550 j.outputFile = outputFile.WithoutRel()
1551}
1552
Colin Crossa1ff7c62021-09-17 14:11:52 -07001553func (j *Module) useCompose() bool {
1554 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1555}
1556
Cole Faust75fffb12021-06-13 15:23:16 -07001557// Returns a copy of the supplied flags, but with all the errorprone-related
1558// fields copied to the regular build's fields.
1559func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1560 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1561
1562 if len(flags.errorProneExtraJavacFlags) > 0 {
1563 if len(flags.javacFlags) > 0 {
1564 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1565 } else {
1566 flags.javacFlags = flags.errorProneExtraJavacFlags
1567 }
1568 }
1569 return flags
1570}
1571
Jaewoong Jung26342642021-03-17 15:56:23 -07001572func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1573 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1574
1575 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1576 if idx >= 0 {
1577 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1578 jarName += strconv.Itoa(idx)
1579 }
1580
1581 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1582 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1583
1584 if ctx.Config().EmitXrefRules() {
1585 extractionFile := android.PathForModuleOut(ctx, kzipName)
1586 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1587 j.kytheFiles = append(j.kytheFiles, extractionFile)
1588 }
1589
1590 return classes
1591}
1592
1593// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1594// since some of these flags may be used internally.
1595func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1596 for _, flag := range flags {
1597 flag = strings.TrimSpace(flag)
1598
1599 if !strings.HasPrefix(flag, "-") {
1600 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1601 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1602 ctx.PropertyErrorf("kotlincflags",
1603 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1604 } else if inList(flag, config.KotlincIllegalFlags) {
1605 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1606 } else if flag == "-include-runtime" {
1607 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1608 } else {
1609 args := strings.Split(flag, " ")
1610 if args[0] == "-kotlin-home" {
1611 ctx.PropertyErrorf("kotlincflags",
1612 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1613 }
1614 }
1615 }
1616}
1617
1618func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1619 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001620 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001621
1622 var jars android.Paths
1623 if len(srcFiles) > 0 || len(srcJars) > 0 {
1624 // Compile java sources into turbine.jar.
1625 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1626 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1627 if ctx.Failed() {
1628 return nil, nil
1629 }
1630 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001631 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001632 }
1633
1634 jars = append(jars, extraJars...)
1635
1636 // Combine any static header libraries into classes-header.jar. If there is only
1637 // one input jar this step will be skipped.
1638 jars = append(jars, deps.staticHeaderJars...)
1639
1640 // we cannot skip the combine step for now if there is only one jar
1641 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1642 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1643 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1644 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001645 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001646
1647 if j.expandJarjarRules != nil {
1648 // Transform classes.jar into classes-jarjar.jar
1649 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001650 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1651 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 if ctx.Failed() {
1653 return nil, nil
1654 }
1655 }
1656
Colin Cross3d56ed52021-11-18 22:23:12 -08001657 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001658}
1659
1660func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001661 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001662
1663 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1664 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1665
1666 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1667
1668 j.jacocoReportClassesFile = jacocoReportClassesFile
1669
1670 return instrumentedJar
1671}
1672
1673func (j *Module) HeaderJars() android.Paths {
1674 if j.headerJarFile == nil {
1675 return nil
1676 }
1677 return android.Paths{j.headerJarFile}
1678}
1679
1680func (j *Module) ImplementationJars() android.Paths {
1681 if j.implementationJarFile == nil {
1682 return nil
1683 }
1684 return android.Paths{j.implementationJarFile}
1685}
1686
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001687func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001688 return j.dexJarFile
1689}
1690
1691func (j *Module) DexJarInstallPath() android.Path {
1692 return j.installFile
1693}
1694
1695func (j *Module) ImplementationAndResourcesJars() android.Paths {
1696 if j.implementationAndResourcesJar == nil {
1697 return nil
1698 }
1699 return android.Paths{j.implementationAndResourcesJar}
1700}
1701
1702func (j *Module) AidlIncludeDirs() android.Paths {
1703 // exportAidlIncludeDirs is type android.Paths already
1704 return j.exportAidlIncludeDirs
1705}
1706
1707func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1708 return j.classLoaderContexts
1709}
1710
1711// Collect information for opening IDE project files in java/jdeps.go.
1712func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1713 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1714 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1715 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1716 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1717 if j.expandJarjarRules != nil {
1718 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1719 }
1720 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001721 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1722 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001723}
1724
1725func (j *Module) CompilerDeps() []string {
1726 jdeps := []string{}
1727 jdeps = append(jdeps, j.properties.Libs...)
1728 jdeps = append(jdeps, j.properties.Static_libs...)
1729 return jdeps
1730}
1731
1732func (j *Module) hasCode(ctx android.ModuleContext) bool {
1733 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1734 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1735}
1736
1737// Implements android.ApexModule
1738func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1739 return j.depIsInSameApex(ctx, dep)
1740}
1741
1742// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001743func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001744 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001745 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001746 return fmt.Errorf("min_sdk_version is not specified")
1747 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001748 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001749 return nil
1750 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001751 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1752 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001753 }
1754 return nil
1755}
1756
1757func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001758 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001759}
1760
Jaewoong Jung26342642021-03-17 15:56:23 -07001761func (j *Module) JacocoReportClassesFile() android.Path {
1762 return j.jacocoReportClassesFile
1763}
1764
1765func (j *Module) IsInstallable() bool {
1766 return Bool(j.properties.Installable)
1767}
1768
1769type sdkLinkType int
1770
1771const (
1772 // TODO(jiyong) rename these for better readability. Make the allowed
1773 // and disallowed link types explicit
1774 // order is important here. See rank()
1775 javaCore sdkLinkType = iota
1776 javaSdk
1777 javaSystem
1778 javaModule
1779 javaSystemServer
1780 javaPlatform
1781)
1782
1783func (lt sdkLinkType) String() string {
1784 switch lt {
1785 case javaCore:
1786 return "core Java API"
1787 case javaSdk:
1788 return "Android API"
1789 case javaSystem:
1790 return "system API"
1791 case javaModule:
1792 return "module API"
1793 case javaSystemServer:
1794 return "system server API"
1795 case javaPlatform:
1796 return "private API"
1797 default:
1798 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1799 }
1800}
1801
1802// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1803// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1804// can't statically depend on modules that use Platform API.
1805func (lt sdkLinkType) rank() int {
1806 return int(lt)
1807}
1808
1809type moduleWithSdkDep interface {
1810 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001811 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001812}
1813
Jiyong Park92315372021-04-02 08:45:46 +09001814func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001815 switch name {
1816 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1817 "stub-annotations", "private-stub-annotations-jar",
1818 "core-lambda-stubs", "core-generated-annotation-stubs":
1819 return javaCore, true
1820 case "android_stubs_current":
1821 return javaSdk, true
1822 case "android_system_stubs_current":
1823 return javaSystem, true
1824 case "android_module_lib_stubs_current":
1825 return javaModule, true
1826 case "android_system_server_stubs_current":
1827 return javaSystemServer, true
1828 case "android_test_stubs_current":
1829 return javaSystem, true
1830 }
1831
1832 if stub, linkType := moduleStubLinkType(name); stub {
1833 return linkType, true
1834 }
1835
Jiyong Park92315372021-04-02 08:45:46 +09001836 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001837 switch ver.Kind {
1838 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001839 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001840 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001841 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001842 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001843 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001844 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001845 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001846 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001847 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001848 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001849 return javaPlatform, false
1850 }
1851
Jiyong Parkf1691d22021-03-29 20:11:58 +09001852 if !ver.Valid() {
1853 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001854 }
1855 return javaSdk, false
1856}
1857
1858// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1859// this module's. See the comment on rank() for details and an example.
1860func (j *Module) checkSdkLinkType(
1861 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1862 if ctx.Host() {
1863 return
1864 }
1865
Jiyong Park92315372021-04-02 08:45:46 +09001866 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001867 if stubs {
1868 return
1869 }
Jiyong Park92315372021-04-02 08:45:46 +09001870 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001871
1872 if myLinkType.rank() < depLinkType.rank() {
1873 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1874 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1875 "property of the source or target module so that target module is built "+
1876 "with the same or smaller API set when compared to the source.",
1877 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1878 }
1879}
1880
1881func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1882 var deps deps
1883
1884 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001885 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001886 if sdkDep.invalidVersion {
1887 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1888 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1889 } else if sdkDep.useFiles {
1890 // sdkDep.jar is actually equivalent to turbine header.jar.
1891 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001892 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001893 deps.aidlPreprocess = sdkDep.aidl
1894 } else {
1895 deps.aidlPreprocess = sdkDep.aidl
1896 }
1897 }
1898
Jiyong Park92315372021-04-02 08:45:46 +09001899 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001900
1901 ctx.VisitDirectDeps(func(module android.Module) {
1902 otherName := ctx.OtherModuleName(module)
1903 tag := ctx.OtherModuleDependencyTag(module)
1904
1905 if IsJniDepTag(tag) {
1906 // Handled by AndroidApp.collectAppDeps
1907 return
1908 }
1909 if tag == certificateTag {
1910 // Handled by AndroidApp.collectAppDeps
1911 return
1912 }
1913
1914 if dep, ok := module.(SdkLibraryDependency); ok {
1915 switch tag {
1916 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001917 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1918 deps.classpath = append(deps.classpath, depHeaderJars...)
1919 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001920 case staticLibTag:
1921 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1922 }
1923 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1924 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1925 if sdkLinkType != javaPlatform &&
1926 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1927 // dep is a sysprop implementation library, but this module is not linking against
1928 // the platform, so it gets the sysprop public stubs library instead. Replace
1929 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1930 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1931 dep = syspropDep.JavaInfo
1932 }
1933 switch tag {
1934 case bootClasspathTag:
1935 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1936 case libTag, instrumentationForTag:
1937 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001938 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001939 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1940 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1941 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1942 case java9LibTag:
1943 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1944 case staticLibTag:
1945 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1946 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1947 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1948 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1949 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1950 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1951 // Turbine doesn't run annotation processors, so any module that uses an
1952 // annotation processor that generates API is incompatible with the turbine
1953 // optimization.
1954 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1955 case pluginTag:
1956 if plugin, ok := module.(*Plugin); ok {
1957 if plugin.pluginProperties.Processor_class != nil {
1958 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1959 } else {
1960 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1961 }
1962 // Turbine doesn't run annotation processors, so any module that uses an
1963 // annotation processor that generates API is incompatible with the turbine
1964 // optimization.
1965 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1966 } else {
1967 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1968 }
1969 case errorpronePluginTag:
1970 if _, ok := module.(*Plugin); ok {
1971 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1972 } else {
1973 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1974 }
1975 case exportedPluginTag:
1976 if plugin, ok := module.(*Plugin); ok {
1977 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1978 if plugin.pluginProperties.Processor_class != nil {
1979 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1980 }
1981 // Turbine doesn't run annotation processors, so any module that uses an
1982 // annotation processor that generates API is incompatible with the turbine
1983 // optimization.
1984 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1985 } else {
1986 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1987 }
1988 case kotlinStdlibTag:
1989 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1990 case kotlinAnnotationsTag:
1991 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001992 case kotlinPluginTag:
1993 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001994 case syspropPublicStubDepTag:
1995 // This is a sysprop implementation library, forward the JavaInfoProvider from
1996 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1997 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1998 JavaInfo: dep,
1999 })
2000 }
2001 } else if dep, ok := module.(android.SourceFileProducer); ok {
2002 switch tag {
2003 case libTag:
2004 checkProducesJars(ctx, dep)
2005 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002006 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002007 case staticLibTag:
2008 checkProducesJars(ctx, dep)
2009 deps.classpath = append(deps.classpath, dep.Srcs()...)
2010 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2011 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2012 }
2013 } else {
2014 switch tag {
2015 case bootClasspathTag:
2016 // If a system modules dependency has been added to the bootclasspath
2017 // then add its libs to the bootclasspath.
2018 sm := module.(SystemModulesProvider)
2019 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2020
2021 case systemModulesTag:
2022 if deps.systemModules != nil {
2023 panic("Found two system module dependencies")
2024 }
2025 sm := module.(SystemModulesProvider)
2026 outputDir, outputDeps := sm.OutputDirAndDeps()
2027 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002028
2029 case instrumentationForTag:
2030 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 -07002031 }
2032 }
2033
2034 addCLCFromDep(ctx, module, j.classLoaderContexts)
2035 })
2036
2037 return deps
2038}
2039
2040func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2041 deps.processorPath = append(deps.processorPath, pluginJars...)
2042 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2043}
2044
2045// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2046// this interface.
2047type ProvidesUsesLib interface {
2048 ProvidesUsesLib() *string
2049}
2050
2051func (j *Module) ProvidesUsesLib() *string {
2052 return j.usesLibraryProperties.Provides_uses_lib
2053}
satayev1c564cc2021-05-25 19:50:30 +01002054
2055type ModuleWithStem interface {
2056 Stem() string
2057}
2058
2059var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002060
2061func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2062 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002063 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002064 if lib, ok := ctx.Module().(*Library); ok {
2065 javaLibraryBp2Build(ctx, lib)
2066 }
2067 case "java_binary_host":
2068 if binary, ok := ctx.Module().(*Binary); ok {
2069 javaBinaryHostBp2Build(ctx, binary)
2070 }
2071 }
Wei Libafb6d62021-12-10 03:14:59 -08002072}