blob: ab5a7d9a25bbc7f6b1944a00076c27e23c63bf9a [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
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800450 // list of unique .java and .kt source files
451 uniqueSrcFiles android.Paths
452
453 // list of srcjars that was passed to javac
454 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700455
456 // manifest file to use instead of properties.Manifest
457 overrideManifest android.OptionalPath
458
Jaewoong Jung26342642021-03-17 15:56:23 -0700459 // list of plugins that this java module is exporting
460 exportedPluginJars android.Paths
461
462 // list of plugins that this java module is exporting
463 exportedPluginClasses []string
464
465 // if true, the exported plugins generate API and require disabling turbine.
466 exportedDisableTurbine bool
467
468 // list of source files, collected from srcFiles with unique java and all kt files,
469 // will be used by android.IDEInfo struct
470 expandIDEInfoCompiledSrcs []string
471
472 // expanded Jarjar_rules
473 expandJarjarRules android.Path
474
Jaewoong Jung26342642021-03-17 15:56:23 -0700475 // Extra files generated by the module type to be added as java resources.
476 extraResources android.Paths
477
478 hiddenAPI
479 dexer
480 dexpreopter
481 usesLibrary
482 linter
483
484 // list of the xref extraction files
485 kytheFiles android.Paths
486
487 // Collect the module directory for IDE info in java/jdeps.go.
488 modulePaths []string
489
490 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900491
492 sdkVersion android.SdkSpec
493 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000494 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400495
496 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700497}
498
Jiyong Park92315372021-04-02 08:45:46 +0900499func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
500 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900501 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700502 return nil
503 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900504 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000505 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700506 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
507 } else {
508 // Treat stable core platform as stable.
509 return nil
510 }
511 } else {
512 return fmt.Errorf("non stable SDK %v", sdkVersion)
513 }
514}
515
516// checkSdkVersions enforces restrictions around SDK dependencies.
517func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
518 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900519 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900520 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700521 ctx.PropertyErrorf("sdk_version",
522 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
523 }
524 }
525 }
526
527 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
528 // See rank() for details.
529 ctx.VisitDirectDeps(func(module android.Module) {
530 tag := ctx.OtherModuleDependencyTag(module)
531 switch module.(type) {
532 // TODO(satayev): cover other types as well, e.g. imports
533 case *Library, *AndroidLibrary:
534 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400535 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700536 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
537 }
538 }
539 })
540}
541
542func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900543 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700544 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900545 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700546 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000547 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 -0700548 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000549 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 -0700550 }
551
552 }
553}
554
555func (j *Module) addHostProperties() {
556 j.AddProperties(
557 &j.properties,
558 &j.protoProperties,
559 &j.usesLibraryProperties,
560 )
561}
562
563func (j *Module) addHostAndDeviceProperties() {
564 j.addHostProperties()
565 j.AddProperties(
566 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900567 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700568 &j.dexer.dexProperties,
569 &j.dexpreoptProperties,
570 &j.linter.properties,
571 )
572}
573
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000574// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
575// makes it available through the hiddenAPIPropertyInfoProvider.
576func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
577 hiddenAPIInfo := newHiddenAPIPropertyInfo()
578
579 // Populate with flag file paths from the properties.
580 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
581
582 // Populate with package rules from the properties.
583 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
584
585 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
586}
587
Jaewoong Jung26342642021-03-17 15:56:23 -0700588func (j *Module) OutputFiles(tag string) (android.Paths, error) {
589 switch tag {
590 case "":
591 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
592 case android.DefaultDistTag:
593 return android.Paths{j.outputFile}, nil
594 case ".jar":
595 return android.Paths{j.implementationAndResourcesJar}, nil
596 case ".proguard_map":
597 if j.dexer.proguardDictionary.Valid() {
598 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
599 }
600 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
601 default:
602 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
603 }
604}
605
606var _ android.OutputFileProducer = (*Module)(nil)
607
608func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
609 initJavaModule(module, hod, false)
610}
611
612func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
613 initJavaModule(module, hod, true)
614}
615
616func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
617 multilib := android.MultilibCommon
618 if multiTargets {
619 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
620 } else {
621 android.InitAndroidArchModule(module, hod, multilib)
622 }
623 android.InitDefaultableModule(module)
624}
625
626func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
627 return j.properties.Instrument &&
628 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
629 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
630}
631
632func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000633 return j.properties.Supports_static_instrumentation &&
634 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700635 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
636 ctx.Config().UnbundledBuild())
637}
638
639func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
640 // Force enable the instrumentation for java code that is built for APEXes ...
641 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
642 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
643 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
644 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
645 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
646 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
647 return true
648 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
649 return true
650 }
651 }
652 return false
653}
654
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400655func (j *Module) setInstrument(value bool) {
656 j.properties.Instrument = value
657}
658
Jiyong Park92315372021-04-02 08:45:46 +0900659func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
660 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700661}
662
Jiyong Parkf1691d22021-03-29 20:11:58 +0900663func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700664 return proptools.String(j.deviceProperties.System_modules)
665}
666
Jiyong Park92315372021-04-02 08:45:46 +0900667func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700668 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900669 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700670 }
Jiyong Park92315372021-04-02 08:45:46 +0900671 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700672}
673
satayev0a420e72021-11-29 17:25:52 +0000674func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
675 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
676 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
677 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
678 return android.SdkSpecFrom(ctx, maxSdkVersion)
679}
680
William Loh5a082f92022-05-17 20:21:50 +0000681func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
682 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
683 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
684}
685
Jiyong Parkf1691d22021-03-29 20:11:58 +0900686func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900687 return j.minSdkVersion.Raw
688}
689
690func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
691 if j.deviceProperties.Target_sdk_version != nil {
692 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
693 }
694 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700695}
696
697func (j *Module) AvailableFor(what string) bool {
698 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
699 // Exception: for hostdex: true libraries, the platform variant is created
700 // even if it's not marked as available to platform. In that case, the platform
701 // variant is used only for the hostdex and not installed to the device.
702 return true
703 }
704 return j.ApexModuleBase.AvailableFor(what)
705}
706
707func (j *Module) deps(ctx android.BottomUpMutatorContext) {
708 if ctx.Device() {
709 j.linter.deps(ctx)
710
Jiyong Parkf1691d22021-03-29 20:11:58 +0900711 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700712
713 if j.deviceProperties.SyspropPublicStub != "" {
714 // This is a sysprop implementation library that has a corresponding sysprop public
715 // stubs library, and a dependency on it so that dependencies on the implementation can
716 // be forwarded to the public stubs library when necessary.
717 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
718 }
719 }
720
721 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
722 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
723
724 // Add dependency on libraries that provide additional hidden api annotations.
725 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
726
727 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
728 // Require java_sdk_library at inter-partition java dependency to ensure stable
729 // interface between partitions. If inter-partition java_library dependency is detected,
730 // raise build error because java_library doesn't have a stable interface.
731 //
732 // Inputs:
733 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
734 // if true, enable enforcement
735 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
736 // exception list of java_library names to allow inter-partition dependency
737 for idx := range j.properties.Libs {
738 if libDeps[idx] == nil {
739 continue
740 }
741
742 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
743 // java_sdk_library is always allowed at inter-partition dependency.
744 // So, skip check.
745 if _, ok := javaDep.(*SdkLibrary); ok {
746 continue
747 }
748
749 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
750 }
751 }
752 }
753
754 // For library dependencies that are component libraries (like stubs), add the implementation
755 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
756 for _, dep := range libDeps {
757 if dep != nil {
758 if component, ok := dep.(SdkLibraryComponentDependency); ok {
759 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100760 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100761 tag := usesLibReqTag
762 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
763 tag = usesLibOptTag
764 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100765 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700766 }
767 }
768 }
769 }
770
771 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
772 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
773 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
774
775 android.ProtoDeps(ctx, &j.protoProperties)
776 if j.hasSrcExt(".proto") {
777 protoDeps(ctx, &j.protoProperties)
778 }
779
780 if j.hasSrcExt(".kt") {
781 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
782 // Kotlin files
783 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
784 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700785 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700786 }
787
788 // Framework libraries need special handling in static coverage builds: they should not have
789 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
790 // the same jacoco classes coming from different bootclasspath jars.
791 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
792 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
793 j.properties.Instrument = true
794 }
795 } else if j.shouldInstrumentStatic(ctx) {
796 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
797 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700798
799 if j.useCompose() {
800 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
801 "androidx.compose.compiler_compiler-hosted")
802 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700803}
804
805func hasSrcExt(srcs []string, ext string) bool {
806 for _, src := range srcs {
807 if filepath.Ext(src) == ext {
808 return true
809 }
810 }
811
812 return false
813}
814
815func (j *Module) hasSrcExt(ext string) bool {
816 return hasSrcExt(j.properties.Srcs, ext)
817}
818
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100819func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
820 var flags string
821
822 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
823 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
824 flags = "-Wmissing-permission-annotation -Werror"
825 }
826 }
827 return flags
828}
829
Jaewoong Jung26342642021-03-17 15:56:23 -0700830func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000831 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700832
833 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
834 aidlIncludes = append(aidlIncludes,
835 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
836 aidlIncludes = append(aidlIncludes,
837 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
838
839 var flags []string
840 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000841 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700842
843 flags = append(flags, j.deviceProperties.Aidl.Flags...)
844
845 if aidlPreprocess.Valid() {
846 flags = append(flags, "-p"+aidlPreprocess.String())
847 deps = append(deps, aidlPreprocess.Path())
848 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000849 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700850 }
851
852 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000853 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700854 }
855
856 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000857 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700858 }
859
Sam Delmerico2351eac2022-05-24 17:10:02 +0000860 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700861 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000862 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700863 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000864 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
865 // add flags for dirs containing AIDL srcs that haven't been specified yet
866 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700867
Zim8774ae12022-08-17 11:46:34 +0100868 sdkVersion := (j.SdkVersion(ctx)).Kind
869 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform))
870 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700871 flags = append(flags, "-t")
872 }
873
874 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
875 flags = append(flags, "--transaction_names")
876 }
877
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100878 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
879 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
880 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
881 }
882
Jooyung Han07f70c02021-11-06 07:08:45 +0900883 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
884 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
885
Jaewoong Jung26342642021-03-17 15:56:23 -0700886 return strings.Join(flags, " "), deps
887}
888
889func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
890
891 var flags javaBuilderFlags
892
893 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900894 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700895
Cole Faust2b1536e2021-06-18 12:25:54 -0700896 epEnabled := j.properties.Errorprone.Enabled
897 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100898 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700899 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
900 }
901
902 errorProneFlags := []string{
903 "-Xplugin:ErrorProne",
904 "${config.ErrorProneChecks}",
905 }
906 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
907
Colin Cross8bf6cad2022-02-28 13:07:03 -0800908 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700909 "'" + strings.Join(errorProneFlags, " ") + "'"
910 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
911 }
912
913 // classpath
914 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
915 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700916 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700917 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
918 flags.processorPath = append(flags.processorPath, deps.processorPath...)
919 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
920
921 flags.processors = append(flags.processors, deps.processorClasses...)
922 flags.processors = android.FirstUniqueStrings(flags.processors)
923
924 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900925 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700926 // Give host-side tools a version of OpenJDK's standard libraries
927 // close to what they're targeting. As of Dec 2017, AOSP is only
928 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
929 //
930 // When building with OpenJDK 8, the following should have no
931 // effect since those jars would be available by default.
932 //
933 // When building with OpenJDK 9 but targeting a version < 1.8,
934 // putting them on the bootclasspath means that:
935 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
936 // b) references to existing APIs are not reinterpreted in an
937 // OpenJDK 9-specific way, eg. calls to subclasses of
938 // java.nio.Buffer as in http://b/70862583
939 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
940 flags.bootClasspath = append(flags.bootClasspath,
941 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
942 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
943 if Bool(j.properties.Use_tools_jar) {
944 flags.bootClasspath = append(flags.bootClasspath,
945 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
946 }
947 }
948
949 // systemModules
950 flags.systemModules = deps.systemModules
951
Jaewoong Jung26342642021-03-17 15:56:23 -0700952 return flags
953}
954
955func (j *Module) collectJavacFlags(
956 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
957 // javac flags.
958 javacFlags := j.properties.Javacflags
959
960 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
961 // For non-host binaries, override the -g flag passed globally to remove
962 // local variable debug info to reduce disk and memory usage.
963 javacFlags = append(javacFlags, "-g:source,lines")
964 }
965 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
966
967 if flags.javaVersion.usesJavaModules() {
968 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
969
970 if j.properties.Patch_module != nil {
971 // Manually specify build directory in case it is not under the repo root.
972 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
973 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200974 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700975
976 // b/150878007
977 //
978 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
979 // execution root for --patch-module. If this javac command line is
980 // invoked within Bazel's execution root working directory, the top
981 // level directories (e.g. libcore/, tools/, frameworks/) are all
982 // symlinks. JDK9 javac does not traverse into symlinks, which causes
983 // --patch-module to fail source file lookups when invoked in the
984 // execution root.
985 //
986 // Short of patching javac or enumerating *all* directories as possible
987 // input dirs, manually add the top level dir of the source files to be
988 // compiled.
989 topLevelDirs := map[string]bool{}
990 for _, srcFilePath := range srcFiles {
991 srcFileParts := strings.Split(srcFilePath.String(), "/")
992 // Ignore source files that are already in the top level directory
993 // as well as generated files in the out directory. The out
994 // directory may be an absolute path, which means srcFileParts[0] is the
995 // empty string, so check that as well. Note that "out" in Bazel's execution
996 // root is *not* a symlink, which doesn't cause problems for --patch-modules
997 // anyway, so it's fine to not apply this workaround for generated
998 // source files.
999 if len(srcFileParts) > 1 &&
1000 srcFileParts[0] != "" &&
1001 srcFileParts[0] != "out" {
1002 topLevelDirs[srcFileParts[0]] = true
1003 }
1004 }
1005 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
1006
1007 classPath := flags.classpath.FormJavaClassPath("")
1008 if classPath != "" {
1009 patchPaths = append(patchPaths, classPath)
1010 }
1011 javacFlags = append(
1012 javacFlags,
1013 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1014 }
1015 }
1016
1017 if len(javacFlags) > 0 {
1018 // optimization.
1019 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1020 flags.javacFlags = "$javacFlags"
1021 }
1022
1023 return flags
1024}
1025
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001026func (j *Module) AddJSONData(d *map[string]interface{}) {
1027 (&j.ModuleBase).AddJSONData(d)
1028 (*d)["Java"] = map[string]interface{}{
1029 "SourceExtensions": j.sourceExtensions,
1030 }
1031
1032}
1033
Jaewoong Jung26342642021-03-17 15:56:23 -07001034func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1035 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1036
1037 deps := j.collectDeps(ctx)
1038 flags := j.collectBuilderFlags(ctx, deps)
1039
1040 if flags.javaVersion.usesJavaModules() {
1041 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1042 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001043
Jaewoong Jung26342642021-03-17 15:56:23 -07001044 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001045 j.sourceExtensions = []string{}
1046 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1047 if hasSrcExt(srcFiles.Strings(), ext) {
1048 j.sourceExtensions = append(j.sourceExtensions, ext)
1049 }
1050 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001051 if hasSrcExt(srcFiles.Strings(), ".proto") {
1052 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1053 }
1054
1055 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1056 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1057 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1058 }
1059
Sam Delmerico2351eac2022-05-24 17:10:02 +00001060 aidlSrcs := srcFiles.FilterByExt(".aidl")
1061 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1062
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001063 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001064 srcFiles = j.genSources(ctx, srcFiles, flags)
1065
1066 // Collect javac flags only after computing the full set of srcFiles to
1067 // ensure that the --patch-module lookup paths are complete.
1068 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1069
1070 srcJars := srcFiles.FilterByExt(".srcjar")
1071 srcJars = append(srcJars, deps.srcJars...)
1072 if aaptSrcJar != nil {
1073 srcJars = append(srcJars, aaptSrcJar)
1074 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001075 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001076
1077 if j.properties.Jarjar_rules != nil {
1078 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1079 }
1080
1081 jarName := ctx.ModuleName() + ".jar"
1082
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001083 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001084 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001085 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001086 if _, found := set[v.String()]; !found {
1087 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001088 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001089 }
1090 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001091 var uniqueKtFiles android.Paths
1092 for _, v := range srcFiles.FilterByExt(".kt") {
1093 if _, found := set[v.String()]; !found {
1094 set[v.String()] = true
1095 uniqueKtFiles = append(uniqueKtFiles, v)
1096 }
1097 }
1098
1099 var uniqueSrcFiles android.Paths
1100 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1101 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1102 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001103
Colin Crossb5db4012022-03-28 17:12:39 -07001104 // We don't currently run annotation processors in turbine, which means we can't use turbine
1105 // generated header jars when an annotation processor that generates API is enabled. One
1106 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1107 // is used to run all of the annotation processors.
1108 disableTurbine := deps.disableTurbine
1109
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001110 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001111 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1112
1113 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001114 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001115
1116 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001117 // When using kotlin sources turbine is used to generate annotation processor sources,
1118 // including for annotation processors that generate API, so we can use turbine for
1119 // java sources too.
1120 disableTurbine = false
1121
Jaewoong Jung26342642021-03-17 15:56:23 -07001122 // user defined kotlin flags.
1123 kotlincFlags := j.properties.Kotlincflags
1124 CheckKotlincFlags(ctx, kotlincFlags)
1125
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001126 // Workaround for KT-46512
1127 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001128
1129 // If there are kotlin files, compile them first but pass all the kotlin and java files
1130 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1131 // won't emit any classes for them.
1132 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1133 if ctx.Device() {
1134 kotlincFlags = append(kotlincFlags, "-no-jdk")
1135 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001136
1137 for _, plugin := range deps.kotlinPlugins {
1138 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1139 }
1140 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1141
Jaewoong Jung26342642021-03-17 15:56:23 -07001142 if len(kotlincFlags) > 0 {
1143 // optimization.
1144 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1145 flags.kotlincFlags += "$kotlincFlags"
1146 }
1147
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001148 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001149 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1150
1151 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1152 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1153
1154 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1155 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1156
Isaac Chioua23d9942022-04-06 06:14:38 +00001157 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001158 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001159 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1160 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001161 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001162 srcJars = append(srcJars, kaptSrcJar)
1163 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001164 // Disable annotation processing in javac, it's already been handled by kapt
1165 flags.processorPath = nil
1166 flags.processors = nil
1167 }
1168
1169 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001170 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001171 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001172 if ctx.Failed() {
1173 return
1174 }
1175
Isaac Chioua23d9942022-04-06 06:14:38 +00001176 // Make javac rule depend on the kotlinc rule
1177 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1178
Jaewoong Jung26342642021-03-17 15:56:23 -07001179 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001180 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1181
Jaewoong Jung26342642021-03-17 15:56:23 -07001182 // Jar kotlin classes into the final jar after javac
1183 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1184 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001185 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001186 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001187 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001188 } else {
1189 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001190 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001191 }
1192 }
1193
1194 jars := append(android.Paths(nil), kotlinJars...)
1195
Jaewoong Jung26342642021-03-17 15:56:23 -07001196 j.compiledSrcJars = srcJars
1197
1198 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001199 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001200 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001201 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1202 enableSharding = true
1203 // Formerly, there was a check here that prevented annotation processors
1204 // from being used when sharding was enabled, as some annotation processors
1205 // do not function correctly in sharded environments. It was removed to
1206 // allow for the use of annotation processors that do function correctly
1207 // with sharding enabled. See: b/77284273.
1208 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001209 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001210 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001211 if ctx.Failed() {
1212 return
1213 }
1214 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001215 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001216 hasErrorproneableFiles := false
1217 for _, ext := range j.sourceExtensions {
1218 if ext != ".proto" && ext != ".aidl" {
1219 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1220 // compile, and it's not useful to have warnings on these generated sources.
1221 hasErrorproneableFiles = true
1222 break
1223 }
1224 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001225 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001226 if Bool(j.properties.Errorprone.Enabled) {
1227 // If error-prone is enabled, enable errorprone flags on the regular
1228 // build.
1229 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001230 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001231 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1232 // a new jar file just for compiling with the errorprone compiler to.
1233 // This is because we don't want to cause the java files to get completely
1234 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1235 // We also don't want to run this if errorprone is enabled by default for
1236 // this module, or else we could have duplicated errorprone messages.
1237 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001238 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001239
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001240 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001241 "errorprone", "errorprone")
1242
Jaewoong Jung26342642021-03-17 15:56:23 -07001243 extraJarDeps = append(extraJarDeps, errorprone)
1244 }
1245
1246 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001247 if headerJarFileWithoutDepsOrJarjar != nil {
1248 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1249 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001250 shardSize := int(*(j.properties.Javac_shard_size))
1251 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001252 if len(uniqueJavaFiles) > 0 {
1253 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001254 for idx, shardSrc := range shardSrcs {
1255 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1256 nil, flags, extraJarDeps)
1257 jars = append(jars, classes)
1258 }
1259 }
1260 if len(srcJars) > 0 {
1261 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1262 nil, srcJars, flags, extraJarDeps)
1263 jars = append(jars, classes)
1264 }
1265 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001266 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001267 jars = append(jars, classes)
1268 }
1269 if ctx.Failed() {
1270 return
1271 }
1272 }
1273
1274 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1275
1276 var includeSrcJar android.WritablePath
1277 if Bool(j.properties.Include_srcs) {
1278 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1279 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1280 }
1281
1282 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1283 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1284 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1285 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1286
1287 var resArgs []string
1288 var resDeps android.Paths
1289
1290 resArgs = append(resArgs, dirArgs...)
1291 resDeps = append(resDeps, dirDeps...)
1292
1293 resArgs = append(resArgs, fileArgs...)
1294 resDeps = append(resDeps, fileDeps...)
1295
1296 resArgs = append(resArgs, extraArgs...)
1297 resDeps = append(resDeps, extraDeps...)
1298
1299 if len(resArgs) > 0 {
1300 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1301 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1302 j.resourceJar = resourceJar
1303 if ctx.Failed() {
1304 return
1305 }
1306 }
1307
1308 var resourceJars android.Paths
1309 if j.resourceJar != nil {
1310 resourceJars = append(resourceJars, j.resourceJar)
1311 }
1312 if Bool(j.properties.Include_srcs) {
1313 resourceJars = append(resourceJars, includeSrcJar)
1314 }
1315 resourceJars = append(resourceJars, deps.staticResourceJars...)
1316
1317 if len(resourceJars) > 1 {
1318 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1319 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1320 false, nil, nil)
1321 j.resourceJar = combinedJar
1322 } else if len(resourceJars) == 1 {
1323 j.resourceJar = resourceJars[0]
1324 }
1325
1326 if len(deps.staticJars) > 0 {
1327 jars = append(jars, deps.staticJars...)
1328 }
1329
1330 manifest := j.overrideManifest
1331 if !manifest.Valid() && j.properties.Manifest != nil {
1332 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1333 }
1334
1335 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1336 if len(services) > 0 {
1337 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1338 var zipargs []string
1339 for _, file := range services {
1340 serviceFile := file.String()
1341 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1342 }
1343 rule := zip
1344 args := map[string]string{
1345 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1346 }
1347 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1348 rule = zipRE
1349 args["implicits"] = strings.Join(services.Strings(), ",")
1350 }
1351 ctx.Build(pctx, android.BuildParams{
1352 Rule: rule,
1353 Output: servicesJar,
1354 Implicits: services,
1355 Args: args,
1356 })
1357 jars = append(jars, servicesJar)
1358 }
1359
1360 // Combine the classes built from sources, any manifests, and any static libraries into
1361 // classes.jar. If there is only one input jar this step will be skipped.
1362 var outputFile android.OutputPath
1363
1364 if len(jars) == 1 && !manifest.Valid() {
1365 // Optimization: skip the combine step as there is nothing to do
1366 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1367 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1368 // any if len(jars) == 1.
1369
1370 // Transform the single path to the jar into an OutputPath as that is required by the following
1371 // code.
1372 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1373 // The path contains an embedded OutputPath so reuse that.
1374 outputFile = moduleOutPath.OutputPath
1375 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1376 // The path is an OutputPath so reuse it directly.
1377 outputFile = outputPath
1378 } else {
1379 // The file is not in the out directory so create an OutputPath into which it can be copied
1380 // and which the following code can use to refer to it.
1381 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1382 ctx.Build(pctx, android.BuildParams{
1383 Rule: android.Cp,
1384 Input: jars[0],
1385 Output: combinedJar,
1386 })
1387 outputFile = combinedJar.OutputPath
1388 }
1389 } else {
1390 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1391 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1392 false, nil, nil)
1393 outputFile = combinedJar.OutputPath
1394 }
1395
1396 // jarjar implementation jar if necessary
1397 if j.expandJarjarRules != nil {
1398 // Transform classes.jar into classes-jarjar.jar
1399 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1400 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1401 outputFile = jarjarFile
1402
1403 // jarjar resource jar if necessary
1404 if j.resourceJar != nil {
1405 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1406 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1407 j.resourceJar = resourceJarJarFile
1408 }
1409
1410 if ctx.Failed() {
1411 return
1412 }
1413 }
1414
1415 // Check package restrictions if necessary.
1416 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001417 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001418 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001419
1420 // Create a rule to copy the output jar to another path and add a validate dependency that
1421 // will check that the jar only contains the permitted packages. The new location will become
1422 // the output file of this module.
1423 inputFile := outputFile
1424 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1425 ctx.Build(pctx, android.BuildParams{
1426 Rule: android.Cp,
1427 Input: inputFile,
1428 Output: outputFile,
1429 // Make sure that any dependency on the output file will cause ninja to run the package check
1430 // rule.
1431 Validation: pkgckFile,
1432 })
1433
1434 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001435 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001436
1437 if ctx.Failed() {
1438 return
1439 }
1440 }
1441
1442 j.implementationJarFile = outputFile
1443 if j.headerJarFile == nil {
1444 j.headerJarFile = j.implementationJarFile
1445 }
1446
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001447 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1448 specs := j.jacocoModuleToZipCommand(ctx)
1449 if ctx.Failed() {
1450 return
1451 }
1452
Jaewoong Jung26342642021-03-17 15:56:23 -07001453 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001454 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001455 }
1456
1457 // merge implementation jar with resources if necessary
1458 implementationAndResourcesJar := outputFile
1459 if j.resourceJar != nil {
1460 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1461 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1462 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1463 false, nil, nil)
1464 implementationAndResourcesJar = combinedJar
1465 }
1466
1467 j.implementationAndResourcesJar = implementationAndResourcesJar
1468
1469 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001470 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001471 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1472 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001473 if compileDex == nil {
1474 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001475 }
1476 if j.deviceProperties.Hostdex == nil {
1477 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1478 }
1479 }
1480
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001481 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001482 if j.hasCode(ctx) {
1483 if j.shouldInstrumentStatic(ctx) {
1484 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1485 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1486 }
1487 // Dex compilation
1488 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001489 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001490 if ctx.Failed() {
1491 return
1492 }
1493
Jaewoong Jung26342642021-03-17 15:56:23 -07001494 // merge dex jar with resources if necessary
1495 if j.resourceJar != nil {
1496 jars := android.Paths{dexOutputFile, j.resourceJar}
1497 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1498 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1499 false, nil, nil)
1500 if *j.dexProperties.Uncompress_dex {
1501 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1502 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1503 dexOutputFile = combinedAlignedJar
1504 } else {
1505 dexOutputFile = combinedJar
1506 }
1507 }
1508
Paul Duffin4de94502021-05-16 05:21:16 +01001509 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001510
1511 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001512
1513 // Encode hidden API flags in dex file, if needed.
1514 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1515
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001516 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001517
1518 // Dexpreopting
1519 j.dexpreopt(ctx, dexOutputFile)
1520
1521 outputFile = dexOutputFile
1522 } else {
1523 // There is no code to compile into a dex jar, make sure the resources are propagated
1524 // to the APK if this is an app.
1525 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001526 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001527 }
1528
1529 if ctx.Failed() {
1530 return
1531 }
1532 } else {
1533 outputFile = implementationAndResourcesJar
1534 }
1535
1536 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001537 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001538 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001539 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001540 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001541 // When running metalava, we pass --version-codename. When that value
1542 // is not REL, metalava will add 1 to the --current-version argument.
1543 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1544 // branch) and the codename is REL, except potentially on the most
1545 // recent non-master branch. On that branch, it goes through two other
1546 // phases before it gets to the phase previously described:
1547 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1548 // is not rel. This happens for most of the internal branch's life
1549 // while the branch has been cut but is still under active development.
1550 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1551 // REL. This happens briefly during the release process. During this
1552 // state the code to add --current-version is commented out, and then
1553 // that commenting out is reverted after the codename is set to REL.
1554 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1555 // prior version and the codename is always non-REL.
1556 //
1557 // We need to add one here to match metalava adding 1. Technically
1558 // this means that in the state described in the second bullet point
1559 // above, this number is 1 higher than it should be.
1560 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001561 }
1562 }
1563
1564 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001565 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1566 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001567 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1568 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001569 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1570 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1571 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001572 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001573 j.linter.javaLanguageLevel = flags.javaVersion.String()
1574 j.linter.kotlinLanguageLevel = "1.3"
1575 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1576 j.linter.buildModuleReportZip = true
1577 }
1578 j.linter.lint(ctx)
1579 }
1580
1581 ctx.CheckbuildFile(outputFile)
1582
1583 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1584 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1585 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1586 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1587 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1588 AidlIncludeDirs: j.exportAidlIncludeDirs,
1589 SrcJarArgs: j.srcJarArgs,
1590 SrcJarDeps: j.srcJarDeps,
1591 ExportedPlugins: j.exportedPluginJars,
1592 ExportedPluginClasses: j.exportedPluginClasses,
1593 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1594 JacocoReportClassesFile: j.jacocoReportClassesFile,
1595 })
1596
1597 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1598 j.outputFile = outputFile.WithoutRel()
1599}
1600
Colin Crossa1ff7c62021-09-17 14:11:52 -07001601func (j *Module) useCompose() bool {
1602 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1603}
1604
Cole Faust75fffb12021-06-13 15:23:16 -07001605// Returns a copy of the supplied flags, but with all the errorprone-related
1606// fields copied to the regular build's fields.
1607func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1608 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1609
1610 if len(flags.errorProneExtraJavacFlags) > 0 {
1611 if len(flags.javacFlags) > 0 {
1612 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1613 } else {
1614 flags.javacFlags = flags.errorProneExtraJavacFlags
1615 }
1616 }
1617 return flags
1618}
1619
Jaewoong Jung26342642021-03-17 15:56:23 -07001620func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1621 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1622
1623 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1624 if idx >= 0 {
1625 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1626 jarName += strconv.Itoa(idx)
1627 }
1628
1629 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1630 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1631
1632 if ctx.Config().EmitXrefRules() {
1633 extractionFile := android.PathForModuleOut(ctx, kzipName)
1634 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1635 j.kytheFiles = append(j.kytheFiles, extractionFile)
1636 }
1637
1638 return classes
1639}
1640
1641// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1642// since some of these flags may be used internally.
1643func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1644 for _, flag := range flags {
1645 flag = strings.TrimSpace(flag)
1646
1647 if !strings.HasPrefix(flag, "-") {
1648 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1649 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1650 ctx.PropertyErrorf("kotlincflags",
1651 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1652 } else if inList(flag, config.KotlincIllegalFlags) {
1653 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1654 } else if flag == "-include-runtime" {
1655 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1656 } else {
1657 args := strings.Split(flag, " ")
1658 if args[0] == "-kotlin-home" {
1659 ctx.PropertyErrorf("kotlincflags",
1660 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1661 }
1662 }
1663 }
1664}
1665
1666func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1667 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001668 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001669
1670 var jars android.Paths
1671 if len(srcFiles) > 0 || len(srcJars) > 0 {
1672 // Compile java sources into turbine.jar.
1673 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1674 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1675 if ctx.Failed() {
1676 return nil, nil
1677 }
1678 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001679 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001680 }
1681
1682 jars = append(jars, extraJars...)
1683
1684 // Combine any static header libraries into classes-header.jar. If there is only
1685 // one input jar this step will be skipped.
1686 jars = append(jars, deps.staticHeaderJars...)
1687
1688 // we cannot skip the combine step for now if there is only one jar
1689 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1690 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1691 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1692 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001693 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001694
1695 if j.expandJarjarRules != nil {
1696 // Transform classes.jar into classes-jarjar.jar
1697 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001698 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1699 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001700 if ctx.Failed() {
1701 return nil, nil
1702 }
1703 }
1704
Colin Cross3d56ed52021-11-18 22:23:12 -08001705 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001706}
1707
1708func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001709 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001710
1711 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1712 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1713
1714 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1715
1716 j.jacocoReportClassesFile = jacocoReportClassesFile
1717
1718 return instrumentedJar
1719}
1720
1721func (j *Module) HeaderJars() android.Paths {
1722 if j.headerJarFile == nil {
1723 return nil
1724 }
1725 return android.Paths{j.headerJarFile}
1726}
1727
1728func (j *Module) ImplementationJars() android.Paths {
1729 if j.implementationJarFile == nil {
1730 return nil
1731 }
1732 return android.Paths{j.implementationJarFile}
1733}
1734
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001735func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001736 return j.dexJarFile
1737}
1738
1739func (j *Module) DexJarInstallPath() android.Path {
1740 return j.installFile
1741}
1742
1743func (j *Module) ImplementationAndResourcesJars() android.Paths {
1744 if j.implementationAndResourcesJar == nil {
1745 return nil
1746 }
1747 return android.Paths{j.implementationAndResourcesJar}
1748}
1749
1750func (j *Module) AidlIncludeDirs() android.Paths {
1751 // exportAidlIncludeDirs is type android.Paths already
1752 return j.exportAidlIncludeDirs
1753}
1754
1755func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1756 return j.classLoaderContexts
1757}
1758
1759// Collect information for opening IDE project files in java/jdeps.go.
1760func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1761 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1762 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1763 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1764 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1765 if j.expandJarjarRules != nil {
1766 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1767 }
1768 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001769 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1770 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001771}
1772
1773func (j *Module) CompilerDeps() []string {
1774 jdeps := []string{}
1775 jdeps = append(jdeps, j.properties.Libs...)
1776 jdeps = append(jdeps, j.properties.Static_libs...)
1777 return jdeps
1778}
1779
1780func (j *Module) hasCode(ctx android.ModuleContext) bool {
1781 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1782 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1783}
1784
1785// Implements android.ApexModule
1786func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1787 return j.depIsInSameApex(ctx, dep)
1788}
1789
1790// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001791func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001792 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001793 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001794 return fmt.Errorf("min_sdk_version is not specified")
1795 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001796 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001797 return nil
1798 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001799 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1800 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001801 }
1802 return nil
1803}
1804
1805func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001806 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001807}
1808
Jaewoong Jung26342642021-03-17 15:56:23 -07001809func (j *Module) JacocoReportClassesFile() android.Path {
1810 return j.jacocoReportClassesFile
1811}
1812
1813func (j *Module) IsInstallable() bool {
1814 return Bool(j.properties.Installable)
1815}
1816
1817type sdkLinkType int
1818
1819const (
1820 // TODO(jiyong) rename these for better readability. Make the allowed
1821 // and disallowed link types explicit
1822 // order is important here. See rank()
1823 javaCore sdkLinkType = iota
1824 javaSdk
1825 javaSystem
1826 javaModule
1827 javaSystemServer
1828 javaPlatform
1829)
1830
1831func (lt sdkLinkType) String() string {
1832 switch lt {
1833 case javaCore:
1834 return "core Java API"
1835 case javaSdk:
1836 return "Android API"
1837 case javaSystem:
1838 return "system API"
1839 case javaModule:
1840 return "module API"
1841 case javaSystemServer:
1842 return "system server API"
1843 case javaPlatform:
1844 return "private API"
1845 default:
1846 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1847 }
1848}
1849
1850// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1851// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1852// can't statically depend on modules that use Platform API.
1853func (lt sdkLinkType) rank() int {
1854 return int(lt)
1855}
1856
1857type moduleWithSdkDep interface {
1858 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001859 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001860}
1861
Jiyong Park92315372021-04-02 08:45:46 +09001862func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001863 switch name {
1864 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1865 "stub-annotations", "private-stub-annotations-jar",
1866 "core-lambda-stubs", "core-generated-annotation-stubs":
1867 return javaCore, true
1868 case "android_stubs_current":
1869 return javaSdk, true
1870 case "android_system_stubs_current":
1871 return javaSystem, true
1872 case "android_module_lib_stubs_current":
1873 return javaModule, true
1874 case "android_system_server_stubs_current":
1875 return javaSystemServer, true
1876 case "android_test_stubs_current":
1877 return javaSystem, true
1878 }
1879
1880 if stub, linkType := moduleStubLinkType(name); stub {
1881 return linkType, true
1882 }
1883
Jiyong Park92315372021-04-02 08:45:46 +09001884 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001885 switch ver.Kind {
1886 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001888 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001889 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001890 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001891 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001892 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001893 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001894 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001895 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001896 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001897 return javaPlatform, false
1898 }
1899
Jiyong Parkf1691d22021-03-29 20:11:58 +09001900 if !ver.Valid() {
1901 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001902 }
1903 return javaSdk, false
1904}
1905
1906// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1907// this module's. See the comment on rank() for details and an example.
1908func (j *Module) checkSdkLinkType(
1909 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1910 if ctx.Host() {
1911 return
1912 }
1913
Jiyong Park92315372021-04-02 08:45:46 +09001914 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001915 if stubs {
1916 return
1917 }
Jiyong Park92315372021-04-02 08:45:46 +09001918 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001919
1920 if myLinkType.rank() < depLinkType.rank() {
1921 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1922 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1923 "property of the source or target module so that target module is built "+
1924 "with the same or smaller API set when compared to the source.",
1925 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1926 }
1927}
1928
1929func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1930 var deps deps
1931
1932 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001933 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001934 if sdkDep.invalidVersion {
1935 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1936 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1937 } else if sdkDep.useFiles {
1938 // sdkDep.jar is actually equivalent to turbine header.jar.
1939 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001940 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001941 deps.aidlPreprocess = sdkDep.aidl
1942 } else {
1943 deps.aidlPreprocess = sdkDep.aidl
1944 }
1945 }
1946
Jiyong Park92315372021-04-02 08:45:46 +09001947 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001948
1949 ctx.VisitDirectDeps(func(module android.Module) {
1950 otherName := ctx.OtherModuleName(module)
1951 tag := ctx.OtherModuleDependencyTag(module)
1952
1953 if IsJniDepTag(tag) {
1954 // Handled by AndroidApp.collectAppDeps
1955 return
1956 }
1957 if tag == certificateTag {
1958 // Handled by AndroidApp.collectAppDeps
1959 return
1960 }
1961
1962 if dep, ok := module.(SdkLibraryDependency); ok {
1963 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04001964 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001965 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1966 deps.classpath = append(deps.classpath, depHeaderJars...)
1967 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001968 case staticLibTag:
1969 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1970 }
1971 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1972 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1973 if sdkLinkType != javaPlatform &&
1974 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1975 // dep is a sysprop implementation library, but this module is not linking against
1976 // the platform, so it gets the sysprop public stubs library instead. Replace
1977 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1978 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1979 dep = syspropDep.JavaInfo
1980 }
1981 switch tag {
1982 case bootClasspathTag:
1983 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04001984 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001985 if _, ok := module.(*Plugin); ok {
1986 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1987 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001988 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001989 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001990 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1991 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1992 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1993 case java9LibTag:
1994 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1995 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001996 if _, ok := module.(*Plugin); ok {
1997 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1998 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001999 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2000 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2001 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2002 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2003 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2004 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2005 // Turbine doesn't run annotation processors, so any module that uses an
2006 // annotation processor that generates API is incompatible with the turbine
2007 // optimization.
2008 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2009 case pluginTag:
2010 if plugin, ok := module.(*Plugin); ok {
2011 if plugin.pluginProperties.Processor_class != nil {
2012 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2013 } else {
2014 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2015 }
2016 // Turbine doesn't run annotation processors, so any module that uses an
2017 // annotation processor that generates API is incompatible with the turbine
2018 // optimization.
2019 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2020 } else {
2021 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2022 }
2023 case errorpronePluginTag:
2024 if _, ok := module.(*Plugin); ok {
2025 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2026 } else {
2027 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2028 }
2029 case exportedPluginTag:
2030 if plugin, ok := module.(*Plugin); ok {
2031 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2032 if plugin.pluginProperties.Processor_class != nil {
2033 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2034 }
2035 // Turbine doesn't run annotation processors, so any module that uses an
2036 // annotation processor that generates API is incompatible with the turbine
2037 // optimization.
2038 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2039 } else {
2040 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2041 }
2042 case kotlinStdlibTag:
2043 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2044 case kotlinAnnotationsTag:
2045 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002046 case kotlinPluginTag:
2047 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002048 case syspropPublicStubDepTag:
2049 // This is a sysprop implementation library, forward the JavaInfoProvider from
2050 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2051 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2052 JavaInfo: dep,
2053 })
2054 }
2055 } else if dep, ok := module.(android.SourceFileProducer); ok {
2056 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002057 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002058 checkProducesJars(ctx, dep)
2059 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002060 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002061 case staticLibTag:
2062 checkProducesJars(ctx, dep)
2063 deps.classpath = append(deps.classpath, dep.Srcs()...)
2064 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2065 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2066 }
2067 } else {
2068 switch tag {
2069 case bootClasspathTag:
2070 // If a system modules dependency has been added to the bootclasspath
2071 // then add its libs to the bootclasspath.
2072 sm := module.(SystemModulesProvider)
2073 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2074
2075 case systemModulesTag:
2076 if deps.systemModules != nil {
2077 panic("Found two system module dependencies")
2078 }
2079 sm := module.(SystemModulesProvider)
2080 outputDir, outputDeps := sm.OutputDirAndDeps()
2081 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002082
2083 case instrumentationForTag:
2084 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 -07002085 }
2086 }
2087
2088 addCLCFromDep(ctx, module, j.classLoaderContexts)
2089 })
2090
2091 return deps
2092}
2093
2094func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2095 deps.processorPath = append(deps.processorPath, pluginJars...)
2096 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2097}
2098
2099// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2100// this interface.
2101type ProvidesUsesLib interface {
2102 ProvidesUsesLib() *string
2103}
2104
2105func (j *Module) ProvidesUsesLib() *string {
2106 return j.usesLibraryProperties.Provides_uses_lib
2107}
satayev1c564cc2021-05-25 19:50:30 +01002108
2109type ModuleWithStem interface {
2110 Stem() string
2111}
2112
2113var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002114
2115func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2116 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002117 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002118 if lib, ok := ctx.Module().(*Library); ok {
2119 javaLibraryBp2Build(ctx, lib)
2120 }
2121 case "java_binary_host":
2122 if binary, ok := ctx.Module().(*Binary); ok {
2123 javaBinaryHostBp2Build(ctx, binary)
2124 }
2125 }
Wei Libafb6d62021-12-10 03:14:59 -08002126}