blob: 2d213a192ee680405d586f91ca975f7bbc7400d4 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
Cole Faust2b1536e2021-06-18 12:25:54 -0700159 // This property can be in 3 states. When set to true, errorprone will
160 // be run during the regular build. When set to false, errorprone will
161 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
162 // environment variable is true. Setting this to false will improve build
163 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700164 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700165 }
166
167 Proto struct {
168 // List of extra options that will be passed to the proto generator.
169 Output_params []string
170 }
171
Sam Delmericoc7593722022-08-31 15:57:52 -0400172 // If true, then jacocoagent is automatically added as a libs dependency so that
173 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700174 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000175 // If true, then the module supports statically including the jacocoagent
176 // into the library.
177 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700178
179 // List of files to include in the META-INF/services folder of the resulting jar.
180 Services []string `android:"path,arch_variant"`
181
182 // If true, package the kotlin stdlib into the jar. Defaults to true.
183 Static_kotlin_stdlib *bool `android:"arch_variant"`
184
185 // A list of java_library instances that provide additional hiddenapi annotations for the library.
186 Hiddenapi_additional_annotations []string
187}
188
189// Properties that are specific to device modules. Host module factories should not add these when
190// constructing a new module.
191type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000192 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000193 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000194 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000195 // 1) numerical API level, "current", "none", or "core_platform"
196 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
197 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
198 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700199 Sdk_version *string
200
201 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000202 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700203 Min_sdk_version *string
204
satayev0a420e72021-11-29 17:25:52 +0000205 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
206 // Defaults to empty string "". See sdk_version for possible values.
207 Max_sdk_version *string
208
William Loh5a082f92022-05-17 20:21:50 +0000209 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
210 // Defaults to empty string "". See sdk_version for possible values.
211 Replace_max_sdk_version_placeholder *string
212
Jaewoong Jung26342642021-03-17 15:56:23 -0700213 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000214 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700215 Target_sdk_version *string
216
217 // Whether to compile against the platform APIs instead of an SDK.
218 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000219 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700220 Platform_apis *bool
221
222 Aidl struct {
223 // Top level directories to pass to aidl tool
224 Include_dirs []string
225
226 // Directories rooted at the Android.bp file to pass to aidl tool
227 Local_include_dirs []string
228
229 // directories that should be added as include directories for any aidl sources of modules
230 // that depend on this module, as well as to aidl for this module.
231 Export_include_dirs []string
232
233 // whether to generate traces (for systrace) for this interface
234 Generate_traces *bool
235
236 // whether to generate Binder#GetTransaction name method.
237 Generate_get_transaction_name *bool
238
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100239 // whether all interfaces should be annotated with required permissions.
240 Enforce_permissions *bool
241
242 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
243 Enforce_permissions_exceptions []string `android:"path"`
244
Jaewoong Jung26342642021-03-17 15:56:23 -0700245 // list of flags that will be passed to the AIDL compiler
246 Flags []string
247 }
248
249 // If true, export a copy of the module as a -hostdex module for host testing.
250 Hostdex *bool
251
252 Target struct {
253 Hostdex struct {
254 // Additional required dependencies to add to -hostdex modules.
255 Required []string
256 }
257 }
258
259 // When targeting 1.9 and above, override the modules to use with --system,
260 // otherwise provides defaults libraries to add to the bootclasspath.
261 System_modules *string
262
Jaewoong Jung26342642021-03-17 15:56:23 -0700263 IsSDKLibrary bool `blueprint:"mutated"`
264
265 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
266 // Defaults to false.
267 V4_signature *bool
268
269 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
270 // public stubs library.
271 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000272
273 HiddenAPIPackageProperties
274 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700275}
276
Jooyung Han01d80d82022-01-08 12:16:32 +0900277// Device properties that can be overridden by overriding module (e.g. override_android_app)
278type OverridableDeviceProperties struct {
279 // set the name of the output. If not set, `name` is used.
280 // To override a module with this property set, overriding module might need to set this as well.
281 // Otherwise, both the overridden and the overriding modules will have the same output name, which
282 // can cause the duplicate output error.
283 Stem *string
284}
285
Jaewoong Jung26342642021-03-17 15:56:23 -0700286// Functionality common to Module and Import
287//
288// It is embedded in Module so its functionality can be used by methods in Module
289// but it is currently only initialized by Import and Library.
290type embeddableInModuleAndImport struct {
291
292 // Functionality related to this being used as a component of a java_sdk_library.
293 EmbeddableSdkLibraryComponent
294}
295
Paul Duffin71b33cc2021-06-23 11:39:47 +0100296func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
297 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700298}
299
300// Module/Import's DepIsInSameApex(...) delegates to this method.
301//
302// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
303// the one provided by ApexModuleBase.
304func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
305 // dependencies other than the static linkage are all considered crossing APEX boundary
306 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
307 return true
308 }
309 return false
310}
311
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100312// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
313// or an invalid path describing the reason it is invalid.
314//
315// It is unset if a dex jar isn't applicable, i.e. no build rule has been
316// requested to create one.
317//
318// If a dex jar has been requested to be built then it is set, and it may be
319// either a valid android.Path, or invalid with a reason message. The latter
320// happens if the source that should produce the dex file isn't able to.
321//
322// E.g. it is invalid with a reason message if there is a prebuilt APEX that
323// could produce the dex jar through a deapexer module, but the APEX isn't
324// installable so doing so wouldn't be safe.
325type OptionalDexJarPath struct {
326 isSet bool
327 path android.OptionalPath
328}
329
330// IsSet returns true if a path has been set, either invalid or valid.
331func (o OptionalDexJarPath) IsSet() bool {
332 return o.isSet
333}
334
335// Valid returns true if there is a path that is valid.
336func (o OptionalDexJarPath) Valid() bool {
337 return o.isSet && o.path.Valid()
338}
339
340// Path returns the valid path, or panics if it's either not set or is invalid.
341func (o OptionalDexJarPath) Path() android.Path {
342 if !o.isSet {
343 panic("path isn't set")
344 }
345 return o.path.Path()
346}
347
348// PathOrNil returns the path if it's set and valid, or else nil.
349func (o OptionalDexJarPath) PathOrNil() android.Path {
350 if o.Valid() {
351 return o.Path()
352 }
353 return nil
354}
355
356// InvalidReason returns the reason for an invalid path, which is never "". It
357// returns "" for an unset or valid path.
358func (o OptionalDexJarPath) InvalidReason() string {
359 if !o.isSet {
360 return ""
361 }
362 return o.path.InvalidReason()
363}
364
365func (o OptionalDexJarPath) String() string {
366 if !o.isSet {
367 return "<unset>"
368 }
369 return o.path.String()
370}
371
372// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
373func makeUnsetDexJarPath() OptionalDexJarPath {
374 return OptionalDexJarPath{isSet: false}
375}
376
377// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
378// the given OptionalPath, which may be valid or invalid.
379func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
380 return OptionalDexJarPath{isSet: true, path: path}
381}
382
383// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
384// valid given path. It returns an unset OptionalDexJarPath if the given path is
385// nil.
386func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
387 if path == nil {
388 return makeUnsetDexJarPath()
389 }
390 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
391}
392
Jaewoong Jung26342642021-03-17 15:56:23 -0700393// Module contains the properties and members used by all java module types
394type Module struct {
395 android.ModuleBase
396 android.DefaultableModuleBase
397 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800398 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700399
400 // Functionality common to Module and Import.
401 embeddableInModuleAndImport
402
403 properties CommonProperties
404 protoProperties android.ProtoProperties
405 deviceProperties DeviceProperties
406
Jooyung Han01d80d82022-01-08 12:16:32 +0900407 overridableDeviceProperties OverridableDeviceProperties
408
Jaewoong Jung26342642021-03-17 15:56:23 -0700409 // jar file containing header classes including static library dependencies, suitable for
410 // inserting into the bootclasspath/classpath of another compile
411 headerJarFile android.Path
412
413 // jar file containing implementation classes including static library dependencies but no
414 // resources
415 implementationJarFile android.Path
416
417 // jar file containing only resources including from static library dependencies
418 resourceJar android.Path
419
420 // args and dependencies to package source files into a srcjar
421 srcJarArgs []string
422 srcJarDeps android.Paths
423
424 // jar file containing implementation classes and resources including static library
425 // dependencies
426 implementationAndResourcesJar android.Path
427
428 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100429 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700430
431 // output file containing uninstrumented classes that will be instrumented by jacoco
432 jacocoReportClassesFile android.Path
433
434 // output file of the module, which may be a classes jar or a dex jar
435 outputFile android.Path
436 extraOutputFiles android.Paths
437
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100438 exportAidlIncludeDirs android.Paths
439 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700440
441 logtagsSrcs android.Paths
442
443 // installed file for binary dependency
444 installFile android.Path
445
Colin Cross3108ce12021-11-10 14:38:50 -0800446 // installed file for hostdex copy
447 hostdexInstallFile android.InstallPath
448
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800449 // list of unique .java and .kt source files
450 uniqueSrcFiles android.Paths
451
452 // list of srcjars that was passed to javac
453 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700454
455 // manifest file to use instead of properties.Manifest
456 overrideManifest android.OptionalPath
457
Jaewoong Jung26342642021-03-17 15:56:23 -0700458 // list of plugins that this java module is exporting
459 exportedPluginJars android.Paths
460
461 // list of plugins that this java module is exporting
462 exportedPluginClasses []string
463
464 // if true, the exported plugins generate API and require disabling turbine.
465 exportedDisableTurbine bool
466
467 // list of source files, collected from srcFiles with unique java and all kt files,
468 // will be used by android.IDEInfo struct
469 expandIDEInfoCompiledSrcs []string
470
471 // expanded Jarjar_rules
472 expandJarjarRules android.Path
473
Jaewoong Jung26342642021-03-17 15:56:23 -0700474 // Extra files generated by the module type to be added as java resources.
475 extraResources android.Paths
476
477 hiddenAPI
478 dexer
479 dexpreopter
480 usesLibrary
481 linter
482
483 // list of the xref extraction files
484 kytheFiles android.Paths
485
486 // Collect the module directory for IDE info in java/jdeps.go.
487 modulePaths []string
488
489 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900490
491 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000492 minSdkVersion android.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000493 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400494
495 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700496}
497
Jiyong Park92315372021-04-02 08:45:46 +0900498func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
499 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900500 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700501 return nil
502 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900503 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000504 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700505 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
506 } else {
507 // Treat stable core platform as stable.
508 return nil
509 }
510 } else {
511 return fmt.Errorf("non stable SDK %v", sdkVersion)
512 }
513}
514
515// checkSdkVersions enforces restrictions around SDK dependencies.
516func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
517 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900518 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900519 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700520 ctx.PropertyErrorf("sdk_version",
521 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
522 }
523 }
524 }
525
526 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
527 // See rank() for details.
528 ctx.VisitDirectDeps(func(module android.Module) {
529 tag := ctx.OtherModuleDependencyTag(module)
530 switch module.(type) {
531 // TODO(satayev): cover other types as well, e.g. imports
532 case *Library, *AndroidLibrary:
533 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400534 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700535 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
536 }
537 }
538 })
539}
540
541func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900542 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700543 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900544 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700545 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000546 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 -0700547 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000548 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 -0700549 }
550
551 }
552}
553
554func (j *Module) addHostProperties() {
555 j.AddProperties(
556 &j.properties,
557 &j.protoProperties,
558 &j.usesLibraryProperties,
559 )
560}
561
562func (j *Module) addHostAndDeviceProperties() {
563 j.addHostProperties()
564 j.AddProperties(
565 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900566 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700567 &j.dexer.dexProperties,
568 &j.dexpreoptProperties,
569 &j.linter.properties,
570 )
571}
572
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000573// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
574// makes it available through the hiddenAPIPropertyInfoProvider.
575func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
576 hiddenAPIInfo := newHiddenAPIPropertyInfo()
577
578 // Populate with flag file paths from the properties.
579 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
580
581 // Populate with package rules from the properties.
582 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
583
584 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
585}
586
Jaewoong Jung26342642021-03-17 15:56:23 -0700587func (j *Module) OutputFiles(tag string) (android.Paths, error) {
588 switch tag {
589 case "":
590 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
591 case android.DefaultDistTag:
592 return android.Paths{j.outputFile}, nil
593 case ".jar":
594 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700595 case ".hjar":
596 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700597 case ".proguard_map":
598 if j.dexer.proguardDictionary.Valid() {
599 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
600 }
601 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
602 default:
603 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
604 }
605}
606
607var _ android.OutputFileProducer = (*Module)(nil)
608
609func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
610 initJavaModule(module, hod, false)
611}
612
613func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
614 initJavaModule(module, hod, true)
615}
616
617func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
618 multilib := android.MultilibCommon
619 if multiTargets {
620 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
621 } else {
622 android.InitAndroidArchModule(module, hod, multilib)
623 }
624 android.InitDefaultableModule(module)
625}
626
627func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
628 return j.properties.Instrument &&
629 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
630 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
631}
632
633func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000634 return j.properties.Supports_static_instrumentation &&
635 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700636 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
637 ctx.Config().UnbundledBuild())
638}
639
640func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
641 // Force enable the instrumentation for java code that is built for APEXes ...
642 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
643 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
644 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
645 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
646 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
647 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
648 return true
649 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
650 return true
651 }
652 }
653 return false
654}
655
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400656func (j *Module) setInstrument(value bool) {
657 j.properties.Instrument = value
658}
659
Jiyong Park92315372021-04-02 08:45:46 +0900660func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
661 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700662}
663
Jiyong Parkf1691d22021-03-29 20:11:58 +0900664func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700665 return proptools.String(j.deviceProperties.System_modules)
666}
667
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000668func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700669 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000670 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700671 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000672 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700673}
674
satayev0a420e72021-11-29 17:25:52 +0000675func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
676 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
677 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
678 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
679 return android.SdkSpecFrom(ctx, maxSdkVersion)
680}
681
William Loh5a082f92022-05-17 20:21:50 +0000682func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
683 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
684 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
685}
686
Jiyong Parkf1691d22021-03-29 20:11:58 +0900687func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000688 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900689}
690
Spandan Dasca70fc42023-03-01 23:38:49 +0000691func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900692 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000693 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900694 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000695 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700696}
697
698func (j *Module) AvailableFor(what string) bool {
699 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
700 // Exception: for hostdex: true libraries, the platform variant is created
701 // even if it's not marked as available to platform. In that case, the platform
702 // variant is used only for the hostdex and not installed to the device.
703 return true
704 }
705 return j.ApexModuleBase.AvailableFor(what)
706}
707
708func (j *Module) deps(ctx android.BottomUpMutatorContext) {
709 if ctx.Device() {
710 j.linter.deps(ctx)
711
Jiyong Parkf1691d22021-03-29 20:11:58 +0900712 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700713
714 if j.deviceProperties.SyspropPublicStub != "" {
715 // This is a sysprop implementation library that has a corresponding sysprop public
716 // stubs library, and a dependency on it so that dependencies on the implementation can
717 // be forwarded to the public stubs library when necessary.
718 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
719 }
720 }
721
722 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
723 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
724
725 // Add dependency on libraries that provide additional hidden api annotations.
726 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
727
728 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
729 // Require java_sdk_library at inter-partition java dependency to ensure stable
730 // interface between partitions. If inter-partition java_library dependency is detected,
731 // raise build error because java_library doesn't have a stable interface.
732 //
733 // Inputs:
734 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
735 // if true, enable enforcement
736 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
737 // exception list of java_library names to allow inter-partition dependency
738 for idx := range j.properties.Libs {
739 if libDeps[idx] == nil {
740 continue
741 }
742
743 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
744 // java_sdk_library is always allowed at inter-partition dependency.
745 // So, skip check.
746 if _, ok := javaDep.(*SdkLibrary); ok {
747 continue
748 }
749
750 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
751 }
752 }
753 }
754
755 // For library dependencies that are component libraries (like stubs), add the implementation
756 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
757 for _, dep := range libDeps {
758 if dep != nil {
759 if component, ok := dep.(SdkLibraryComponentDependency); ok {
760 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100761 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100762 tag := usesLibReqTag
763 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
764 tag = usesLibOptTag
765 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100766 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700767 }
768 }
769 }
770 }
771
772 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
773 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
774 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
775
776 android.ProtoDeps(ctx, &j.protoProperties)
777 if j.hasSrcExt(".proto") {
778 protoDeps(ctx, &j.protoProperties)
779 }
780
781 if j.hasSrcExt(".kt") {
782 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
783 // Kotlin files
784 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
785 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700786 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700787 }
788
789 // Framework libraries need special handling in static coverage builds: they should not have
790 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
791 // the same jacoco classes coming from different bootclasspath jars.
792 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
793 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
794 j.properties.Instrument = true
795 }
796 } else if j.shouldInstrumentStatic(ctx) {
797 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
798 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700799
800 if j.useCompose() {
801 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
802 "androidx.compose.compiler_compiler-hosted")
803 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700804}
805
806func hasSrcExt(srcs []string, ext string) bool {
807 for _, src := range srcs {
808 if filepath.Ext(src) == ext {
809 return true
810 }
811 }
812
813 return false
814}
815
816func (j *Module) hasSrcExt(ext string) bool {
817 return hasSrcExt(j.properties.Srcs, ext)
818}
819
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100820func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
821 var flags string
822
823 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
824 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
825 flags = "-Wmissing-permission-annotation -Werror"
826 }
827 }
828 return flags
829}
830
Jaewoong Jung26342642021-03-17 15:56:23 -0700831func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000832 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700833
834 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
835 aidlIncludes = append(aidlIncludes,
836 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
837 aidlIncludes = append(aidlIncludes,
838 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
839
840 var flags []string
841 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000842 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700843
844 flags = append(flags, j.deviceProperties.Aidl.Flags...)
845
846 if aidlPreprocess.Valid() {
847 flags = append(flags, "-p"+aidlPreprocess.String())
848 deps = append(deps, aidlPreprocess.Path())
849 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000850 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700851 }
852
853 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000854 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700855 }
856
857 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000858 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700859 }
860
Sam Delmerico2351eac2022-05-24 17:10:02 +0000861 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700862 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000863 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700864 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000865 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
866 // add flags for dirs containing AIDL srcs that haven't been specified yet
867 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700868
Zim8774ae12022-08-17 11:46:34 +0100869 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000870 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100871 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 flags = append(flags, "-t")
873 }
874
875 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
876 flags = append(flags, "--transaction_names")
877 }
878
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100879 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
880 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
881 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
882 }
883
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000884 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900885 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
886
Jaewoong Jung26342642021-03-17 15:56:23 -0700887 return strings.Join(flags, " "), deps
888}
889
890func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
891
892 var flags javaBuilderFlags
893
894 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900895 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700896
Cole Faust2b1536e2021-06-18 12:25:54 -0700897 epEnabled := j.properties.Errorprone.Enabled
898 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100899 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700900 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
901 }
902
903 errorProneFlags := []string{
904 "-Xplugin:ErrorProne",
905 "${config.ErrorProneChecks}",
906 }
907 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
908
Colin Cross8bf6cad2022-02-28 13:07:03 -0800909 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700910 "'" + strings.Join(errorProneFlags, " ") + "'"
911 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
912 }
913
914 // classpath
915 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
916 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700917 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700918 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
919 flags.processorPath = append(flags.processorPath, deps.processorPath...)
920 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
921
922 flags.processors = append(flags.processors, deps.processorClasses...)
923 flags.processors = android.FirstUniqueStrings(flags.processors)
924
925 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900926 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700927 // Give host-side tools a version of OpenJDK's standard libraries
928 // close to what they're targeting. As of Dec 2017, AOSP is only
929 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
930 //
931 // When building with OpenJDK 8, the following should have no
932 // effect since those jars would be available by default.
933 //
934 // When building with OpenJDK 9 but targeting a version < 1.8,
935 // putting them on the bootclasspath means that:
936 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
937 // b) references to existing APIs are not reinterpreted in an
938 // OpenJDK 9-specific way, eg. calls to subclasses of
939 // java.nio.Buffer as in http://b/70862583
940 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
941 flags.bootClasspath = append(flags.bootClasspath,
942 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
943 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
944 if Bool(j.properties.Use_tools_jar) {
945 flags.bootClasspath = append(flags.bootClasspath,
946 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
947 }
948 }
949
950 // systemModules
951 flags.systemModules = deps.systemModules
952
Jaewoong Jung26342642021-03-17 15:56:23 -0700953 return flags
954}
955
956func (j *Module) collectJavacFlags(
957 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
958 // javac flags.
959 javacFlags := j.properties.Javacflags
960
961 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
962 // For non-host binaries, override the -g flag passed globally to remove
963 // local variable debug info to reduce disk and memory usage.
964 javacFlags = append(javacFlags, "-g:source,lines")
965 }
966 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
967
968 if flags.javaVersion.usesJavaModules() {
969 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
970
971 if j.properties.Patch_module != nil {
972 // Manually specify build directory in case it is not under the repo root.
973 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
974 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200975 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700976
977 // b/150878007
978 //
979 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
980 // execution root for --patch-module. If this javac command line is
981 // invoked within Bazel's execution root working directory, the top
982 // level directories (e.g. libcore/, tools/, frameworks/) are all
983 // symlinks. JDK9 javac does not traverse into symlinks, which causes
984 // --patch-module to fail source file lookups when invoked in the
985 // execution root.
986 //
987 // Short of patching javac or enumerating *all* directories as possible
988 // input dirs, manually add the top level dir of the source files to be
989 // compiled.
990 topLevelDirs := map[string]bool{}
991 for _, srcFilePath := range srcFiles {
992 srcFileParts := strings.Split(srcFilePath.String(), "/")
993 // Ignore source files that are already in the top level directory
994 // as well as generated files in the out directory. The out
995 // directory may be an absolute path, which means srcFileParts[0] is the
996 // empty string, so check that as well. Note that "out" in Bazel's execution
997 // root is *not* a symlink, which doesn't cause problems for --patch-modules
998 // anyway, so it's fine to not apply this workaround for generated
999 // source files.
1000 if len(srcFileParts) > 1 &&
1001 srcFileParts[0] != "" &&
1002 srcFileParts[0] != "out" {
1003 topLevelDirs[srcFileParts[0]] = true
1004 }
1005 }
Cole Faust18994c72023-02-28 16:02:16 -08001006 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001007
1008 classPath := flags.classpath.FormJavaClassPath("")
1009 if classPath != "" {
1010 patchPaths = append(patchPaths, classPath)
1011 }
1012 javacFlags = append(
1013 javacFlags,
1014 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1015 }
1016 }
1017
1018 if len(javacFlags) > 0 {
1019 // optimization.
1020 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1021 flags.javacFlags = "$javacFlags"
1022 }
1023
1024 return flags
1025}
1026
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001027func (j *Module) AddJSONData(d *map[string]interface{}) {
1028 (&j.ModuleBase).AddJSONData(d)
1029 (*d)["Java"] = map[string]interface{}{
1030 "SourceExtensions": j.sourceExtensions,
1031 }
1032
1033}
1034
Jaewoong Jung26342642021-03-17 15:56:23 -07001035func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1036 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1037
1038 deps := j.collectDeps(ctx)
1039 flags := j.collectBuilderFlags(ctx, deps)
1040
1041 if flags.javaVersion.usesJavaModules() {
1042 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1043 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001044
Jaewoong Jung26342642021-03-17 15:56:23 -07001045 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001046 j.sourceExtensions = []string{}
1047 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1048 if hasSrcExt(srcFiles.Strings(), ext) {
1049 j.sourceExtensions = append(j.sourceExtensions, ext)
1050 }
1051 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001052 if hasSrcExt(srcFiles.Strings(), ".proto") {
1053 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1054 }
1055
1056 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1057 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1058 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1059 }
1060
Sam Delmerico2351eac2022-05-24 17:10:02 +00001061 aidlSrcs := srcFiles.FilterByExt(".aidl")
1062 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1063
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001064 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001065 srcFiles = j.genSources(ctx, srcFiles, flags)
1066
1067 // Collect javac flags only after computing the full set of srcFiles to
1068 // ensure that the --patch-module lookup paths are complete.
1069 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1070
1071 srcJars := srcFiles.FilterByExt(".srcjar")
1072 srcJars = append(srcJars, deps.srcJars...)
1073 if aaptSrcJar != nil {
1074 srcJars = append(srcJars, aaptSrcJar)
1075 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001076 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001077
1078 if j.properties.Jarjar_rules != nil {
1079 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1080 }
1081
1082 jarName := ctx.ModuleName() + ".jar"
1083
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001084 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001086 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001087 if _, found := set[v.String()]; !found {
1088 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001089 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001090 }
1091 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001092 var uniqueKtFiles android.Paths
1093 for _, v := range srcFiles.FilterByExt(".kt") {
1094 if _, found := set[v.String()]; !found {
1095 set[v.String()] = true
1096 uniqueKtFiles = append(uniqueKtFiles, v)
1097 }
1098 }
1099
1100 var uniqueSrcFiles android.Paths
1101 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1102 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1103 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001104
Colin Crossb5db4012022-03-28 17:12:39 -07001105 // We don't currently run annotation processors in turbine, which means we can't use turbine
1106 // generated header jars when an annotation processor that generates API is enabled. One
1107 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1108 // is used to run all of the annotation processors.
1109 disableTurbine := deps.disableTurbine
1110
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001111 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001112 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1113
1114 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001115 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001116
1117 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001118 // When using kotlin sources turbine is used to generate annotation processor sources,
1119 // including for annotation processors that generate API, so we can use turbine for
1120 // java sources too.
1121 disableTurbine = false
1122
Jaewoong Jung26342642021-03-17 15:56:23 -07001123 // user defined kotlin flags.
1124 kotlincFlags := j.properties.Kotlincflags
1125 CheckKotlincFlags(ctx, kotlincFlags)
1126
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001127 // Workaround for KT-46512
1128 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001129
1130 // If there are kotlin files, compile them first but pass all the kotlin and java files
1131 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1132 // won't emit any classes for them.
1133 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1134 if ctx.Device() {
1135 kotlincFlags = append(kotlincFlags, "-no-jdk")
1136 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001137
1138 for _, plugin := range deps.kotlinPlugins {
1139 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1140 }
1141 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1142
Jaewoong Jung26342642021-03-17 15:56:23 -07001143 if len(kotlincFlags) > 0 {
1144 // optimization.
1145 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1146 flags.kotlincFlags += "$kotlincFlags"
1147 }
1148
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001149 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001150 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1151
1152 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1153 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1154
1155 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1156 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1157
Isaac Chioua23d9942022-04-06 06:14:38 +00001158 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001160 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1161 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001162 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001163 srcJars = append(srcJars, kaptSrcJar)
1164 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001165 // Disable annotation processing in javac, it's already been handled by kapt
1166 flags.processorPath = nil
1167 flags.processors = nil
1168 }
1169
1170 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001171 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001172 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001173 if ctx.Failed() {
1174 return
1175 }
1176
Isaac Chioua23d9942022-04-06 06:14:38 +00001177 // Make javac rule depend on the kotlinc rule
1178 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1179
Jaewoong Jung26342642021-03-17 15:56:23 -07001180 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001181 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1182
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 // Jar kotlin classes into the final jar after javac
1184 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1185 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001186 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001187 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001188 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001189 } else {
1190 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001191 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001192 }
1193 }
1194
1195 jars := append(android.Paths(nil), kotlinJars...)
1196
Jaewoong Jung26342642021-03-17 15:56:23 -07001197 j.compiledSrcJars = srcJars
1198
1199 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001200 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001201 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001202 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1203 enableSharding = true
1204 // Formerly, there was a check here that prevented annotation processors
1205 // from being used when sharding was enabled, as some annotation processors
1206 // do not function correctly in sharded environments. It was removed to
1207 // allow for the use of annotation processors that do function correctly
1208 // with sharding enabled. See: b/77284273.
1209 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001210 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001211 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001212 if ctx.Failed() {
1213 return
1214 }
1215 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001216 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001217 hasErrorproneableFiles := false
1218 for _, ext := range j.sourceExtensions {
1219 if ext != ".proto" && ext != ".aidl" {
1220 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1221 // compile, and it's not useful to have warnings on these generated sources.
1222 hasErrorproneableFiles = true
1223 break
1224 }
1225 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001226 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001227 if Bool(j.properties.Errorprone.Enabled) {
1228 // If error-prone is enabled, enable errorprone flags on the regular
1229 // build.
1230 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001231 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001232 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1233 // a new jar file just for compiling with the errorprone compiler to.
1234 // This is because we don't want to cause the java files to get completely
1235 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1236 // We also don't want to run this if errorprone is enabled by default for
1237 // this module, or else we could have duplicated errorprone messages.
1238 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001239 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001240
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001241 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001242 "errorprone", "errorprone")
1243
Jaewoong Jung26342642021-03-17 15:56:23 -07001244 extraJarDeps = append(extraJarDeps, errorprone)
1245 }
1246
1247 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001248 if headerJarFileWithoutDepsOrJarjar != nil {
1249 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1250 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001251 shardSize := int(*(j.properties.Javac_shard_size))
1252 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001253 if len(uniqueJavaFiles) > 0 {
1254 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001255 for idx, shardSrc := range shardSrcs {
1256 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1257 nil, flags, extraJarDeps)
1258 jars = append(jars, classes)
1259 }
1260 }
1261 if len(srcJars) > 0 {
1262 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1263 nil, srcJars, flags, extraJarDeps)
1264 jars = append(jars, classes)
1265 }
1266 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001267 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001268 jars = append(jars, classes)
1269 }
1270 if ctx.Failed() {
1271 return
1272 }
1273 }
1274
1275 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1276
1277 var includeSrcJar android.WritablePath
1278 if Bool(j.properties.Include_srcs) {
1279 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1280 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1281 }
1282
1283 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1284 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1285 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1286 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1287
1288 var resArgs []string
1289 var resDeps android.Paths
1290
1291 resArgs = append(resArgs, dirArgs...)
1292 resDeps = append(resDeps, dirDeps...)
1293
1294 resArgs = append(resArgs, fileArgs...)
1295 resDeps = append(resDeps, fileDeps...)
1296
1297 resArgs = append(resArgs, extraArgs...)
1298 resDeps = append(resDeps, extraDeps...)
1299
1300 if len(resArgs) > 0 {
1301 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1302 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1303 j.resourceJar = resourceJar
1304 if ctx.Failed() {
1305 return
1306 }
1307 }
1308
1309 var resourceJars android.Paths
1310 if j.resourceJar != nil {
1311 resourceJars = append(resourceJars, j.resourceJar)
1312 }
1313 if Bool(j.properties.Include_srcs) {
1314 resourceJars = append(resourceJars, includeSrcJar)
1315 }
1316 resourceJars = append(resourceJars, deps.staticResourceJars...)
1317
1318 if len(resourceJars) > 1 {
1319 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1320 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1321 false, nil, nil)
1322 j.resourceJar = combinedJar
1323 } else if len(resourceJars) == 1 {
1324 j.resourceJar = resourceJars[0]
1325 }
1326
1327 if len(deps.staticJars) > 0 {
1328 jars = append(jars, deps.staticJars...)
1329 }
1330
1331 manifest := j.overrideManifest
1332 if !manifest.Valid() && j.properties.Manifest != nil {
1333 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1334 }
1335
1336 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1337 if len(services) > 0 {
1338 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1339 var zipargs []string
1340 for _, file := range services {
1341 serviceFile := file.String()
1342 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1343 }
1344 rule := zip
1345 args := map[string]string{
1346 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1347 }
1348 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1349 rule = zipRE
1350 args["implicits"] = strings.Join(services.Strings(), ",")
1351 }
1352 ctx.Build(pctx, android.BuildParams{
1353 Rule: rule,
1354 Output: servicesJar,
1355 Implicits: services,
1356 Args: args,
1357 })
1358 jars = append(jars, servicesJar)
1359 }
1360
1361 // Combine the classes built from sources, any manifests, and any static libraries into
1362 // classes.jar. If there is only one input jar this step will be skipped.
1363 var outputFile android.OutputPath
1364
1365 if len(jars) == 1 && !manifest.Valid() {
1366 // Optimization: skip the combine step as there is nothing to do
1367 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1368 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1369 // any if len(jars) == 1.
1370
1371 // Transform the single path to the jar into an OutputPath as that is required by the following
1372 // code.
1373 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1374 // The path contains an embedded OutputPath so reuse that.
1375 outputFile = moduleOutPath.OutputPath
1376 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1377 // The path is an OutputPath so reuse it directly.
1378 outputFile = outputPath
1379 } else {
1380 // The file is not in the out directory so create an OutputPath into which it can be copied
1381 // and which the following code can use to refer to it.
1382 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1383 ctx.Build(pctx, android.BuildParams{
1384 Rule: android.Cp,
1385 Input: jars[0],
1386 Output: combinedJar,
1387 })
1388 outputFile = combinedJar.OutputPath
1389 }
1390 } else {
1391 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1392 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1393 false, nil, nil)
1394 outputFile = combinedJar.OutputPath
1395 }
1396
1397 // jarjar implementation jar if necessary
1398 if j.expandJarjarRules != nil {
1399 // Transform classes.jar into classes-jarjar.jar
1400 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1401 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1402 outputFile = jarjarFile
1403
1404 // jarjar resource jar if necessary
1405 if j.resourceJar != nil {
1406 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1407 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1408 j.resourceJar = resourceJarJarFile
1409 }
1410
1411 if ctx.Failed() {
1412 return
1413 }
1414 }
1415
1416 // Check package restrictions if necessary.
1417 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001418 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001419 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001420
1421 // Create a rule to copy the output jar to another path and add a validate dependency that
1422 // will check that the jar only contains the permitted packages. The new location will become
1423 // the output file of this module.
1424 inputFile := outputFile
1425 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1426 ctx.Build(pctx, android.BuildParams{
1427 Rule: android.Cp,
1428 Input: inputFile,
1429 Output: outputFile,
1430 // Make sure that any dependency on the output file will cause ninja to run the package check
1431 // rule.
1432 Validation: pkgckFile,
1433 })
1434
1435 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001436 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001437
1438 if ctx.Failed() {
1439 return
1440 }
1441 }
1442
1443 j.implementationJarFile = outputFile
1444 if j.headerJarFile == nil {
1445 j.headerJarFile = j.implementationJarFile
1446 }
1447
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001448 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1449 specs := j.jacocoModuleToZipCommand(ctx)
1450 if ctx.Failed() {
1451 return
1452 }
1453
Jaewoong Jung26342642021-03-17 15:56:23 -07001454 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001455 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 }
1457
1458 // merge implementation jar with resources if necessary
1459 implementationAndResourcesJar := outputFile
1460 if j.resourceJar != nil {
1461 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1462 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1463 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1464 false, nil, nil)
1465 implementationAndResourcesJar = combinedJar
1466 }
1467
1468 j.implementationAndResourcesJar = implementationAndResourcesJar
1469
1470 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001471 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001472 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1473 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001474 if compileDex == nil {
1475 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 }
1477 if j.deviceProperties.Hostdex == nil {
1478 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1479 }
1480 }
1481
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001482 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001483 if j.hasCode(ctx) {
1484 if j.shouldInstrumentStatic(ctx) {
1485 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1486 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1487 }
1488 // Dex compilation
1489 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001490 params := &compileDexParams{
1491 flags: flags,
1492 sdkVersion: j.SdkVersion(ctx),
1493 minSdkVersion: j.MinSdkVersion(ctx),
1494 classesJar: implementationAndResourcesJar,
1495 jarName: jarName,
1496 }
1497 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001498 if ctx.Failed() {
1499 return
1500 }
1501
Jaewoong Jung26342642021-03-17 15:56:23 -07001502 // merge dex jar with resources if necessary
1503 if j.resourceJar != nil {
1504 jars := android.Paths{dexOutputFile, j.resourceJar}
1505 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1506 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1507 false, nil, nil)
1508 if *j.dexProperties.Uncompress_dex {
1509 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1510 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1511 dexOutputFile = combinedAlignedJar
1512 } else {
1513 dexOutputFile = combinedJar
1514 }
1515 }
1516
Paul Duffin4de94502021-05-16 05:21:16 +01001517 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001518
1519 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001520
1521 // Encode hidden API flags in dex file, if needed.
1522 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1523
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001524 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001525
1526 // Dexpreopting
1527 j.dexpreopt(ctx, dexOutputFile)
1528
1529 outputFile = dexOutputFile
1530 } else {
1531 // There is no code to compile into a dex jar, make sure the resources are propagated
1532 // to the APK if this is an app.
1533 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001534 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001535 }
1536
1537 if ctx.Failed() {
1538 return
1539 }
1540 } else {
1541 outputFile = implementationAndResourcesJar
1542 }
1543
1544 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001545 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1546 if !apiLevel.IsPreview() {
1547 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001548 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001549 // When running metalava, we pass --version-codename. When that value
1550 // is not REL, metalava will add 1 to the --current-version argument.
1551 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1552 // branch) and the codename is REL, except potentially on the most
1553 // recent non-master branch. On that branch, it goes through two other
1554 // phases before it gets to the phase previously described:
1555 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1556 // is not rel. This happens for most of the internal branch's life
1557 // while the branch has been cut but is still under active development.
1558 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1559 // REL. This happens briefly during the release process. During this
1560 // state the code to add --current-version is commented out, and then
1561 // that commenting out is reverted after the codename is set to REL.
1562 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1563 // prior version and the codename is always non-REL.
1564 //
1565 // We need to add one here to match metalava adding 1. Technically
1566 // this means that in the state described in the second bullet point
1567 // above, this number is 1 higher than it should be.
1568 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001569 }
1570 }
1571
1572 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001573 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1574 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001575 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1576 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001577 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001578 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001579 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001580 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001581 j.linter.javaLanguageLevel = flags.javaVersion.String()
1582 j.linter.kotlinLanguageLevel = "1.3"
1583 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1584 j.linter.buildModuleReportZip = true
1585 }
1586 j.linter.lint(ctx)
1587 }
1588
1589 ctx.CheckbuildFile(outputFile)
1590
1591 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1592 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001593 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1594 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001595 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1596 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1597 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1598 AidlIncludeDirs: j.exportAidlIncludeDirs,
1599 SrcJarArgs: j.srcJarArgs,
1600 SrcJarDeps: j.srcJarDeps,
1601 ExportedPlugins: j.exportedPluginJars,
1602 ExportedPluginClasses: j.exportedPluginClasses,
1603 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1604 JacocoReportClassesFile: j.jacocoReportClassesFile,
1605 })
1606
1607 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1608 j.outputFile = outputFile.WithoutRel()
1609}
1610
Colin Crossa1ff7c62021-09-17 14:11:52 -07001611func (j *Module) useCompose() bool {
1612 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1613}
1614
Cole Faust75fffb12021-06-13 15:23:16 -07001615// Returns a copy of the supplied flags, but with all the errorprone-related
1616// fields copied to the regular build's fields.
1617func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1618 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1619
1620 if len(flags.errorProneExtraJavacFlags) > 0 {
1621 if len(flags.javacFlags) > 0 {
1622 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1623 } else {
1624 flags.javacFlags = flags.errorProneExtraJavacFlags
1625 }
1626 }
1627 return flags
1628}
1629
Jaewoong Jung26342642021-03-17 15:56:23 -07001630func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1631 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1632
1633 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1634 if idx >= 0 {
1635 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1636 jarName += strconv.Itoa(idx)
1637 }
1638
1639 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1640 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1641
1642 if ctx.Config().EmitXrefRules() {
1643 extractionFile := android.PathForModuleOut(ctx, kzipName)
1644 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1645 j.kytheFiles = append(j.kytheFiles, extractionFile)
1646 }
1647
1648 return classes
1649}
1650
1651// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1652// since some of these flags may be used internally.
1653func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1654 for _, flag := range flags {
1655 flag = strings.TrimSpace(flag)
1656
1657 if !strings.HasPrefix(flag, "-") {
1658 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1659 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1660 ctx.PropertyErrorf("kotlincflags",
1661 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1662 } else if inList(flag, config.KotlincIllegalFlags) {
1663 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1664 } else if flag == "-include-runtime" {
1665 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1666 } else {
1667 args := strings.Split(flag, " ")
1668 if args[0] == "-kotlin-home" {
1669 ctx.PropertyErrorf("kotlincflags",
1670 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1671 }
1672 }
1673 }
1674}
1675
1676func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1677 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001678 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001679
1680 var jars android.Paths
1681 if len(srcFiles) > 0 || len(srcJars) > 0 {
1682 // Compile java sources into turbine.jar.
1683 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1684 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1685 if ctx.Failed() {
1686 return nil, nil
1687 }
1688 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001689 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001690 }
1691
1692 jars = append(jars, extraJars...)
1693
1694 // Combine any static header libraries into classes-header.jar. If there is only
1695 // one input jar this step will be skipped.
1696 jars = append(jars, deps.staticHeaderJars...)
1697
1698 // we cannot skip the combine step for now if there is only one jar
1699 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1700 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1701 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1702 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001703 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001704
1705 if j.expandJarjarRules != nil {
1706 // Transform classes.jar into classes-jarjar.jar
1707 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001708 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1709 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001710 if ctx.Failed() {
1711 return nil, nil
1712 }
1713 }
1714
Colin Cross3d56ed52021-11-18 22:23:12 -08001715 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001716}
1717
1718func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001719 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001720
1721 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1722 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1723
1724 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1725
1726 j.jacocoReportClassesFile = jacocoReportClassesFile
1727
1728 return instrumentedJar
1729}
1730
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001731type providesTransitiveHeaderJars struct {
1732 // set of header jars for all transitive libs deps
1733 transitiveLibsHeaderJars *android.DepSet
1734 // set of header jars for all transitive static libs deps
1735 transitiveStaticLibsHeaderJars *android.DepSet
1736}
1737
1738func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
1739 return j.transitiveLibsHeaderJars
1740}
1741
1742func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
1743 return j.transitiveStaticLibsHeaderJars
1744}
1745
1746func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1747 directLibs := android.Paths{}
1748 directStaticLibs := android.Paths{}
1749 transitiveLibs := []*android.DepSet{}
1750 transitiveStaticLibs := []*android.DepSet{}
1751 ctx.VisitDirectDeps(func(module android.Module) {
1752 // don't add deps of the prebuilt version of the same library
1753 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1754 return
1755 }
1756
1757 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1758 if dep.TransitiveLibsHeaderJars != nil {
1759 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1760 }
1761 if dep.TransitiveStaticLibsHeaderJars != nil {
1762 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1763 }
1764
1765 tag := ctx.OtherModuleDependencyTag(module)
1766 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1767 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1768 directLibs = append(directLibs, dep.HeaderJars...)
1769 } else if tag == staticLibTag {
1770 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1771 }
1772 })
1773 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1774 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1775}
1776
Jaewoong Jung26342642021-03-17 15:56:23 -07001777func (j *Module) HeaderJars() android.Paths {
1778 if j.headerJarFile == nil {
1779 return nil
1780 }
1781 return android.Paths{j.headerJarFile}
1782}
1783
1784func (j *Module) ImplementationJars() android.Paths {
1785 if j.implementationJarFile == nil {
1786 return nil
1787 }
1788 return android.Paths{j.implementationJarFile}
1789}
1790
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001791func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001792 return j.dexJarFile
1793}
1794
1795func (j *Module) DexJarInstallPath() android.Path {
1796 return j.installFile
1797}
1798
1799func (j *Module) ImplementationAndResourcesJars() android.Paths {
1800 if j.implementationAndResourcesJar == nil {
1801 return nil
1802 }
1803 return android.Paths{j.implementationAndResourcesJar}
1804}
1805
1806func (j *Module) AidlIncludeDirs() android.Paths {
1807 // exportAidlIncludeDirs is type android.Paths already
1808 return j.exportAidlIncludeDirs
1809}
1810
1811func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1812 return j.classLoaderContexts
1813}
1814
1815// Collect information for opening IDE project files in java/jdeps.go.
1816func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1817 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1818 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1819 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1820 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1821 if j.expandJarjarRules != nil {
1822 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1823 }
1824 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001825 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1826 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001827}
1828
1829func (j *Module) CompilerDeps() []string {
1830 jdeps := []string{}
1831 jdeps = append(jdeps, j.properties.Libs...)
1832 jdeps = append(jdeps, j.properties.Static_libs...)
1833 return jdeps
1834}
1835
1836func (j *Module) hasCode(ctx android.ModuleContext) bool {
1837 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1838 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1839}
1840
1841// Implements android.ApexModule
1842func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1843 return j.depIsInSameApex(ctx, dep)
1844}
1845
1846// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001847func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001848 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001849 minSdkVersion := j.MinSdkVersion(ctx)
1850 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001851 return fmt.Errorf("min_sdk_version is not specified")
1852 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001853 // If the module is compiling against core (via sdk_version), skip comparison check.
1854 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001855 return nil
1856 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001857 if minSdkVersion.GreaterThan(sdkVersion) {
1858 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001859 }
1860 return nil
1861}
1862
1863func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001864 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001865}
1866
Jaewoong Jung26342642021-03-17 15:56:23 -07001867func (j *Module) JacocoReportClassesFile() android.Path {
1868 return j.jacocoReportClassesFile
1869}
1870
1871func (j *Module) IsInstallable() bool {
1872 return Bool(j.properties.Installable)
1873}
1874
1875type sdkLinkType int
1876
1877const (
1878 // TODO(jiyong) rename these for better readability. Make the allowed
1879 // and disallowed link types explicit
1880 // order is important here. See rank()
1881 javaCore sdkLinkType = iota
1882 javaSdk
1883 javaSystem
1884 javaModule
1885 javaSystemServer
1886 javaPlatform
1887)
1888
1889func (lt sdkLinkType) String() string {
1890 switch lt {
1891 case javaCore:
1892 return "core Java API"
1893 case javaSdk:
1894 return "Android API"
1895 case javaSystem:
1896 return "system API"
1897 case javaModule:
1898 return "module API"
1899 case javaSystemServer:
1900 return "system server API"
1901 case javaPlatform:
1902 return "private API"
1903 default:
1904 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1905 }
1906}
1907
1908// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1909// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1910// can't statically depend on modules that use Platform API.
1911func (lt sdkLinkType) rank() int {
1912 return int(lt)
1913}
1914
1915type moduleWithSdkDep interface {
1916 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001917 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001918}
1919
Jiyong Park92315372021-04-02 08:45:46 +09001920func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001921 switch name {
1922 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1923 "stub-annotations", "private-stub-annotations-jar",
1924 "core-lambda-stubs", "core-generated-annotation-stubs":
1925 return javaCore, true
Spandan Das626a8ad2023-03-20 18:52:50 +00001926 case android.SdkPublic.JavaLibraryName(ctx.Config()):
Jaewoong Jung26342642021-03-17 15:56:23 -07001927 return javaSdk, true
Spandan Das626a8ad2023-03-20 18:52:50 +00001928 case android.SdkSystem.JavaLibraryName(ctx.Config()):
Jaewoong Jung26342642021-03-17 15:56:23 -07001929 return javaSystem, true
Spandan Das626a8ad2023-03-20 18:52:50 +00001930 case android.SdkModule.JavaLibraryName(ctx.Config()):
Jaewoong Jung26342642021-03-17 15:56:23 -07001931 return javaModule, true
Spandan Das626a8ad2023-03-20 18:52:50 +00001932 case android.SdkSystemServer.JavaLibraryName(ctx.Config()):
Jaewoong Jung26342642021-03-17 15:56:23 -07001933 return javaSystemServer, true
Spandan Das626a8ad2023-03-20 18:52:50 +00001934 case android.SdkTest.JavaLibraryName(ctx.Config()):
Jaewoong Jung26342642021-03-17 15:56:23 -07001935 return javaSystem, true
1936 }
1937
1938 if stub, linkType := moduleStubLinkType(name); stub {
1939 return linkType, true
1940 }
1941
Jiyong Park92315372021-04-02 08:45:46 +09001942 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001943 switch ver.Kind {
1944 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001945 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001946 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001947 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001948 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001949 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001950 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001951 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001952 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001953 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001954 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001955 return javaPlatform, false
1956 }
1957
Jiyong Parkf1691d22021-03-29 20:11:58 +09001958 if !ver.Valid() {
1959 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001960 }
1961 return javaSdk, false
1962}
1963
1964// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1965// this module's. See the comment on rank() for details and an example.
1966func (j *Module) checkSdkLinkType(
1967 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1968 if ctx.Host() {
1969 return
1970 }
1971
Jiyong Park92315372021-04-02 08:45:46 +09001972 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001973 if stubs {
1974 return
1975 }
Jiyong Park92315372021-04-02 08:45:46 +09001976 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001977
1978 if myLinkType.rank() < depLinkType.rank() {
1979 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1980 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1981 "property of the source or target module so that target module is built "+
1982 "with the same or smaller API set when compared to the source.",
1983 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1984 }
1985}
1986
1987func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1988 var deps deps
1989
1990 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001991 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001992 if sdkDep.invalidVersion {
1993 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1994 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1995 } else if sdkDep.useFiles {
1996 // sdkDep.jar is actually equivalent to turbine header.jar.
1997 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001998 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001999 deps.aidlPreprocess = sdkDep.aidl
2000 } else {
2001 deps.aidlPreprocess = sdkDep.aidl
2002 }
2003 }
2004
Jiyong Park92315372021-04-02 08:45:46 +09002005 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002006
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002007 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002008 ctx.VisitDirectDeps(func(module android.Module) {
2009 otherName := ctx.OtherModuleName(module)
2010 tag := ctx.OtherModuleDependencyTag(module)
2011
2012 if IsJniDepTag(tag) {
2013 // Handled by AndroidApp.collectAppDeps
2014 return
2015 }
2016 if tag == certificateTag {
2017 // Handled by AndroidApp.collectAppDeps
2018 return
2019 }
2020
2021 if dep, ok := module.(SdkLibraryDependency); ok {
2022 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002023 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002024 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2025 deps.classpath = append(deps.classpath, depHeaderJars...)
2026 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002027 case staticLibTag:
2028 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2029 }
2030 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2031 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2032 if sdkLinkType != javaPlatform &&
2033 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2034 // dep is a sysprop implementation library, but this module is not linking against
2035 // the platform, so it gets the sysprop public stubs library instead. Replace
2036 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2037 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2038 dep = syspropDep.JavaInfo
2039 }
2040 switch tag {
2041 case bootClasspathTag:
2042 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002043 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002044 if _, ok := module.(*Plugin); ok {
2045 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2046 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002047 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002048 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002049 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2050 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2051 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2052 case java9LibTag:
2053 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2054 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002055 if _, ok := module.(*Plugin); ok {
2056 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2057 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002058 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2059 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2060 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2061 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2062 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2063 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2064 // Turbine doesn't run annotation processors, so any module that uses an
2065 // annotation processor that generates API is incompatible with the turbine
2066 // optimization.
2067 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2068 case pluginTag:
2069 if plugin, ok := module.(*Plugin); ok {
2070 if plugin.pluginProperties.Processor_class != nil {
2071 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2072 } else {
2073 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2074 }
2075 // Turbine doesn't run annotation processors, so any module that uses an
2076 // annotation processor that generates API is incompatible with the turbine
2077 // optimization.
2078 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2079 } else {
2080 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2081 }
2082 case errorpronePluginTag:
2083 if _, ok := module.(*Plugin); ok {
2084 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2085 } else {
2086 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2087 }
2088 case exportedPluginTag:
2089 if plugin, ok := module.(*Plugin); ok {
2090 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2091 if plugin.pluginProperties.Processor_class != nil {
2092 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2093 }
2094 // Turbine doesn't run annotation processors, so any module that uses an
2095 // annotation processor that generates API is incompatible with the turbine
2096 // optimization.
2097 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2098 } else {
2099 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2100 }
2101 case kotlinStdlibTag:
2102 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2103 case kotlinAnnotationsTag:
2104 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002105 case kotlinPluginTag:
2106 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002107 case syspropPublicStubDepTag:
2108 // This is a sysprop implementation library, forward the JavaInfoProvider from
2109 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2110 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2111 JavaInfo: dep,
2112 })
2113 }
2114 } else if dep, ok := module.(android.SourceFileProducer); ok {
2115 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002116 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002117 checkProducesJars(ctx, dep)
2118 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002119 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002120 case staticLibTag:
2121 checkProducesJars(ctx, dep)
2122 deps.classpath = append(deps.classpath, dep.Srcs()...)
2123 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2124 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2125 }
2126 } else {
2127 switch tag {
2128 case bootClasspathTag:
2129 // If a system modules dependency has been added to the bootclasspath
2130 // then add its libs to the bootclasspath.
2131 sm := module.(SystemModulesProvider)
2132 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2133
2134 case systemModulesTag:
2135 if deps.systemModules != nil {
2136 panic("Found two system module dependencies")
2137 }
2138 sm := module.(SystemModulesProvider)
2139 outputDir, outputDeps := sm.OutputDirAndDeps()
2140 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002141
2142 case instrumentationForTag:
2143 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 -07002144 }
2145 }
2146
2147 addCLCFromDep(ctx, module, j.classLoaderContexts)
2148 })
2149
2150 return deps
2151}
2152
2153func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2154 deps.processorPath = append(deps.processorPath, pluginJars...)
2155 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2156}
2157
2158// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2159// this interface.
2160type ProvidesUsesLib interface {
2161 ProvidesUsesLib() *string
2162}
2163
2164func (j *Module) ProvidesUsesLib() *string {
2165 return j.usesLibraryProperties.Provides_uses_lib
2166}
satayev1c564cc2021-05-25 19:50:30 +01002167
2168type ModuleWithStem interface {
2169 Stem() string
2170}
2171
2172var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002173
2174func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2175 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002176 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002177 if lib, ok := ctx.Module().(*Library); ok {
2178 javaLibraryBp2Build(ctx, lib)
2179 }
2180 case "java_binary_host":
2181 if binary, ok := ctx.Module().(*Binary); ok {
2182 javaBinaryHostBp2Build(ctx, binary)
2183 }
2184 }
Wei Libafb6d62021-12-10 03:14:59 -08002185}