blob: 7f6132a6bf62a028de7603432dbdd29ebb7ce62e [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 Delmericoc7593722022-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 Duffin0038a8d2022-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.
Spandan Das1ccf5742022-10-14 16:51:23 +0000193 // Defaults to an empty string, which compiles the module against the private platform APIs.
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
William Loh5a082f92022-05-17 20:21:50 +0000209 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
210 // Defaults to empty string "". See sdk_version for possible values.
211 Replace_max_sdk_version_placeholder *string
212
Jaewoong Jung26342642021-03-17 15:56:23 -0700213 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000214 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700215 Target_sdk_version *string
216
217 // Whether to compile against the platform APIs instead of an SDK.
218 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000219 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700220 Platform_apis *bool
221
222 Aidl struct {
223 // Top level directories to pass to aidl tool
224 Include_dirs []string
225
226 // Directories rooted at the Android.bp file to pass to aidl tool
227 Local_include_dirs []string
228
229 // directories that should be added as include directories for any aidl sources of modules
230 // that depend on this module, as well as to aidl for this module.
231 Export_include_dirs []string
232
233 // whether to generate traces (for systrace) for this interface
234 Generate_traces *bool
235
236 // whether to generate Binder#GetTransaction name method.
237 Generate_get_transaction_name *bool
238
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100239 // whether all interfaces should be annotated with required permissions.
240 Enforce_permissions *bool
241
242 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
243 Enforce_permissions_exceptions []string `android:"path"`
244
Jaewoong Jung26342642021-03-17 15:56:23 -0700245 // list of flags that will be passed to the AIDL compiler
246 Flags []string
247 }
248
249 // If true, export a copy of the module as a -hostdex module for host testing.
250 Hostdex *bool
251
252 Target struct {
253 Hostdex struct {
254 // Additional required dependencies to add to -hostdex modules.
255 Required []string
256 }
257 }
258
259 // When targeting 1.9 and above, override the modules to use with --system,
260 // otherwise provides defaults libraries to add to the bootclasspath.
261 System_modules *string
262
Jaewoong Jung26342642021-03-17 15:56:23 -0700263 IsSDKLibrary bool `blueprint:"mutated"`
264
265 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
266 // Defaults to false.
267 V4_signature *bool
268
269 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
270 // public stubs library.
271 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000272
273 HiddenAPIPackageProperties
274 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700275}
276
Jooyung Han01d80d82022-01-08 12:16:32 +0900277// Device properties that can be overridden by overriding module (e.g. override_android_app)
278type OverridableDeviceProperties struct {
279 // set the name of the output. If not set, `name` is used.
280 // To override a module with this property set, overriding module might need to set this as well.
281 // Otherwise, both the overridden and the overriding modules will have the same output name, which
282 // can cause the duplicate output error.
283 Stem *string
284}
285
Jaewoong Jung26342642021-03-17 15:56:23 -0700286// Functionality common to Module and Import
287//
288// It is embedded in Module so its functionality can be used by methods in Module
289// but it is currently only initialized by Import and Library.
290type embeddableInModuleAndImport struct {
291
292 // Functionality related to this being used as a component of a java_sdk_library.
293 EmbeddableSdkLibraryComponent
294}
295
Paul Duffin71b33cc2021-06-23 11:39:47 +0100296func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
297 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700298}
299
300// Module/Import's DepIsInSameApex(...) delegates to this method.
301//
302// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
303// the one provided by ApexModuleBase.
304func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
305 // dependencies other than the static linkage are all considered crossing APEX boundary
306 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
307 return true
308 }
309 return false
310}
311
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100312// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
313// or an invalid path describing the reason it is invalid.
314//
315// It is unset if a dex jar isn't applicable, i.e. no build rule has been
316// requested to create one.
317//
318// If a dex jar has been requested to be built then it is set, and it may be
319// either a valid android.Path, or invalid with a reason message. The latter
320// happens if the source that should produce the dex file isn't able to.
321//
322// E.g. it is invalid with a reason message if there is a prebuilt APEX that
323// could produce the dex jar through a deapexer module, but the APEX isn't
324// installable so doing so wouldn't be safe.
325type OptionalDexJarPath struct {
326 isSet bool
327 path android.OptionalPath
328}
329
330// IsSet returns true if a path has been set, either invalid or valid.
331func (o OptionalDexJarPath) IsSet() bool {
332 return o.isSet
333}
334
335// Valid returns true if there is a path that is valid.
336func (o OptionalDexJarPath) Valid() bool {
337 return o.isSet && o.path.Valid()
338}
339
340// Path returns the valid path, or panics if it's either not set or is invalid.
341func (o OptionalDexJarPath) Path() android.Path {
342 if !o.isSet {
343 panic("path isn't set")
344 }
345 return o.path.Path()
346}
347
348// PathOrNil returns the path if it's set and valid, or else nil.
349func (o OptionalDexJarPath) PathOrNil() android.Path {
350 if o.Valid() {
351 return o.Path()
352 }
353 return nil
354}
355
356// InvalidReason returns the reason for an invalid path, which is never "". It
357// returns "" for an unset or valid path.
358func (o OptionalDexJarPath) InvalidReason() string {
359 if !o.isSet {
360 return ""
361 }
362 return o.path.InvalidReason()
363}
364
365func (o OptionalDexJarPath) String() string {
366 if !o.isSet {
367 return "<unset>"
368 }
369 return o.path.String()
370}
371
372// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
373func makeUnsetDexJarPath() OptionalDexJarPath {
374 return OptionalDexJarPath{isSet: false}
375}
376
377// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
378// the given OptionalPath, which may be valid or invalid.
379func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
380 return OptionalDexJarPath{isSet: true, path: path}
381}
382
383// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
384// valid given path. It returns an unset OptionalDexJarPath if the given path is
385// nil.
386func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
387 if path == nil {
388 return makeUnsetDexJarPath()
389 }
390 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
391}
392
Jaewoong Jung26342642021-03-17 15:56:23 -0700393// Module contains the properties and members used by all java module types
394type Module struct {
395 android.ModuleBase
396 android.DefaultableModuleBase
397 android.ApexModuleBase
398 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800399 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700400
401 // Functionality common to Module and Import.
402 embeddableInModuleAndImport
403
404 properties CommonProperties
405 protoProperties android.ProtoProperties
406 deviceProperties DeviceProperties
407
Jooyung Han01d80d82022-01-08 12:16:32 +0900408 overridableDeviceProperties OverridableDeviceProperties
409
Jaewoong Jung26342642021-03-17 15:56:23 -0700410 // jar file containing header classes including static library dependencies, suitable for
411 // inserting into the bootclasspath/classpath of another compile
412 headerJarFile android.Path
413
414 // jar file containing implementation classes including static library dependencies but no
415 // resources
416 implementationJarFile android.Path
417
418 // jar file containing only resources including from static library dependencies
419 resourceJar android.Path
420
421 // args and dependencies to package source files into a srcjar
422 srcJarArgs []string
423 srcJarDeps android.Paths
424
425 // jar file containing implementation classes and resources including static library
426 // dependencies
427 implementationAndResourcesJar android.Path
428
429 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100430 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700431
432 // output file containing uninstrumented classes that will be instrumented by jacoco
433 jacocoReportClassesFile android.Path
434
435 // output file of the module, which may be a classes jar or a dex jar
436 outputFile android.Path
437 extraOutputFiles android.Paths
438
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100439 exportAidlIncludeDirs android.Paths
440 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700441
442 logtagsSrcs android.Paths
443
444 // installed file for binary dependency
445 installFile android.Path
446
Colin Cross3108ce12021-11-10 14:38:50 -0800447 // installed file for hostdex copy
448 hostdexInstallFile android.InstallPath
449
Jaewoong Jung26342642021-03-17 15:56:23 -0700450 // list of .java files and srcjars that was passed to javac
451 compiledJavaSrcs android.Paths
452 compiledSrcJars android.Paths
453
454 // manifest file to use instead of properties.Manifest
455 overrideManifest android.OptionalPath
456
Jaewoong Jung26342642021-03-17 15:56:23 -0700457 // list of plugins that this java module is exporting
458 exportedPluginJars android.Paths
459
460 // list of plugins that this java module is exporting
461 exportedPluginClasses []string
462
463 // if true, the exported plugins generate API and require disabling turbine.
464 exportedDisableTurbine bool
465
466 // list of source files, collected from srcFiles with unique java and all kt files,
467 // will be used by android.IDEInfo struct
468 expandIDEInfoCompiledSrcs []string
469
470 // expanded Jarjar_rules
471 expandJarjarRules android.Path
472
Jaewoong Jung26342642021-03-17 15:56:23 -0700473 // Extra files generated by the module type to be added as java resources.
474 extraResources android.Paths
475
476 hiddenAPI
477 dexer
478 dexpreopter
479 usesLibrary
480 linter
481
482 // list of the xref extraction files
483 kytheFiles android.Paths
484
485 // Collect the module directory for IDE info in java/jdeps.go.
486 modulePaths []string
487
488 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900489
490 sdkVersion android.SdkSpec
491 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000492 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400493
494 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700495}
496
Jiyong Park92315372021-04-02 08:45:46 +0900497func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
498 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900499 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700500 return nil
501 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900502 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000503 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700504 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
505 } else {
506 // Treat stable core platform as stable.
507 return nil
508 }
509 } else {
510 return fmt.Errorf("non stable SDK %v", sdkVersion)
511 }
512}
513
514// checkSdkVersions enforces restrictions around SDK dependencies.
515func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
516 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900517 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900518 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700519 ctx.PropertyErrorf("sdk_version",
520 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
521 }
522 }
523 }
524
525 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
526 // See rank() for details.
527 ctx.VisitDirectDeps(func(module android.Module) {
528 tag := ctx.OtherModuleDependencyTag(module)
529 switch module.(type) {
530 // TODO(satayev): cover other types as well, e.g. imports
531 case *Library, *AndroidLibrary:
532 switch tag {
533 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
534 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
535 }
536 }
537 })
538}
539
540func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900541 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700542 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900543 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700544 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000545 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 -0700546 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000547 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 -0700548 }
549
550 }
551}
552
553func (j *Module) addHostProperties() {
554 j.AddProperties(
555 &j.properties,
556 &j.protoProperties,
557 &j.usesLibraryProperties,
558 )
559}
560
561func (j *Module) addHostAndDeviceProperties() {
562 j.addHostProperties()
563 j.AddProperties(
564 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900565 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700566 &j.dexer.dexProperties,
567 &j.dexpreoptProperties,
568 &j.linter.properties,
569 )
570}
571
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000572// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
573// makes it available through the hiddenAPIPropertyInfoProvider.
574func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
575 hiddenAPIInfo := newHiddenAPIPropertyInfo()
576
577 // Populate with flag file paths from the properties.
578 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
579
580 // Populate with package rules from the properties.
581 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
582
583 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
584}
585
Jaewoong Jung26342642021-03-17 15:56:23 -0700586func (j *Module) OutputFiles(tag string) (android.Paths, error) {
587 switch tag {
588 case "":
589 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
590 case android.DefaultDistTag:
591 return android.Paths{j.outputFile}, nil
592 case ".jar":
593 return android.Paths{j.implementationAndResourcesJar}, nil
594 case ".proguard_map":
595 if j.dexer.proguardDictionary.Valid() {
596 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
597 }
598 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
599 default:
600 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
601 }
602}
603
604var _ android.OutputFileProducer = (*Module)(nil)
605
606func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
607 initJavaModule(module, hod, false)
608}
609
610func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
611 initJavaModule(module, hod, true)
612}
613
614func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
615 multilib := android.MultilibCommon
616 if multiTargets {
617 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
618 } else {
619 android.InitAndroidArchModule(module, hod, multilib)
620 }
621 android.InitDefaultableModule(module)
622}
623
624func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
625 return j.properties.Instrument &&
626 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
627 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
628}
629
630func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000631 return j.properties.Supports_static_instrumentation &&
632 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700633 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
634 ctx.Config().UnbundledBuild())
635}
636
637func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
638 // Force enable the instrumentation for java code that is built for APEXes ...
639 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
640 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
641 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
642 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
643 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
644 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
645 return true
646 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
647 return true
648 }
649 }
650 return false
651}
652
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400653func (j *Module) setInstrument(value bool) {
654 j.properties.Instrument = value
655}
656
Jiyong Park92315372021-04-02 08:45:46 +0900657func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
658 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700659}
660
Jiyong Parkf1691d22021-03-29 20:11:58 +0900661func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700662 return proptools.String(j.deviceProperties.System_modules)
663}
664
Jiyong Park92315372021-04-02 08:45:46 +0900665func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700666 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900667 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700668 }
Jiyong Park92315372021-04-02 08:45:46 +0900669 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700670}
671
satayev0a420e72021-11-29 17:25:52 +0000672func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
673 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
674 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
675 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
676 return android.SdkSpecFrom(ctx, maxSdkVersion)
677}
678
William Loh5a082f92022-05-17 20:21:50 +0000679func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
680 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
681 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
682}
683
Jiyong Parkf1691d22021-03-29 20:11:58 +0900684func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900685 return j.minSdkVersion.Raw
686}
687
688func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
689 if j.deviceProperties.Target_sdk_version != nil {
690 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
691 }
692 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700693}
694
695func (j *Module) AvailableFor(what string) bool {
696 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
697 // Exception: for hostdex: true libraries, the platform variant is created
698 // even if it's not marked as available to platform. In that case, the platform
699 // variant is used only for the hostdex and not installed to the device.
700 return true
701 }
702 return j.ApexModuleBase.AvailableFor(what)
703}
704
705func (j *Module) deps(ctx android.BottomUpMutatorContext) {
706 if ctx.Device() {
707 j.linter.deps(ctx)
708
Jiyong Parkf1691d22021-03-29 20:11:58 +0900709 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700710
711 if j.deviceProperties.SyspropPublicStub != "" {
712 // This is a sysprop implementation library that has a corresponding sysprop public
713 // stubs library, and a dependency on it so that dependencies on the implementation can
714 // be forwarded to the public stubs library when necessary.
715 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
716 }
717 }
718
719 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
720 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
721
722 // Add dependency on libraries that provide additional hidden api annotations.
723 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
724
725 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
726 // Require java_sdk_library at inter-partition java dependency to ensure stable
727 // interface between partitions. If inter-partition java_library dependency is detected,
728 // raise build error because java_library doesn't have a stable interface.
729 //
730 // Inputs:
731 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
732 // if true, enable enforcement
733 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
734 // exception list of java_library names to allow inter-partition dependency
735 for idx := range j.properties.Libs {
736 if libDeps[idx] == nil {
737 continue
738 }
739
740 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
741 // java_sdk_library is always allowed at inter-partition dependency.
742 // So, skip check.
743 if _, ok := javaDep.(*SdkLibrary); ok {
744 continue
745 }
746
747 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
748 }
749 }
750 }
751
752 // For library dependencies that are component libraries (like stubs), add the implementation
753 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
754 for _, dep := range libDeps {
755 if dep != nil {
756 if component, ok := dep.(SdkLibraryComponentDependency); ok {
757 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100758 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100759 tag := usesLibReqTag
760 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
761 tag = usesLibOptTag
762 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100763 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700764 }
765 }
766 }
767 }
768
769 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
770 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
771 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
772
773 android.ProtoDeps(ctx, &j.protoProperties)
774 if j.hasSrcExt(".proto") {
775 protoDeps(ctx, &j.protoProperties)
776 }
777
778 if j.hasSrcExt(".kt") {
779 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
780 // Kotlin files
781 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
782 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700783 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700784 }
785
786 // Framework libraries need special handling in static coverage builds: they should not have
787 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
788 // the same jacoco classes coming from different bootclasspath jars.
789 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
790 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
791 j.properties.Instrument = true
792 }
793 } else if j.shouldInstrumentStatic(ctx) {
794 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
795 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700796
797 if j.useCompose() {
798 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
799 "androidx.compose.compiler_compiler-hosted")
800 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700801}
802
803func hasSrcExt(srcs []string, ext string) bool {
804 for _, src := range srcs {
805 if filepath.Ext(src) == ext {
806 return true
807 }
808 }
809
810 return false
811}
812
813func (j *Module) hasSrcExt(ext string) bool {
814 return hasSrcExt(j.properties.Srcs, ext)
815}
816
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100817func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
818 var flags string
819
820 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
821 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
822 flags = "-Wmissing-permission-annotation -Werror"
823 }
824 }
825 return flags
826}
827
Jaewoong Jung26342642021-03-17 15:56:23 -0700828func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000829 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700830
831 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
832 aidlIncludes = append(aidlIncludes,
833 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
834 aidlIncludes = append(aidlIncludes,
835 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
836
837 var flags []string
838 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000839 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700840
841 flags = append(flags, j.deviceProperties.Aidl.Flags...)
842
843 if aidlPreprocess.Valid() {
844 flags = append(flags, "-p"+aidlPreprocess.String())
845 deps = append(deps, aidlPreprocess.Path())
846 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000847 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700848 }
849
850 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000851 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700852 }
853
854 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000855 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700856 }
857
Sam Delmerico2351eac2022-05-24 17:10:02 +0000858 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700859 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000860 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700861 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000862 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
863 // add flags for dirs containing AIDL srcs that haven't been specified yet
864 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700865
Zim8774ae12022-08-17 11:46:34 +0100866 sdkVersion := (j.SdkVersion(ctx)).Kind
867 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform))
868 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700869 flags = append(flags, "-t")
870 }
871
872 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
873 flags = append(flags, "--transaction_names")
874 }
875
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100876 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
877 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
878 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
879 }
880
Jooyung Han07f70c02021-11-06 07:08:45 +0900881 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
882 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
883
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 return strings.Join(flags, " "), deps
885}
886
887func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
888
889 var flags javaBuilderFlags
890
891 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900892 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700893
Cole Faust2b1536e2021-06-18 12:25:54 -0700894 epEnabled := j.properties.Errorprone.Enabled
895 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700896 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
897 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
898 }
899
900 errorProneFlags := []string{
901 "-Xplugin:ErrorProne",
902 "${config.ErrorProneChecks}",
903 }
904 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
905
Colin Cross8bf6cad2022-02-28 13:07:03 -0800906 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700907 "'" + strings.Join(errorProneFlags, " ") + "'"
908 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
909 }
910
911 // classpath
912 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
913 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700914 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700915 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
916 flags.processorPath = append(flags.processorPath, deps.processorPath...)
917 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
918
919 flags.processors = append(flags.processors, deps.processorClasses...)
920 flags.processors = android.FirstUniqueStrings(flags.processors)
921
922 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900923 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700924 // Give host-side tools a version of OpenJDK's standard libraries
925 // close to what they're targeting. As of Dec 2017, AOSP is only
926 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
927 //
928 // When building with OpenJDK 8, the following should have no
929 // effect since those jars would be available by default.
930 //
931 // When building with OpenJDK 9 but targeting a version < 1.8,
932 // putting them on the bootclasspath means that:
933 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
934 // b) references to existing APIs are not reinterpreted in an
935 // OpenJDK 9-specific way, eg. calls to subclasses of
936 // java.nio.Buffer as in http://b/70862583
937 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
938 flags.bootClasspath = append(flags.bootClasspath,
939 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
940 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
941 if Bool(j.properties.Use_tools_jar) {
942 flags.bootClasspath = append(flags.bootClasspath,
943 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
944 }
945 }
946
947 // systemModules
948 flags.systemModules = deps.systemModules
949
Jaewoong Jung26342642021-03-17 15:56:23 -0700950 return flags
951}
952
953func (j *Module) collectJavacFlags(
954 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
955 // javac flags.
956 javacFlags := j.properties.Javacflags
957
958 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
959 // For non-host binaries, override the -g flag passed globally to remove
960 // local variable debug info to reduce disk and memory usage.
961 javacFlags = append(javacFlags, "-g:source,lines")
962 }
963 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
964
965 if flags.javaVersion.usesJavaModules() {
966 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
967
968 if j.properties.Patch_module != nil {
969 // Manually specify build directory in case it is not under the repo root.
970 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
971 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200972 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700973
974 // b/150878007
975 //
976 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
977 // execution root for --patch-module. If this javac command line is
978 // invoked within Bazel's execution root working directory, the top
979 // level directories (e.g. libcore/, tools/, frameworks/) are all
980 // symlinks. JDK9 javac does not traverse into symlinks, which causes
981 // --patch-module to fail source file lookups when invoked in the
982 // execution root.
983 //
984 // Short of patching javac or enumerating *all* directories as possible
985 // input dirs, manually add the top level dir of the source files to be
986 // compiled.
987 topLevelDirs := map[string]bool{}
988 for _, srcFilePath := range srcFiles {
989 srcFileParts := strings.Split(srcFilePath.String(), "/")
990 // Ignore source files that are already in the top level directory
991 // as well as generated files in the out directory. The out
992 // directory may be an absolute path, which means srcFileParts[0] is the
993 // empty string, so check that as well. Note that "out" in Bazel's execution
994 // root is *not* a symlink, which doesn't cause problems for --patch-modules
995 // anyway, so it's fine to not apply this workaround for generated
996 // source files.
997 if len(srcFileParts) > 1 &&
998 srcFileParts[0] != "" &&
999 srcFileParts[0] != "out" {
1000 topLevelDirs[srcFileParts[0]] = true
1001 }
1002 }
1003 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
1004
1005 classPath := flags.classpath.FormJavaClassPath("")
1006 if classPath != "" {
1007 patchPaths = append(patchPaths, classPath)
1008 }
1009 javacFlags = append(
1010 javacFlags,
1011 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1012 }
1013 }
1014
1015 if len(javacFlags) > 0 {
1016 // optimization.
1017 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1018 flags.javacFlags = "$javacFlags"
1019 }
1020
1021 return flags
1022}
1023
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001024func (j *Module) AddJSONData(d *map[string]interface{}) {
1025 (&j.ModuleBase).AddJSONData(d)
1026 (*d)["Java"] = map[string]interface{}{
1027 "SourceExtensions": j.sourceExtensions,
1028 }
1029
1030}
1031
Jaewoong Jung26342642021-03-17 15:56:23 -07001032func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1033 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1034
1035 deps := j.collectDeps(ctx)
1036 flags := j.collectBuilderFlags(ctx, deps)
1037
1038 if flags.javaVersion.usesJavaModules() {
1039 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1040 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001041
Jaewoong Jung26342642021-03-17 15:56:23 -07001042 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001043 j.sourceExtensions = []string{}
1044 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1045 if hasSrcExt(srcFiles.Strings(), ext) {
1046 j.sourceExtensions = append(j.sourceExtensions, ext)
1047 }
1048 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001049 if hasSrcExt(srcFiles.Strings(), ".proto") {
1050 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1051 }
1052
1053 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1054 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1055 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1056 }
1057
Sam Delmerico2351eac2022-05-24 17:10:02 +00001058 aidlSrcs := srcFiles.FilterByExt(".aidl")
1059 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1060
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001061 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001062 srcFiles = j.genSources(ctx, srcFiles, flags)
1063
1064 // Collect javac flags only after computing the full set of srcFiles to
1065 // ensure that the --patch-module lookup paths are complete.
1066 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1067
1068 srcJars := srcFiles.FilterByExt(".srcjar")
1069 srcJars = append(srcJars, deps.srcJars...)
1070 if aaptSrcJar != nil {
1071 srcJars = append(srcJars, aaptSrcJar)
1072 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001073 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001074
1075 if j.properties.Jarjar_rules != nil {
1076 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1077 }
1078
1079 jarName := ctx.ModuleName() + ".jar"
1080
1081 javaSrcFiles := srcFiles.FilterByExt(".java")
1082 var uniqueSrcFiles android.Paths
1083 set := make(map[string]bool)
1084 for _, v := range javaSrcFiles {
1085 if _, found := set[v.String()]; !found {
1086 set[v.String()] = true
1087 uniqueSrcFiles = append(uniqueSrcFiles, v)
1088 }
1089 }
1090
Colin Crossb5db4012022-03-28 17:12:39 -07001091 // We don't currently run annotation processors in turbine, which means we can't use turbine
1092 // generated header jars when an annotation processor that generates API is enabled. One
1093 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1094 // is used to run all of the annotation processors.
1095 disableTurbine := deps.disableTurbine
1096
Jaewoong Jung26342642021-03-17 15:56:23 -07001097 // Collect .java files for AIDEGen
1098 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1099
1100 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001101 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001102
1103 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001104 // When using kotlin sources turbine is used to generate annotation processor sources,
1105 // including for annotation processors that generate API, so we can use turbine for
1106 // java sources too.
1107 disableTurbine = false
1108
Jaewoong Jung26342642021-03-17 15:56:23 -07001109 // user defined kotlin flags.
1110 kotlincFlags := j.properties.Kotlincflags
1111 CheckKotlincFlags(ctx, kotlincFlags)
1112
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001113 // Workaround for KT-46512
1114 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001115
1116 // If there are kotlin files, compile them first but pass all the kotlin and java files
1117 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1118 // won't emit any classes for them.
1119 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1120 if ctx.Device() {
1121 kotlincFlags = append(kotlincFlags, "-no-jdk")
1122 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001123
1124 for _, plugin := range deps.kotlinPlugins {
1125 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1126 }
1127 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1128
Jaewoong Jung26342642021-03-17 15:56:23 -07001129 if len(kotlincFlags) > 0 {
1130 // optimization.
1131 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1132 flags.kotlincFlags += "$kotlincFlags"
1133 }
1134
1135 var kotlinSrcFiles android.Paths
1136 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1137 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1138
1139 // Collect .kt files for AIDEGen
1140 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1141 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1142
1143 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1144 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1145
1146 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1147 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1148
Isaac Chioua23d9942022-04-06 06:14:38 +00001149 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001150 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001151 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1152 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1153 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1154 srcJars = append(srcJars, kaptSrcJar)
1155 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001156 // Disable annotation processing in javac, it's already been handled by kapt
1157 flags.processorPath = nil
1158 flags.processors = nil
1159 }
1160
1161 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001162 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1163 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001164 if ctx.Failed() {
1165 return
1166 }
1167
Isaac Chioua23d9942022-04-06 06:14:38 +00001168 // Make javac rule depend on the kotlinc rule
1169 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1170
Jaewoong Jung26342642021-03-17 15:56:23 -07001171 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001172 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1173
Jaewoong Jung26342642021-03-17 15:56:23 -07001174 // Jar kotlin classes into the final jar after javac
1175 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1176 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001177 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001178 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001179 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001180 } else {
1181 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001182 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 }
1184 }
1185
1186 jars := append(android.Paths(nil), kotlinJars...)
1187
1188 // Store the list of .java files that was passed to javac
1189 j.compiledJavaSrcs = uniqueSrcFiles
1190 j.compiledSrcJars = srcJars
1191
1192 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001193 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001194 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001195 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1196 enableSharding = true
1197 // Formerly, there was a check here that prevented annotation processors
1198 // from being used when sharding was enabled, as some annotation processors
1199 // do not function correctly in sharded environments. It was removed to
1200 // allow for the use of annotation processors that do function correctly
1201 // with sharding enabled. See: b/77284273.
1202 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001203 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001204 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001205 if ctx.Failed() {
1206 return
1207 }
1208 }
1209 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001210 hasErrorproneableFiles := false
1211 for _, ext := range j.sourceExtensions {
1212 if ext != ".proto" && ext != ".aidl" {
1213 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1214 // compile, and it's not useful to have warnings on these generated sources.
1215 hasErrorproneableFiles = true
1216 break
1217 }
1218 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001219 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001220 if Bool(j.properties.Errorprone.Enabled) {
1221 // If error-prone is enabled, enable errorprone flags on the regular
1222 // build.
1223 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001224 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001225 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1226 // a new jar file just for compiling with the errorprone compiler to.
1227 // This is because we don't want to cause the java files to get completely
1228 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1229 // We also don't want to run this if errorprone is enabled by default for
1230 // this module, or else we could have duplicated errorprone messages.
1231 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001233
1234 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1235 "errorprone", "errorprone")
1236
Jaewoong Jung26342642021-03-17 15:56:23 -07001237 extraJarDeps = append(extraJarDeps, errorprone)
1238 }
1239
1240 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001241 if headerJarFileWithoutDepsOrJarjar != nil {
1242 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1243 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001244 shardSize := int(*(j.properties.Javac_shard_size))
1245 var shardSrcs []android.Paths
1246 if len(uniqueSrcFiles) > 0 {
1247 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1248 for idx, shardSrc := range shardSrcs {
1249 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1250 nil, flags, extraJarDeps)
1251 jars = append(jars, classes)
1252 }
1253 }
1254 if len(srcJars) > 0 {
1255 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1256 nil, srcJars, flags, extraJarDeps)
1257 jars = append(jars, classes)
1258 }
1259 } else {
1260 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1261 jars = append(jars, classes)
1262 }
1263 if ctx.Failed() {
1264 return
1265 }
1266 }
1267
1268 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1269
1270 var includeSrcJar android.WritablePath
1271 if Bool(j.properties.Include_srcs) {
1272 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1273 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1274 }
1275
1276 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1277 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1278 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1279 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1280
1281 var resArgs []string
1282 var resDeps android.Paths
1283
1284 resArgs = append(resArgs, dirArgs...)
1285 resDeps = append(resDeps, dirDeps...)
1286
1287 resArgs = append(resArgs, fileArgs...)
1288 resDeps = append(resDeps, fileDeps...)
1289
1290 resArgs = append(resArgs, extraArgs...)
1291 resDeps = append(resDeps, extraDeps...)
1292
1293 if len(resArgs) > 0 {
1294 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1295 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1296 j.resourceJar = resourceJar
1297 if ctx.Failed() {
1298 return
1299 }
1300 }
1301
1302 var resourceJars android.Paths
1303 if j.resourceJar != nil {
1304 resourceJars = append(resourceJars, j.resourceJar)
1305 }
1306 if Bool(j.properties.Include_srcs) {
1307 resourceJars = append(resourceJars, includeSrcJar)
1308 }
1309 resourceJars = append(resourceJars, deps.staticResourceJars...)
1310
1311 if len(resourceJars) > 1 {
1312 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1313 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1314 false, nil, nil)
1315 j.resourceJar = combinedJar
1316 } else if len(resourceJars) == 1 {
1317 j.resourceJar = resourceJars[0]
1318 }
1319
1320 if len(deps.staticJars) > 0 {
1321 jars = append(jars, deps.staticJars...)
1322 }
1323
1324 manifest := j.overrideManifest
1325 if !manifest.Valid() && j.properties.Manifest != nil {
1326 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1327 }
1328
1329 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1330 if len(services) > 0 {
1331 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1332 var zipargs []string
1333 for _, file := range services {
1334 serviceFile := file.String()
1335 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1336 }
1337 rule := zip
1338 args := map[string]string{
1339 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1340 }
1341 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1342 rule = zipRE
1343 args["implicits"] = strings.Join(services.Strings(), ",")
1344 }
1345 ctx.Build(pctx, android.BuildParams{
1346 Rule: rule,
1347 Output: servicesJar,
1348 Implicits: services,
1349 Args: args,
1350 })
1351 jars = append(jars, servicesJar)
1352 }
1353
1354 // Combine the classes built from sources, any manifests, and any static libraries into
1355 // classes.jar. If there is only one input jar this step will be skipped.
1356 var outputFile android.OutputPath
1357
1358 if len(jars) == 1 && !manifest.Valid() {
1359 // Optimization: skip the combine step as there is nothing to do
1360 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1361 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1362 // any if len(jars) == 1.
1363
1364 // Transform the single path to the jar into an OutputPath as that is required by the following
1365 // code.
1366 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1367 // The path contains an embedded OutputPath so reuse that.
1368 outputFile = moduleOutPath.OutputPath
1369 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1370 // The path is an OutputPath so reuse it directly.
1371 outputFile = outputPath
1372 } else {
1373 // The file is not in the out directory so create an OutputPath into which it can be copied
1374 // and which the following code can use to refer to it.
1375 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1376 ctx.Build(pctx, android.BuildParams{
1377 Rule: android.Cp,
1378 Input: jars[0],
1379 Output: combinedJar,
1380 })
1381 outputFile = combinedJar.OutputPath
1382 }
1383 } else {
1384 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1385 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1386 false, nil, nil)
1387 outputFile = combinedJar.OutputPath
1388 }
1389
1390 // jarjar implementation jar if necessary
1391 if j.expandJarjarRules != nil {
1392 // Transform classes.jar into classes-jarjar.jar
1393 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1394 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1395 outputFile = jarjarFile
1396
1397 // jarjar resource jar if necessary
1398 if j.resourceJar != nil {
1399 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1400 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1401 j.resourceJar = resourceJarJarFile
1402 }
1403
1404 if ctx.Failed() {
1405 return
1406 }
1407 }
1408
1409 // Check package restrictions if necessary.
1410 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001411 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001412 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001413
1414 // Create a rule to copy the output jar to another path and add a validate dependency that
1415 // will check that the jar only contains the permitted packages. The new location will become
1416 // the output file of this module.
1417 inputFile := outputFile
1418 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1419 ctx.Build(pctx, android.BuildParams{
1420 Rule: android.Cp,
1421 Input: inputFile,
1422 Output: outputFile,
1423 // Make sure that any dependency on the output file will cause ninja to run the package check
1424 // rule.
1425 Validation: pkgckFile,
1426 })
1427
1428 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001429 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001430
1431 if ctx.Failed() {
1432 return
1433 }
1434 }
1435
1436 j.implementationJarFile = outputFile
1437 if j.headerJarFile == nil {
1438 j.headerJarFile = j.implementationJarFile
1439 }
1440
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001441 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1442 specs := j.jacocoModuleToZipCommand(ctx)
1443 if ctx.Failed() {
1444 return
1445 }
1446
Jaewoong Jung26342642021-03-17 15:56:23 -07001447 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001448 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001449 }
1450
1451 // merge implementation jar with resources if necessary
1452 implementationAndResourcesJar := outputFile
1453 if j.resourceJar != nil {
1454 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1455 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1456 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1457 false, nil, nil)
1458 implementationAndResourcesJar = combinedJar
1459 }
1460
1461 j.implementationAndResourcesJar = implementationAndResourcesJar
1462
1463 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001464 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001465 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1466 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001467 if compileDex == nil {
1468 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001469 }
1470 if j.deviceProperties.Hostdex == nil {
1471 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1472 }
1473 }
1474
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001475 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 if j.hasCode(ctx) {
1477 if j.shouldInstrumentStatic(ctx) {
1478 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1479 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1480 }
1481 // Dex compilation
1482 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001483 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001484 if ctx.Failed() {
1485 return
1486 }
1487
Jaewoong Jung26342642021-03-17 15:56:23 -07001488 // merge dex jar with resources if necessary
1489 if j.resourceJar != nil {
1490 jars := android.Paths{dexOutputFile, j.resourceJar}
1491 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1492 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1493 false, nil, nil)
1494 if *j.dexProperties.Uncompress_dex {
1495 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1496 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1497 dexOutputFile = combinedAlignedJar
1498 } else {
1499 dexOutputFile = combinedJar
1500 }
1501 }
1502
Paul Duffin4de94502021-05-16 05:21:16 +01001503 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001504
1505 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001506
1507 // Encode hidden API flags in dex file, if needed.
1508 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1509
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001510 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001511
1512 // Dexpreopting
1513 j.dexpreopt(ctx, dexOutputFile)
1514
1515 outputFile = dexOutputFile
1516 } else {
1517 // There is no code to compile into a dex jar, make sure the resources are propagated
1518 // to the APK if this is an app.
1519 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001520 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001521 }
1522
1523 if ctx.Failed() {
1524 return
1525 }
1526 } else {
1527 outputFile = implementationAndResourcesJar
1528 }
1529
1530 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001531 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001532 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001533 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001534 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001535 // When running metalava, we pass --version-codename. When that value
1536 // is not REL, metalava will add 1 to the --current-version argument.
1537 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1538 // branch) and the codename is REL, except potentially on the most
1539 // recent non-master branch. On that branch, it goes through two other
1540 // phases before it gets to the phase previously described:
1541 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1542 // is not rel. This happens for most of the internal branch's life
1543 // while the branch has been cut but is still under active development.
1544 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1545 // REL. This happens briefly during the release process. During this
1546 // state the code to add --current-version is commented out, and then
1547 // that commenting out is reverted after the codename is set to REL.
1548 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1549 // prior version and the codename is always non-REL.
1550 //
1551 // We need to add one here to match metalava adding 1. Technically
1552 // this means that in the state described in the second bullet point
1553 // above, this number is 1 higher than it should be.
1554 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001555 }
1556 }
1557
1558 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001559 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1560 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001561 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1562 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001563 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1564 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1565 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001566 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001567 j.linter.javaLanguageLevel = flags.javaVersion.String()
1568 j.linter.kotlinLanguageLevel = "1.3"
1569 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1570 j.linter.buildModuleReportZip = true
1571 }
1572 j.linter.lint(ctx)
1573 }
1574
1575 ctx.CheckbuildFile(outputFile)
1576
1577 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1578 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1579 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1580 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1581 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1582 AidlIncludeDirs: j.exportAidlIncludeDirs,
1583 SrcJarArgs: j.srcJarArgs,
1584 SrcJarDeps: j.srcJarDeps,
1585 ExportedPlugins: j.exportedPluginJars,
1586 ExportedPluginClasses: j.exportedPluginClasses,
1587 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1588 JacocoReportClassesFile: j.jacocoReportClassesFile,
1589 })
1590
1591 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1592 j.outputFile = outputFile.WithoutRel()
1593}
1594
Colin Crossa1ff7c62021-09-17 14:11:52 -07001595func (j *Module) useCompose() bool {
1596 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1597}
1598
Cole Faust75fffb12021-06-13 15:23:16 -07001599// Returns a copy of the supplied flags, but with all the errorprone-related
1600// fields copied to the regular build's fields.
1601func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1602 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1603
1604 if len(flags.errorProneExtraJavacFlags) > 0 {
1605 if len(flags.javacFlags) > 0 {
1606 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1607 } else {
1608 flags.javacFlags = flags.errorProneExtraJavacFlags
1609 }
1610 }
1611 return flags
1612}
1613
Jaewoong Jung26342642021-03-17 15:56:23 -07001614func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1615 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1616
1617 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1618 if idx >= 0 {
1619 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1620 jarName += strconv.Itoa(idx)
1621 }
1622
1623 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1624 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1625
1626 if ctx.Config().EmitXrefRules() {
1627 extractionFile := android.PathForModuleOut(ctx, kzipName)
1628 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1629 j.kytheFiles = append(j.kytheFiles, extractionFile)
1630 }
1631
1632 return classes
1633}
1634
1635// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1636// since some of these flags may be used internally.
1637func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1638 for _, flag := range flags {
1639 flag = strings.TrimSpace(flag)
1640
1641 if !strings.HasPrefix(flag, "-") {
1642 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1643 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1644 ctx.PropertyErrorf("kotlincflags",
1645 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1646 } else if inList(flag, config.KotlincIllegalFlags) {
1647 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1648 } else if flag == "-include-runtime" {
1649 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1650 } else {
1651 args := strings.Split(flag, " ")
1652 if args[0] == "-kotlin-home" {
1653 ctx.PropertyErrorf("kotlincflags",
1654 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1655 }
1656 }
1657 }
1658}
1659
1660func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1661 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001662 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001663
1664 var jars android.Paths
1665 if len(srcFiles) > 0 || len(srcJars) > 0 {
1666 // Compile java sources into turbine.jar.
1667 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1668 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1669 if ctx.Failed() {
1670 return nil, nil
1671 }
1672 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001673 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001674 }
1675
1676 jars = append(jars, extraJars...)
1677
1678 // Combine any static header libraries into classes-header.jar. If there is only
1679 // one input jar this step will be skipped.
1680 jars = append(jars, deps.staticHeaderJars...)
1681
1682 // we cannot skip the combine step for now if there is only one jar
1683 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1684 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1685 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1686 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001687 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001688
1689 if j.expandJarjarRules != nil {
1690 // Transform classes.jar into classes-jarjar.jar
1691 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001692 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1693 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001694 if ctx.Failed() {
1695 return nil, nil
1696 }
1697 }
1698
Colin Cross3d56ed52021-11-18 22:23:12 -08001699 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001700}
1701
1702func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001703 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001704
1705 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1706 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1707
1708 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1709
1710 j.jacocoReportClassesFile = jacocoReportClassesFile
1711
1712 return instrumentedJar
1713}
1714
1715func (j *Module) HeaderJars() android.Paths {
1716 if j.headerJarFile == nil {
1717 return nil
1718 }
1719 return android.Paths{j.headerJarFile}
1720}
1721
1722func (j *Module) ImplementationJars() android.Paths {
1723 if j.implementationJarFile == nil {
1724 return nil
1725 }
1726 return android.Paths{j.implementationJarFile}
1727}
1728
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001729func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001730 return j.dexJarFile
1731}
1732
1733func (j *Module) DexJarInstallPath() android.Path {
1734 return j.installFile
1735}
1736
1737func (j *Module) ImplementationAndResourcesJars() android.Paths {
1738 if j.implementationAndResourcesJar == nil {
1739 return nil
1740 }
1741 return android.Paths{j.implementationAndResourcesJar}
1742}
1743
1744func (j *Module) AidlIncludeDirs() android.Paths {
1745 // exportAidlIncludeDirs is type android.Paths already
1746 return j.exportAidlIncludeDirs
1747}
1748
1749func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1750 return j.classLoaderContexts
1751}
1752
1753// Collect information for opening IDE project files in java/jdeps.go.
1754func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1755 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1756 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1757 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1758 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1759 if j.expandJarjarRules != nil {
1760 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1761 }
1762 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001763 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1764 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001765}
1766
1767func (j *Module) CompilerDeps() []string {
1768 jdeps := []string{}
1769 jdeps = append(jdeps, j.properties.Libs...)
1770 jdeps = append(jdeps, j.properties.Static_libs...)
1771 return jdeps
1772}
1773
1774func (j *Module) hasCode(ctx android.ModuleContext) bool {
1775 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1776 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1777}
1778
1779// Implements android.ApexModule
1780func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1781 return j.depIsInSameApex(ctx, dep)
1782}
1783
1784// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001785func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001786 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001787 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001788 return fmt.Errorf("min_sdk_version is not specified")
1789 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001790 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001791 return nil
1792 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001793 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1794 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001795 }
1796 return nil
1797}
1798
1799func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001800 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001801}
1802
Jaewoong Jung26342642021-03-17 15:56:23 -07001803func (j *Module) JacocoReportClassesFile() android.Path {
1804 return j.jacocoReportClassesFile
1805}
1806
1807func (j *Module) IsInstallable() bool {
1808 return Bool(j.properties.Installable)
1809}
1810
1811type sdkLinkType int
1812
1813const (
1814 // TODO(jiyong) rename these for better readability. Make the allowed
1815 // and disallowed link types explicit
1816 // order is important here. See rank()
1817 javaCore sdkLinkType = iota
1818 javaSdk
1819 javaSystem
1820 javaModule
1821 javaSystemServer
1822 javaPlatform
1823)
1824
1825func (lt sdkLinkType) String() string {
1826 switch lt {
1827 case javaCore:
1828 return "core Java API"
1829 case javaSdk:
1830 return "Android API"
1831 case javaSystem:
1832 return "system API"
1833 case javaModule:
1834 return "module API"
1835 case javaSystemServer:
1836 return "system server API"
1837 case javaPlatform:
1838 return "private API"
1839 default:
1840 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1841 }
1842}
1843
1844// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1845// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1846// can't statically depend on modules that use Platform API.
1847func (lt sdkLinkType) rank() int {
1848 return int(lt)
1849}
1850
1851type moduleWithSdkDep interface {
1852 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001853 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001854}
1855
Jiyong Park92315372021-04-02 08:45:46 +09001856func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001857 switch name {
1858 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1859 "stub-annotations", "private-stub-annotations-jar",
1860 "core-lambda-stubs", "core-generated-annotation-stubs":
1861 return javaCore, true
1862 case "android_stubs_current":
1863 return javaSdk, true
1864 case "android_system_stubs_current":
1865 return javaSystem, true
1866 case "android_module_lib_stubs_current":
1867 return javaModule, true
1868 case "android_system_server_stubs_current":
1869 return javaSystemServer, true
1870 case "android_test_stubs_current":
1871 return javaSystem, true
1872 }
1873
1874 if stub, linkType := moduleStubLinkType(name); stub {
1875 return linkType, true
1876 }
1877
Jiyong Park92315372021-04-02 08:45:46 +09001878 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001879 switch ver.Kind {
1880 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001881 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001882 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001883 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001884 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001885 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001886 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001888 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001889 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001890 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001891 return javaPlatform, false
1892 }
1893
Jiyong Parkf1691d22021-03-29 20:11:58 +09001894 if !ver.Valid() {
1895 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001896 }
1897 return javaSdk, false
1898}
1899
1900// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1901// this module's. See the comment on rank() for details and an example.
1902func (j *Module) checkSdkLinkType(
1903 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1904 if ctx.Host() {
1905 return
1906 }
1907
Jiyong Park92315372021-04-02 08:45:46 +09001908 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001909 if stubs {
1910 return
1911 }
Jiyong Park92315372021-04-02 08:45:46 +09001912 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001913
1914 if myLinkType.rank() < depLinkType.rank() {
1915 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1916 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1917 "property of the source or target module so that target module is built "+
1918 "with the same or smaller API set when compared to the source.",
1919 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1920 }
1921}
1922
1923func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1924 var deps deps
1925
1926 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001927 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001928 if sdkDep.invalidVersion {
1929 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1930 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1931 } else if sdkDep.useFiles {
1932 // sdkDep.jar is actually equivalent to turbine header.jar.
1933 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001934 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001935 deps.aidlPreprocess = sdkDep.aidl
1936 } else {
1937 deps.aidlPreprocess = sdkDep.aidl
1938 }
1939 }
1940
Jiyong Park92315372021-04-02 08:45:46 +09001941 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001942
1943 ctx.VisitDirectDeps(func(module android.Module) {
1944 otherName := ctx.OtherModuleName(module)
1945 tag := ctx.OtherModuleDependencyTag(module)
1946
1947 if IsJniDepTag(tag) {
1948 // Handled by AndroidApp.collectAppDeps
1949 return
1950 }
1951 if tag == certificateTag {
1952 // Handled by AndroidApp.collectAppDeps
1953 return
1954 }
1955
1956 if dep, ok := module.(SdkLibraryDependency); ok {
1957 switch tag {
1958 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001959 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1960 deps.classpath = append(deps.classpath, depHeaderJars...)
1961 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001962 case staticLibTag:
1963 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1964 }
1965 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1966 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1967 if sdkLinkType != javaPlatform &&
1968 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1969 // dep is a sysprop implementation library, but this module is not linking against
1970 // the platform, so it gets the sysprop public stubs library instead. Replace
1971 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1972 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1973 dep = syspropDep.JavaInfo
1974 }
1975 switch tag {
1976 case bootClasspathTag:
1977 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1978 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001979 if _, ok := module.(*Plugin); ok {
1980 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1981 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001982 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001983 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001984 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1985 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1986 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1987 case java9LibTag:
1988 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1989 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001990 if _, ok := module.(*Plugin); ok {
1991 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1992 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001993 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1994 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1995 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1996 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1997 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1998 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1999 // Turbine doesn't run annotation processors, so any module that uses an
2000 // annotation processor that generates API is incompatible with the turbine
2001 // optimization.
2002 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2003 case pluginTag:
2004 if plugin, ok := module.(*Plugin); ok {
2005 if plugin.pluginProperties.Processor_class != nil {
2006 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2007 } else {
2008 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2009 }
2010 // Turbine doesn't run annotation processors, so any module that uses an
2011 // annotation processor that generates API is incompatible with the turbine
2012 // optimization.
2013 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2014 } else {
2015 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2016 }
2017 case errorpronePluginTag:
2018 if _, ok := module.(*Plugin); ok {
2019 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2020 } else {
2021 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2022 }
2023 case exportedPluginTag:
2024 if plugin, ok := module.(*Plugin); ok {
2025 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2026 if plugin.pluginProperties.Processor_class != nil {
2027 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2028 }
2029 // Turbine doesn't run annotation processors, so any module that uses an
2030 // annotation processor that generates API is incompatible with the turbine
2031 // optimization.
2032 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2033 } else {
2034 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2035 }
2036 case kotlinStdlibTag:
2037 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2038 case kotlinAnnotationsTag:
2039 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002040 case kotlinPluginTag:
2041 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002042 case syspropPublicStubDepTag:
2043 // This is a sysprop implementation library, forward the JavaInfoProvider from
2044 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2045 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2046 JavaInfo: dep,
2047 })
2048 }
2049 } else if dep, ok := module.(android.SourceFileProducer); ok {
2050 switch tag {
2051 case libTag:
2052 checkProducesJars(ctx, dep)
2053 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002054 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002055 case staticLibTag:
2056 checkProducesJars(ctx, dep)
2057 deps.classpath = append(deps.classpath, dep.Srcs()...)
2058 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2059 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2060 }
2061 } else {
2062 switch tag {
2063 case bootClasspathTag:
2064 // If a system modules dependency has been added to the bootclasspath
2065 // then add its libs to the bootclasspath.
2066 sm := module.(SystemModulesProvider)
2067 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2068
2069 case systemModulesTag:
2070 if deps.systemModules != nil {
2071 panic("Found two system module dependencies")
2072 }
2073 sm := module.(SystemModulesProvider)
2074 outputDir, outputDeps := sm.OutputDirAndDeps()
2075 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002076
2077 case instrumentationForTag:
2078 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 -07002079 }
2080 }
2081
2082 addCLCFromDep(ctx, module, j.classLoaderContexts)
2083 })
2084
2085 return deps
2086}
2087
2088func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2089 deps.processorPath = append(deps.processorPath, pluginJars...)
2090 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2091}
2092
2093// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2094// this interface.
2095type ProvidesUsesLib interface {
2096 ProvidesUsesLib() *string
2097}
2098
2099func (j *Module) ProvidesUsesLib() *string {
2100 return j.usesLibraryProperties.Provides_uses_lib
2101}
satayev1c564cc2021-05-25 19:50:30 +01002102
2103type ModuleWithStem interface {
2104 Stem() string
2105}
2106
2107var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002108
2109func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2110 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002111 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002112 if lib, ok := ctx.Module().(*Library); ok {
2113 javaLibraryBp2Build(ctx, lib)
2114 }
2115 case "java_binary_host":
2116 if binary, ok := ctx.Module().(*Binary); ok {
2117 javaBinaryHostBp2Build(ctx, binary)
2118 }
2119 }
Wei Libafb6d62021-12-10 03:14:59 -08002120}