blob: 995d257f9c305fe7906c11d526cd4b32f297835b [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.
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000193 // Defaults to private.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000194 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000195 // 1) numerical API level, "current", "none", or "core_platform"
196 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
197 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
198 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700199 Sdk_version *string
200
201 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000202 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700203 Min_sdk_version *string
204
satayev0a420e72021-11-29 17:25:52 +0000205 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
206 // Defaults to empty string "". See sdk_version for possible values.
207 Max_sdk_version *string
208
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
866 if Bool(j.deviceProperties.Aidl.Generate_traces) {
867 flags = append(flags, "-t")
868 }
869
870 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
871 flags = append(flags, "--transaction_names")
872 }
873
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100874 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
875 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
876 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
877 }
878
Jooyung Han07f70c02021-11-06 07:08:45 +0900879 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
880 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
881
Jaewoong Jung26342642021-03-17 15:56:23 -0700882 return strings.Join(flags, " "), deps
883}
884
885func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
886
887 var flags javaBuilderFlags
888
889 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900890 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700891
Cole Faust2b1536e2021-06-18 12:25:54 -0700892 epEnabled := j.properties.Errorprone.Enabled
893 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700894 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
895 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
896 }
897
898 errorProneFlags := []string{
899 "-Xplugin:ErrorProne",
900 "${config.ErrorProneChecks}",
901 }
902 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
903
Colin Cross8bf6cad2022-02-28 13:07:03 -0800904 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700905 "'" + strings.Join(errorProneFlags, " ") + "'"
906 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
907 }
908
909 // classpath
910 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
911 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700912 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700913 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
914 flags.processorPath = append(flags.processorPath, deps.processorPath...)
915 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
916
917 flags.processors = append(flags.processors, deps.processorClasses...)
918 flags.processors = android.FirstUniqueStrings(flags.processors)
919
920 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900921 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700922 // Give host-side tools a version of OpenJDK's standard libraries
923 // close to what they're targeting. As of Dec 2017, AOSP is only
924 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
925 //
926 // When building with OpenJDK 8, the following should have no
927 // effect since those jars would be available by default.
928 //
929 // When building with OpenJDK 9 but targeting a version < 1.8,
930 // putting them on the bootclasspath means that:
931 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
932 // b) references to existing APIs are not reinterpreted in an
933 // OpenJDK 9-specific way, eg. calls to subclasses of
934 // java.nio.Buffer as in http://b/70862583
935 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
936 flags.bootClasspath = append(flags.bootClasspath,
937 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
938 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
939 if Bool(j.properties.Use_tools_jar) {
940 flags.bootClasspath = append(flags.bootClasspath,
941 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
942 }
943 }
944
945 // systemModules
946 flags.systemModules = deps.systemModules
947
Jaewoong Jung26342642021-03-17 15:56:23 -0700948 return flags
949}
950
951func (j *Module) collectJavacFlags(
952 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
953 // javac flags.
954 javacFlags := j.properties.Javacflags
955
956 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
957 // For non-host binaries, override the -g flag passed globally to remove
958 // local variable debug info to reduce disk and memory usage.
959 javacFlags = append(javacFlags, "-g:source,lines")
960 }
961 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
962
963 if flags.javaVersion.usesJavaModules() {
964 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
965
966 if j.properties.Patch_module != nil {
967 // Manually specify build directory in case it is not under the repo root.
968 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
969 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200970 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700971
972 // b/150878007
973 //
974 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
975 // execution root for --patch-module. If this javac command line is
976 // invoked within Bazel's execution root working directory, the top
977 // level directories (e.g. libcore/, tools/, frameworks/) are all
978 // symlinks. JDK9 javac does not traverse into symlinks, which causes
979 // --patch-module to fail source file lookups when invoked in the
980 // execution root.
981 //
982 // Short of patching javac or enumerating *all* directories as possible
983 // input dirs, manually add the top level dir of the source files to be
984 // compiled.
985 topLevelDirs := map[string]bool{}
986 for _, srcFilePath := range srcFiles {
987 srcFileParts := strings.Split(srcFilePath.String(), "/")
988 // Ignore source files that are already in the top level directory
989 // as well as generated files in the out directory. The out
990 // directory may be an absolute path, which means srcFileParts[0] is the
991 // empty string, so check that as well. Note that "out" in Bazel's execution
992 // root is *not* a symlink, which doesn't cause problems for --patch-modules
993 // anyway, so it's fine to not apply this workaround for generated
994 // source files.
995 if len(srcFileParts) > 1 &&
996 srcFileParts[0] != "" &&
997 srcFileParts[0] != "out" {
998 topLevelDirs[srcFileParts[0]] = true
999 }
1000 }
1001 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
1002
1003 classPath := flags.classpath.FormJavaClassPath("")
1004 if classPath != "" {
1005 patchPaths = append(patchPaths, classPath)
1006 }
1007 javacFlags = append(
1008 javacFlags,
1009 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1010 }
1011 }
1012
1013 if len(javacFlags) > 0 {
1014 // optimization.
1015 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1016 flags.javacFlags = "$javacFlags"
1017 }
1018
1019 return flags
1020}
1021
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001022func (j *Module) AddJSONData(d *map[string]interface{}) {
1023 (&j.ModuleBase).AddJSONData(d)
1024 (*d)["Java"] = map[string]interface{}{
1025 "SourceExtensions": j.sourceExtensions,
1026 }
1027
1028}
1029
Jaewoong Jung26342642021-03-17 15:56:23 -07001030func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1031 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1032
1033 deps := j.collectDeps(ctx)
1034 flags := j.collectBuilderFlags(ctx, deps)
1035
1036 if flags.javaVersion.usesJavaModules() {
1037 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1038 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001039
Jaewoong Jung26342642021-03-17 15:56:23 -07001040 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001041 j.sourceExtensions = []string{}
1042 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1043 if hasSrcExt(srcFiles.Strings(), ext) {
1044 j.sourceExtensions = append(j.sourceExtensions, ext)
1045 }
1046 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001047 if hasSrcExt(srcFiles.Strings(), ".proto") {
1048 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1049 }
1050
1051 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1052 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1053 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1054 }
1055
Sam Delmerico2351eac2022-05-24 17:10:02 +00001056 aidlSrcs := srcFiles.FilterByExt(".aidl")
1057 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1058
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001059 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001060 srcFiles = j.genSources(ctx, srcFiles, flags)
1061
1062 // Collect javac flags only after computing the full set of srcFiles to
1063 // ensure that the --patch-module lookup paths are complete.
1064 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1065
1066 srcJars := srcFiles.FilterByExt(".srcjar")
1067 srcJars = append(srcJars, deps.srcJars...)
1068 if aaptSrcJar != nil {
1069 srcJars = append(srcJars, aaptSrcJar)
1070 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001071 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001072
1073 if j.properties.Jarjar_rules != nil {
1074 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1075 }
1076
1077 jarName := ctx.ModuleName() + ".jar"
1078
1079 javaSrcFiles := srcFiles.FilterByExt(".java")
1080 var uniqueSrcFiles android.Paths
1081 set := make(map[string]bool)
1082 for _, v := range javaSrcFiles {
1083 if _, found := set[v.String()]; !found {
1084 set[v.String()] = true
1085 uniqueSrcFiles = append(uniqueSrcFiles, v)
1086 }
1087 }
1088
Colin Crossb5db4012022-03-28 17:12:39 -07001089 // We don't currently run annotation processors in turbine, which means we can't use turbine
1090 // generated header jars when an annotation processor that generates API is enabled. One
1091 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1092 // is used to run all of the annotation processors.
1093 disableTurbine := deps.disableTurbine
1094
Jaewoong Jung26342642021-03-17 15:56:23 -07001095 // Collect .java files for AIDEGen
1096 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1097
1098 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001099 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001100
1101 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001102 // When using kotlin sources turbine is used to generate annotation processor sources,
1103 // including for annotation processors that generate API, so we can use turbine for
1104 // java sources too.
1105 disableTurbine = false
1106
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 // user defined kotlin flags.
1108 kotlincFlags := j.properties.Kotlincflags
1109 CheckKotlincFlags(ctx, kotlincFlags)
1110
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001111 // Workaround for KT-46512
1112 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001113
1114 // If there are kotlin files, compile them first but pass all the kotlin and java files
1115 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1116 // won't emit any classes for them.
1117 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1118 if ctx.Device() {
1119 kotlincFlags = append(kotlincFlags, "-no-jdk")
1120 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001121
1122 for _, plugin := range deps.kotlinPlugins {
1123 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1124 }
1125 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1126
Jaewoong Jung26342642021-03-17 15:56:23 -07001127 if len(kotlincFlags) > 0 {
1128 // optimization.
1129 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1130 flags.kotlincFlags += "$kotlincFlags"
1131 }
1132
1133 var kotlinSrcFiles android.Paths
1134 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1135 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1136
1137 // Collect .kt files for AIDEGen
1138 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1139 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1140
1141 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1142 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1143
1144 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1145 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1146
Isaac Chioua23d9942022-04-06 06:14:38 +00001147 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001148 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001149 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1150 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1151 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1152 srcJars = append(srcJars, kaptSrcJar)
1153 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 // Disable annotation processing in javac, it's already been handled by kapt
1155 flags.processorPath = nil
1156 flags.processors = nil
1157 }
1158
1159 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001160 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1161 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001162 if ctx.Failed() {
1163 return
1164 }
1165
Isaac Chioua23d9942022-04-06 06:14:38 +00001166 // Make javac rule depend on the kotlinc rule
1167 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1168
Jaewoong Jung26342642021-03-17 15:56:23 -07001169 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001170 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1171
Jaewoong Jung26342642021-03-17 15:56:23 -07001172 // Jar kotlin classes into the final jar after javac
1173 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1174 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001175 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001176 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001177 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001178 } else {
1179 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001180 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001181 }
1182 }
1183
1184 jars := append(android.Paths(nil), kotlinJars...)
1185
1186 // Store the list of .java files that was passed to javac
1187 j.compiledJavaSrcs = uniqueSrcFiles
1188 j.compiledSrcJars = srcJars
1189
1190 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001191 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001192 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1194 enableSharding = true
1195 // Formerly, there was a check here that prevented annotation processors
1196 // from being used when sharding was enabled, as some annotation processors
1197 // do not function correctly in sharded environments. It was removed to
1198 // allow for the use of annotation processors that do function correctly
1199 // with sharding enabled. See: b/77284273.
1200 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001201 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001202 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001203 if ctx.Failed() {
1204 return
1205 }
1206 }
1207 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001208 hasErrorproneableFiles := false
1209 for _, ext := range j.sourceExtensions {
1210 if ext != ".proto" && ext != ".aidl" {
1211 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1212 // compile, and it's not useful to have warnings on these generated sources.
1213 hasErrorproneableFiles = true
1214 break
1215 }
1216 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001217 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001218 if Bool(j.properties.Errorprone.Enabled) {
1219 // If error-prone is enabled, enable errorprone flags on the regular
1220 // build.
1221 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001222 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001223 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1224 // a new jar file just for compiling with the errorprone compiler to.
1225 // This is because we don't want to cause the java files to get completely
1226 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1227 // We also don't want to run this if errorprone is enabled by default for
1228 // this module, or else we could have duplicated errorprone messages.
1229 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001230 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001231
1232 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1233 "errorprone", "errorprone")
1234
Jaewoong Jung26342642021-03-17 15:56:23 -07001235 extraJarDeps = append(extraJarDeps, errorprone)
1236 }
1237
1238 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001239 if headerJarFileWithoutDepsOrJarjar != nil {
1240 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1241 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001242 shardSize := int(*(j.properties.Javac_shard_size))
1243 var shardSrcs []android.Paths
1244 if len(uniqueSrcFiles) > 0 {
1245 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1246 for idx, shardSrc := range shardSrcs {
1247 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1248 nil, flags, extraJarDeps)
1249 jars = append(jars, classes)
1250 }
1251 }
1252 if len(srcJars) > 0 {
1253 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1254 nil, srcJars, flags, extraJarDeps)
1255 jars = append(jars, classes)
1256 }
1257 } else {
1258 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1259 jars = append(jars, classes)
1260 }
1261 if ctx.Failed() {
1262 return
1263 }
1264 }
1265
1266 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1267
1268 var includeSrcJar android.WritablePath
1269 if Bool(j.properties.Include_srcs) {
1270 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1271 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1272 }
1273
1274 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1275 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1276 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1277 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1278
1279 var resArgs []string
1280 var resDeps android.Paths
1281
1282 resArgs = append(resArgs, dirArgs...)
1283 resDeps = append(resDeps, dirDeps...)
1284
1285 resArgs = append(resArgs, fileArgs...)
1286 resDeps = append(resDeps, fileDeps...)
1287
1288 resArgs = append(resArgs, extraArgs...)
1289 resDeps = append(resDeps, extraDeps...)
1290
1291 if len(resArgs) > 0 {
1292 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1293 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1294 j.resourceJar = resourceJar
1295 if ctx.Failed() {
1296 return
1297 }
1298 }
1299
1300 var resourceJars android.Paths
1301 if j.resourceJar != nil {
1302 resourceJars = append(resourceJars, j.resourceJar)
1303 }
1304 if Bool(j.properties.Include_srcs) {
1305 resourceJars = append(resourceJars, includeSrcJar)
1306 }
1307 resourceJars = append(resourceJars, deps.staticResourceJars...)
1308
1309 if len(resourceJars) > 1 {
1310 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1311 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1312 false, nil, nil)
1313 j.resourceJar = combinedJar
1314 } else if len(resourceJars) == 1 {
1315 j.resourceJar = resourceJars[0]
1316 }
1317
1318 if len(deps.staticJars) > 0 {
1319 jars = append(jars, deps.staticJars...)
1320 }
1321
1322 manifest := j.overrideManifest
1323 if !manifest.Valid() && j.properties.Manifest != nil {
1324 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1325 }
1326
1327 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1328 if len(services) > 0 {
1329 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1330 var zipargs []string
1331 for _, file := range services {
1332 serviceFile := file.String()
1333 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1334 }
1335 rule := zip
1336 args := map[string]string{
1337 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1338 }
1339 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1340 rule = zipRE
1341 args["implicits"] = strings.Join(services.Strings(), ",")
1342 }
1343 ctx.Build(pctx, android.BuildParams{
1344 Rule: rule,
1345 Output: servicesJar,
1346 Implicits: services,
1347 Args: args,
1348 })
1349 jars = append(jars, servicesJar)
1350 }
1351
1352 // Combine the classes built from sources, any manifests, and any static libraries into
1353 // classes.jar. If there is only one input jar this step will be skipped.
1354 var outputFile android.OutputPath
1355
1356 if len(jars) == 1 && !manifest.Valid() {
1357 // Optimization: skip the combine step as there is nothing to do
1358 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1359 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1360 // any if len(jars) == 1.
1361
1362 // Transform the single path to the jar into an OutputPath as that is required by the following
1363 // code.
1364 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1365 // The path contains an embedded OutputPath so reuse that.
1366 outputFile = moduleOutPath.OutputPath
1367 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1368 // The path is an OutputPath so reuse it directly.
1369 outputFile = outputPath
1370 } else {
1371 // The file is not in the out directory so create an OutputPath into which it can be copied
1372 // and which the following code can use to refer to it.
1373 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1374 ctx.Build(pctx, android.BuildParams{
1375 Rule: android.Cp,
1376 Input: jars[0],
1377 Output: combinedJar,
1378 })
1379 outputFile = combinedJar.OutputPath
1380 }
1381 } else {
1382 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1383 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1384 false, nil, nil)
1385 outputFile = combinedJar.OutputPath
1386 }
1387
1388 // jarjar implementation jar if necessary
1389 if j.expandJarjarRules != nil {
1390 // Transform classes.jar into classes-jarjar.jar
1391 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1392 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1393 outputFile = jarjarFile
1394
1395 // jarjar resource jar if necessary
1396 if j.resourceJar != nil {
1397 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1398 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1399 j.resourceJar = resourceJarJarFile
1400 }
1401
1402 if ctx.Failed() {
1403 return
1404 }
1405 }
1406
1407 // Check package restrictions if necessary.
1408 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001409 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001410 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001411
1412 // Create a rule to copy the output jar to another path and add a validate dependency that
1413 // will check that the jar only contains the permitted packages. The new location will become
1414 // the output file of this module.
1415 inputFile := outputFile
1416 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1417 ctx.Build(pctx, android.BuildParams{
1418 Rule: android.Cp,
1419 Input: inputFile,
1420 Output: outputFile,
1421 // Make sure that any dependency on the output file will cause ninja to run the package check
1422 // rule.
1423 Validation: pkgckFile,
1424 })
1425
1426 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001427 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001428
1429 if ctx.Failed() {
1430 return
1431 }
1432 }
1433
1434 j.implementationJarFile = outputFile
1435 if j.headerJarFile == nil {
1436 j.headerJarFile = j.implementationJarFile
1437 }
1438
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001439 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1440 specs := j.jacocoModuleToZipCommand(ctx)
1441 if ctx.Failed() {
1442 return
1443 }
1444
Jaewoong Jung26342642021-03-17 15:56:23 -07001445 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001446 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001447 }
1448
1449 // merge implementation jar with resources if necessary
1450 implementationAndResourcesJar := outputFile
1451 if j.resourceJar != nil {
1452 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1453 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1454 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1455 false, nil, nil)
1456 implementationAndResourcesJar = combinedJar
1457 }
1458
1459 j.implementationAndResourcesJar = implementationAndResourcesJar
1460
1461 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001462 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001463 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1464 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001465 if compileDex == nil {
1466 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001467 }
1468 if j.deviceProperties.Hostdex == nil {
1469 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1470 }
1471 }
1472
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001473 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001474 if j.hasCode(ctx) {
1475 if j.shouldInstrumentStatic(ctx) {
1476 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1477 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1478 }
1479 // Dex compilation
1480 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001481 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001482 if ctx.Failed() {
1483 return
1484 }
1485
Jaewoong Jung26342642021-03-17 15:56:23 -07001486 // merge dex jar with resources if necessary
1487 if j.resourceJar != nil {
1488 jars := android.Paths{dexOutputFile, j.resourceJar}
1489 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1490 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1491 false, nil, nil)
1492 if *j.dexProperties.Uncompress_dex {
1493 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1494 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1495 dexOutputFile = combinedAlignedJar
1496 } else {
1497 dexOutputFile = combinedJar
1498 }
1499 }
1500
Paul Duffin4de94502021-05-16 05:21:16 +01001501 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001502
1503 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001504
1505 // Encode hidden API flags in dex file, if needed.
1506 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1507
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001508 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001509
1510 // Dexpreopting
1511 j.dexpreopt(ctx, dexOutputFile)
1512
1513 outputFile = dexOutputFile
1514 } else {
1515 // There is no code to compile into a dex jar, make sure the resources are propagated
1516 // to the APK if this is an app.
1517 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001518 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001519 }
1520
1521 if ctx.Failed() {
1522 return
1523 }
1524 } else {
1525 outputFile = implementationAndResourcesJar
1526 }
1527
1528 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001529 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001530 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001531 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001532 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001533 // When running metalava, we pass --version-codename. When that value
1534 // is not REL, metalava will add 1 to the --current-version argument.
1535 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1536 // branch) and the codename is REL, except potentially on the most
1537 // recent non-master branch. On that branch, it goes through two other
1538 // phases before it gets to the phase previously described:
1539 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1540 // is not rel. This happens for most of the internal branch's life
1541 // while the branch has been cut but is still under active development.
1542 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1543 // REL. This happens briefly during the release process. During this
1544 // state the code to add --current-version is commented out, and then
1545 // that commenting out is reverted after the codename is set to REL.
1546 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1547 // prior version and the codename is always non-REL.
1548 //
1549 // We need to add one here to match metalava adding 1. Technically
1550 // this means that in the state described in the second bullet point
1551 // above, this number is 1 higher than it should be.
1552 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001553 }
1554 }
1555
1556 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001557 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1558 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001559 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1560 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001561 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1562 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1563 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001564 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001565 j.linter.javaLanguageLevel = flags.javaVersion.String()
1566 j.linter.kotlinLanguageLevel = "1.3"
1567 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1568 j.linter.buildModuleReportZip = true
1569 }
1570 j.linter.lint(ctx)
1571 }
1572
1573 ctx.CheckbuildFile(outputFile)
1574
1575 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1576 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1577 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1578 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1579 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1580 AidlIncludeDirs: j.exportAidlIncludeDirs,
1581 SrcJarArgs: j.srcJarArgs,
1582 SrcJarDeps: j.srcJarDeps,
1583 ExportedPlugins: j.exportedPluginJars,
1584 ExportedPluginClasses: j.exportedPluginClasses,
1585 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1586 JacocoReportClassesFile: j.jacocoReportClassesFile,
1587 })
1588
1589 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1590 j.outputFile = outputFile.WithoutRel()
1591}
1592
Colin Crossa1ff7c62021-09-17 14:11:52 -07001593func (j *Module) useCompose() bool {
1594 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1595}
1596
Cole Faust75fffb12021-06-13 15:23:16 -07001597// Returns a copy of the supplied flags, but with all the errorprone-related
1598// fields copied to the regular build's fields.
1599func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1600 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1601
1602 if len(flags.errorProneExtraJavacFlags) > 0 {
1603 if len(flags.javacFlags) > 0 {
1604 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1605 } else {
1606 flags.javacFlags = flags.errorProneExtraJavacFlags
1607 }
1608 }
1609 return flags
1610}
1611
Jaewoong Jung26342642021-03-17 15:56:23 -07001612func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1613 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1614
1615 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1616 if idx >= 0 {
1617 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1618 jarName += strconv.Itoa(idx)
1619 }
1620
1621 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1622 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1623
1624 if ctx.Config().EmitXrefRules() {
1625 extractionFile := android.PathForModuleOut(ctx, kzipName)
1626 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1627 j.kytheFiles = append(j.kytheFiles, extractionFile)
1628 }
1629
1630 return classes
1631}
1632
1633// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1634// since some of these flags may be used internally.
1635func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1636 for _, flag := range flags {
1637 flag = strings.TrimSpace(flag)
1638
1639 if !strings.HasPrefix(flag, "-") {
1640 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1641 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1642 ctx.PropertyErrorf("kotlincflags",
1643 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1644 } else if inList(flag, config.KotlincIllegalFlags) {
1645 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1646 } else if flag == "-include-runtime" {
1647 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1648 } else {
1649 args := strings.Split(flag, " ")
1650 if args[0] == "-kotlin-home" {
1651 ctx.PropertyErrorf("kotlincflags",
1652 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1653 }
1654 }
1655 }
1656}
1657
1658func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1659 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001660 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001661
1662 var jars android.Paths
1663 if len(srcFiles) > 0 || len(srcJars) > 0 {
1664 // Compile java sources into turbine.jar.
1665 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1666 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1667 if ctx.Failed() {
1668 return nil, nil
1669 }
1670 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001671 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001672 }
1673
1674 jars = append(jars, extraJars...)
1675
1676 // Combine any static header libraries into classes-header.jar. If there is only
1677 // one input jar this step will be skipped.
1678 jars = append(jars, deps.staticHeaderJars...)
1679
1680 // we cannot skip the combine step for now if there is only one jar
1681 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1682 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1683 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1684 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001685 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001686
1687 if j.expandJarjarRules != nil {
1688 // Transform classes.jar into classes-jarjar.jar
1689 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001690 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1691 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001692 if ctx.Failed() {
1693 return nil, nil
1694 }
1695 }
1696
Colin Cross3d56ed52021-11-18 22:23:12 -08001697 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001698}
1699
1700func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001701 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001702
1703 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1704 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1705
1706 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1707
1708 j.jacocoReportClassesFile = jacocoReportClassesFile
1709
1710 return instrumentedJar
1711}
1712
1713func (j *Module) HeaderJars() android.Paths {
1714 if j.headerJarFile == nil {
1715 return nil
1716 }
1717 return android.Paths{j.headerJarFile}
1718}
1719
1720func (j *Module) ImplementationJars() android.Paths {
1721 if j.implementationJarFile == nil {
1722 return nil
1723 }
1724 return android.Paths{j.implementationJarFile}
1725}
1726
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001727func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 return j.dexJarFile
1729}
1730
1731func (j *Module) DexJarInstallPath() android.Path {
1732 return j.installFile
1733}
1734
1735func (j *Module) ImplementationAndResourcesJars() android.Paths {
1736 if j.implementationAndResourcesJar == nil {
1737 return nil
1738 }
1739 return android.Paths{j.implementationAndResourcesJar}
1740}
1741
1742func (j *Module) AidlIncludeDirs() android.Paths {
1743 // exportAidlIncludeDirs is type android.Paths already
1744 return j.exportAidlIncludeDirs
1745}
1746
1747func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1748 return j.classLoaderContexts
1749}
1750
1751// Collect information for opening IDE project files in java/jdeps.go.
1752func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1753 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1754 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1755 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1756 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1757 if j.expandJarjarRules != nil {
1758 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1759 }
1760 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001761 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1762 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001763}
1764
1765func (j *Module) CompilerDeps() []string {
1766 jdeps := []string{}
1767 jdeps = append(jdeps, j.properties.Libs...)
1768 jdeps = append(jdeps, j.properties.Static_libs...)
1769 return jdeps
1770}
1771
1772func (j *Module) hasCode(ctx android.ModuleContext) bool {
1773 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1774 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1775}
1776
1777// Implements android.ApexModule
1778func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1779 return j.depIsInSameApex(ctx, dep)
1780}
1781
1782// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001783func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001784 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001785 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001786 return fmt.Errorf("min_sdk_version is not specified")
1787 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001788 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001789 return nil
1790 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001791 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1792 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001793 }
1794 return nil
1795}
1796
1797func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001798 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001799}
1800
Jaewoong Jung26342642021-03-17 15:56:23 -07001801func (j *Module) JacocoReportClassesFile() android.Path {
1802 return j.jacocoReportClassesFile
1803}
1804
1805func (j *Module) IsInstallable() bool {
1806 return Bool(j.properties.Installable)
1807}
1808
1809type sdkLinkType int
1810
1811const (
1812 // TODO(jiyong) rename these for better readability. Make the allowed
1813 // and disallowed link types explicit
1814 // order is important here. See rank()
1815 javaCore sdkLinkType = iota
1816 javaSdk
1817 javaSystem
1818 javaModule
1819 javaSystemServer
1820 javaPlatform
1821)
1822
1823func (lt sdkLinkType) String() string {
1824 switch lt {
1825 case javaCore:
1826 return "core Java API"
1827 case javaSdk:
1828 return "Android API"
1829 case javaSystem:
1830 return "system API"
1831 case javaModule:
1832 return "module API"
1833 case javaSystemServer:
1834 return "system server API"
1835 case javaPlatform:
1836 return "private API"
1837 default:
1838 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1839 }
1840}
1841
1842// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1843// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1844// can't statically depend on modules that use Platform API.
1845func (lt sdkLinkType) rank() int {
1846 return int(lt)
1847}
1848
1849type moduleWithSdkDep interface {
1850 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001851 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001852}
1853
Jiyong Park92315372021-04-02 08:45:46 +09001854func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001855 switch name {
1856 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1857 "stub-annotations", "private-stub-annotations-jar",
1858 "core-lambda-stubs", "core-generated-annotation-stubs":
1859 return javaCore, true
1860 case "android_stubs_current":
1861 return javaSdk, true
1862 case "android_system_stubs_current":
1863 return javaSystem, true
1864 case "android_module_lib_stubs_current":
1865 return javaModule, true
1866 case "android_system_server_stubs_current":
1867 return javaSystemServer, true
1868 case "android_test_stubs_current":
1869 return javaSystem, true
1870 }
1871
1872 if stub, linkType := moduleStubLinkType(name); stub {
1873 return linkType, true
1874 }
1875
Jiyong Park92315372021-04-02 08:45:46 +09001876 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001877 switch ver.Kind {
1878 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001879 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001880 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001881 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001882 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001883 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001884 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001885 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001886 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001888 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001889 return javaPlatform, false
1890 }
1891
Jiyong Parkf1691d22021-03-29 20:11:58 +09001892 if !ver.Valid() {
1893 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001894 }
1895 return javaSdk, false
1896}
1897
1898// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1899// this module's. See the comment on rank() for details and an example.
1900func (j *Module) checkSdkLinkType(
1901 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1902 if ctx.Host() {
1903 return
1904 }
1905
Jiyong Park92315372021-04-02 08:45:46 +09001906 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001907 if stubs {
1908 return
1909 }
Jiyong Park92315372021-04-02 08:45:46 +09001910 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001911
1912 if myLinkType.rank() < depLinkType.rank() {
1913 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1914 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1915 "property of the source or target module so that target module is built "+
1916 "with the same or smaller API set when compared to the source.",
1917 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1918 }
1919}
1920
1921func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1922 var deps deps
1923
1924 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001925 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001926 if sdkDep.invalidVersion {
1927 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1928 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1929 } else if sdkDep.useFiles {
1930 // sdkDep.jar is actually equivalent to turbine header.jar.
1931 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001932 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001933 deps.aidlPreprocess = sdkDep.aidl
1934 } else {
1935 deps.aidlPreprocess = sdkDep.aidl
1936 }
1937 }
1938
Jiyong Park92315372021-04-02 08:45:46 +09001939 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001940
1941 ctx.VisitDirectDeps(func(module android.Module) {
1942 otherName := ctx.OtherModuleName(module)
1943 tag := ctx.OtherModuleDependencyTag(module)
1944
1945 if IsJniDepTag(tag) {
1946 // Handled by AndroidApp.collectAppDeps
1947 return
1948 }
1949 if tag == certificateTag {
1950 // Handled by AndroidApp.collectAppDeps
1951 return
1952 }
1953
1954 if dep, ok := module.(SdkLibraryDependency); ok {
1955 switch tag {
1956 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001957 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1958 deps.classpath = append(deps.classpath, depHeaderJars...)
1959 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001960 case staticLibTag:
1961 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1962 }
1963 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1964 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1965 if sdkLinkType != javaPlatform &&
1966 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1967 // dep is a sysprop implementation library, but this module is not linking against
1968 // the platform, so it gets the sysprop public stubs library instead. Replace
1969 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1970 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1971 dep = syspropDep.JavaInfo
1972 }
1973 switch tag {
1974 case bootClasspathTag:
1975 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1976 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001977 if _, ok := module.(*Plugin); ok {
1978 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1979 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001980 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001981 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001982 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1983 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1984 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1985 case java9LibTag:
1986 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1987 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001988 if _, ok := module.(*Plugin); ok {
1989 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1990 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001991 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1992 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1993 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1994 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1995 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1996 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1997 // Turbine doesn't run annotation processors, so any module that uses an
1998 // annotation processor that generates API is incompatible with the turbine
1999 // optimization.
2000 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2001 case pluginTag:
2002 if plugin, ok := module.(*Plugin); ok {
2003 if plugin.pluginProperties.Processor_class != nil {
2004 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2005 } else {
2006 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2007 }
2008 // Turbine doesn't run annotation processors, so any module that uses an
2009 // annotation processor that generates API is incompatible with the turbine
2010 // optimization.
2011 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2012 } else {
2013 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2014 }
2015 case errorpronePluginTag:
2016 if _, ok := module.(*Plugin); ok {
2017 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2018 } else {
2019 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2020 }
2021 case exportedPluginTag:
2022 if plugin, ok := module.(*Plugin); ok {
2023 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2024 if plugin.pluginProperties.Processor_class != nil {
2025 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2026 }
2027 // Turbine doesn't run annotation processors, so any module that uses an
2028 // annotation processor that generates API is incompatible with the turbine
2029 // optimization.
2030 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2031 } else {
2032 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2033 }
2034 case kotlinStdlibTag:
2035 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2036 case kotlinAnnotationsTag:
2037 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002038 case kotlinPluginTag:
2039 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002040 case syspropPublicStubDepTag:
2041 // This is a sysprop implementation library, forward the JavaInfoProvider from
2042 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2043 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2044 JavaInfo: dep,
2045 })
2046 }
2047 } else if dep, ok := module.(android.SourceFileProducer); ok {
2048 switch tag {
2049 case libTag:
2050 checkProducesJars(ctx, dep)
2051 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002052 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002053 case staticLibTag:
2054 checkProducesJars(ctx, dep)
2055 deps.classpath = append(deps.classpath, dep.Srcs()...)
2056 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2057 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2058 }
2059 } else {
2060 switch tag {
2061 case bootClasspathTag:
2062 // If a system modules dependency has been added to the bootclasspath
2063 // then add its libs to the bootclasspath.
2064 sm := module.(SystemModulesProvider)
2065 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2066
2067 case systemModulesTag:
2068 if deps.systemModules != nil {
2069 panic("Found two system module dependencies")
2070 }
2071 sm := module.(SystemModulesProvider)
2072 outputDir, outputDeps := sm.OutputDirAndDeps()
2073 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002074
2075 case instrumentationForTag:
2076 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 -07002077 }
2078 }
2079
2080 addCLCFromDep(ctx, module, j.classLoaderContexts)
2081 })
2082
2083 return deps
2084}
2085
2086func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2087 deps.processorPath = append(deps.processorPath, pluginJars...)
2088 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2089}
2090
2091// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2092// this interface.
2093type ProvidesUsesLib interface {
2094 ProvidesUsesLib() *string
2095}
2096
2097func (j *Module) ProvidesUsesLib() *string {
2098 return j.usesLibraryProperties.Provides_uses_lib
2099}
satayev1c564cc2021-05-25 19:50:30 +01002100
2101type ModuleWithStem interface {
2102 Stem() string
2103}
2104
2105var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002106
2107func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2108 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002109 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002110 if lib, ok := ctx.Module().(*Library); ok {
2111 javaLibraryBp2Build(ctx, lib)
2112 }
2113 case "java_binary_host":
2114 if binary, ok := ctx.Module().(*Binary); ok {
2115 javaBinaryHostBp2Build(ctx, binary)
2116 }
2117 }
Wei Libafb6d62021-12-10 03:14:59 -08002118}