blob: afb626a49e67ffc33736fc9a05456eae138402a3 [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
Jihoon Kang381c2fa2023-06-01 22:17:32 +000082 // list of java libraries that should not be used to build this module
83 Exclude_static_libs []string `android:"arch_variant"`
84
Jaewoong Jung26342642021-03-17 15:56:23 -070085 // manifest file to be included in resulting jar
86 Manifest *string `android:"path"`
87
88 // if not blank, run jarjar using the specified rules file
89 Jarjar_rules *string `android:"path,arch_variant"`
90
91 // If not blank, set the java version passed to javac as -source and -target
92 Java_version *string
93
94 // If set to true, allow this module to be dexed and installed on devices. Has no
95 // effect on host modules, which are always considered installable.
96 Installable *bool
97
98 // If set to true, include sources used to compile the module in to the final jar
99 Include_srcs *bool
100
101 // If not empty, classes are restricted to the specified packages and their sub-packages.
102 // This restriction is checked after applying jarjar rules and including static libs.
103 Permitted_packages []string
104
105 // List of modules to use as annotation processors
106 Plugins []string
107
108 // List of modules to export to libraries that directly depend on this library as annotation
109 // processors. Note that if the plugins set generates_api: true this will disable the turbine
110 // optimization on modules that depend on this module, which will reduce parallelism and cause
111 // more recompilation.
112 Exported_plugins []string
113
114 // The number of Java source entries each Javac instance can process
115 Javac_shard_size *int64
116
117 // Add host jdk tools.jar to bootclasspath
118 Use_tools_jar *bool
119
120 Openjdk9 struct {
121 // List of source files that should only be used when passing -source 1.9 or higher
122 Srcs []string `android:"path"`
123
124 // List of javac flags that should only be used when passing -source 1.9 or higher
125 Javacflags []string
126 }
127
128 // When compiling language level 9+ .java code in packages that are part of
129 // a system module, patch_module names the module that your sources and
130 // dependencies should be patched into. The Android runtime currently
131 // doesn't implement the JEP 261 module system so this option is only
132 // supported at compile time. It should only be needed to compile tests in
133 // packages that exist in libcore and which are inconvenient to move
134 // elsewhere.
135 Patch_module *string `android:"arch_variant"`
136
137 Jacoco struct {
138 // List of classes to include for instrumentation with jacoco to collect coverage
139 // information at runtime when building with coverage enabled. If unset defaults to all
140 // classes.
141 // Supports '*' as the last character of an entry in the list as a wildcard match.
142 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
143 // it matches classes in the package that have the class name as a prefix.
144 Include_filter []string
145
146 // List of classes to exclude from instrumentation with jacoco to collect coverage
147 // information at runtime when building with coverage enabled. Overrides classes selected
148 // by the include_filter property.
149 // Supports '*' as the last character of an entry in the list as a wildcard match.
150 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
151 // it matches classes in the package that have the class name as a prefix.
152 Exclude_filter []string
153 }
154
155 Errorprone struct {
156 // List of javac flags that should only be used when running errorprone.
157 Javacflags []string
158
159 // List of java_plugin modules that provide extra errorprone checks.
160 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700161
Cole Faust2b1536e2021-06-18 12:25:54 -0700162 // This property can be in 3 states. When set to true, errorprone will
163 // be run during the regular build. When set to false, errorprone will
164 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
165 // environment variable is true. Setting this to false will improve build
166 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700167 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700168 }
169
170 Proto struct {
171 // List of extra options that will be passed to the proto generator.
172 Output_params []string
173 }
174
Sam Delmericoc7593722022-08-31 15:57:52 -0400175 // If true, then jacocoagent is automatically added as a libs dependency so that
176 // r8 will not strip instrumentation classes out of dexed libraries.
Jaewoong Jung26342642021-03-17 15:56:23 -0700177 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000178 // If true, then the module supports statically including the jacocoagent
179 // into the library.
180 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700181
182 // List of files to include in the META-INF/services folder of the resulting jar.
183 Services []string `android:"path,arch_variant"`
184
185 // If true, package the kotlin stdlib into the jar. Defaults to true.
186 Static_kotlin_stdlib *bool `android:"arch_variant"`
187
188 // A list of java_library instances that provide additional hiddenapi annotations for the library.
189 Hiddenapi_additional_annotations []string
Joe Onorato175073c2023-06-01 14:42:59 -0700190
191 // Additional srcJars tacked in by GeneratedJavaLibraryModule
192 Generated_srcjars []android.Path `android:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700193}
194
195// Properties that are specific to device modules. Host module factories should not add these when
196// constructing a new module.
197type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000198 // If not blank, set to the version of the sdk to compile against.
Spandan Das1ccf5742022-10-14 16:51:23 +0000199 // Defaults to an empty string, which compiles the module against the private platform APIs.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000200 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000201 // 1) numerical API level, "current", "none", or "core_platform"
202 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
203 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
204 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700205 Sdk_version *string
206
207 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000208 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700209 Min_sdk_version *string
210
satayev0a420e72021-11-29 17:25:52 +0000211 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
212 // Defaults to empty string "". See sdk_version for possible values.
213 Max_sdk_version *string
214
William Loh5a082f92022-05-17 20:21:50 +0000215 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
216 // Defaults to empty string "". See sdk_version for possible values.
217 Replace_max_sdk_version_placeholder *string
218
Jaewoong Jung26342642021-03-17 15:56:23 -0700219 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000220 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700221 Target_sdk_version *string
222
223 // Whether to compile against the platform APIs instead of an SDK.
224 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000225 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700226 Platform_apis *bool
227
228 Aidl struct {
229 // Top level directories to pass to aidl tool
230 Include_dirs []string
231
232 // Directories rooted at the Android.bp file to pass to aidl tool
233 Local_include_dirs []string
234
235 // directories that should be added as include directories for any aidl sources of modules
236 // that depend on this module, as well as to aidl for this module.
237 Export_include_dirs []string
238
239 // whether to generate traces (for systrace) for this interface
240 Generate_traces *bool
241
242 // whether to generate Binder#GetTransaction name method.
243 Generate_get_transaction_name *bool
244
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100245 // whether all interfaces should be annotated with required permissions.
246 Enforce_permissions *bool
247
248 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
249 Enforce_permissions_exceptions []string `android:"path"`
250
Jaewoong Jung26342642021-03-17 15:56:23 -0700251 // list of flags that will be passed to the AIDL compiler
252 Flags []string
253 }
254
255 // If true, export a copy of the module as a -hostdex module for host testing.
256 Hostdex *bool
257
258 Target struct {
259 Hostdex struct {
260 // Additional required dependencies to add to -hostdex modules.
261 Required []string
262 }
263 }
264
265 // When targeting 1.9 and above, override the modules to use with --system,
266 // otherwise provides defaults libraries to add to the bootclasspath.
267 System_modules *string
268
Jaewoong Jung26342642021-03-17 15:56:23 -0700269 IsSDKLibrary bool `blueprint:"mutated"`
270
271 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
272 // Defaults to false.
273 V4_signature *bool
274
275 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
276 // public stubs library.
277 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000278
279 HiddenAPIPackageProperties
280 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700281}
282
Jooyung Han01d80d82022-01-08 12:16:32 +0900283// Device properties that can be overridden by overriding module (e.g. override_android_app)
284type OverridableDeviceProperties struct {
285 // set the name of the output. If not set, `name` is used.
286 // To override a module with this property set, overriding module might need to set this as well.
287 // Otherwise, both the overridden and the overriding modules will have the same output name, which
288 // can cause the duplicate output error.
289 Stem *string
290}
291
Jaewoong Jung26342642021-03-17 15:56:23 -0700292// Functionality common to Module and Import
293//
294// It is embedded in Module so its functionality can be used by methods in Module
295// but it is currently only initialized by Import and Library.
296type embeddableInModuleAndImport struct {
297
298 // Functionality related to this being used as a component of a java_sdk_library.
299 EmbeddableSdkLibraryComponent
300}
301
Paul Duffin71b33cc2021-06-23 11:39:47 +0100302func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
303 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700304}
305
306// Module/Import's DepIsInSameApex(...) delegates to this method.
307//
308// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
309// the one provided by ApexModuleBase.
310func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
311 // dependencies other than the static linkage are all considered crossing APEX boundary
312 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
313 return true
314 }
315 return false
316}
317
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100318// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
319// or an invalid path describing the reason it is invalid.
320//
321// It is unset if a dex jar isn't applicable, i.e. no build rule has been
322// requested to create one.
323//
324// If a dex jar has been requested to be built then it is set, and it may be
325// either a valid android.Path, or invalid with a reason message. The latter
326// happens if the source that should produce the dex file isn't able to.
327//
328// E.g. it is invalid with a reason message if there is a prebuilt APEX that
329// could produce the dex jar through a deapexer module, but the APEX isn't
330// installable so doing so wouldn't be safe.
331type OptionalDexJarPath struct {
332 isSet bool
333 path android.OptionalPath
334}
335
336// IsSet returns true if a path has been set, either invalid or valid.
337func (o OptionalDexJarPath) IsSet() bool {
338 return o.isSet
339}
340
341// Valid returns true if there is a path that is valid.
342func (o OptionalDexJarPath) Valid() bool {
343 return o.isSet && o.path.Valid()
344}
345
346// Path returns the valid path, or panics if it's either not set or is invalid.
347func (o OptionalDexJarPath) Path() android.Path {
348 if !o.isSet {
349 panic("path isn't set")
350 }
351 return o.path.Path()
352}
353
354// PathOrNil returns the path if it's set and valid, or else nil.
355func (o OptionalDexJarPath) PathOrNil() android.Path {
356 if o.Valid() {
357 return o.Path()
358 }
359 return nil
360}
361
362// InvalidReason returns the reason for an invalid path, which is never "". It
363// returns "" for an unset or valid path.
364func (o OptionalDexJarPath) InvalidReason() string {
365 if !o.isSet {
366 return ""
367 }
368 return o.path.InvalidReason()
369}
370
371func (o OptionalDexJarPath) String() string {
372 if !o.isSet {
373 return "<unset>"
374 }
375 return o.path.String()
376}
377
378// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
379func makeUnsetDexJarPath() OptionalDexJarPath {
380 return OptionalDexJarPath{isSet: false}
381}
382
383// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
384// the given OptionalPath, which may be valid or invalid.
385func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
386 return OptionalDexJarPath{isSet: true, path: path}
387}
388
389// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
390// valid given path. It returns an unset OptionalDexJarPath if the given path is
391// nil.
392func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
393 if path == nil {
394 return makeUnsetDexJarPath()
395 }
396 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
397}
398
Jaewoong Jung26342642021-03-17 15:56:23 -0700399// Module contains the properties and members used by all java module types
400type Module struct {
401 android.ModuleBase
402 android.DefaultableModuleBase
403 android.ApexModuleBase
Wei Libafb6d62021-12-10 03:14:59 -0800404 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700405
406 // Functionality common to Module and Import.
407 embeddableInModuleAndImport
408
409 properties CommonProperties
410 protoProperties android.ProtoProperties
411 deviceProperties DeviceProperties
412
Jooyung Han01d80d82022-01-08 12:16:32 +0900413 overridableDeviceProperties OverridableDeviceProperties
414
Jaewoong Jung26342642021-03-17 15:56:23 -0700415 // jar file containing header classes including static library dependencies, suitable for
416 // inserting into the bootclasspath/classpath of another compile
417 headerJarFile android.Path
418
419 // jar file containing implementation classes including static library dependencies but no
420 // resources
421 implementationJarFile android.Path
422
423 // jar file containing only resources including from static library dependencies
424 resourceJar android.Path
425
426 // args and dependencies to package source files into a srcjar
427 srcJarArgs []string
428 srcJarDeps android.Paths
429
430 // jar file containing implementation classes and resources including static library
431 // dependencies
432 implementationAndResourcesJar android.Path
433
434 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100435 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700436
437 // output file containing uninstrumented classes that will be instrumented by jacoco
438 jacocoReportClassesFile android.Path
439
440 // output file of the module, which may be a classes jar or a dex jar
441 outputFile android.Path
442 extraOutputFiles android.Paths
443
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100444 exportAidlIncludeDirs android.Paths
445 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700446
447 logtagsSrcs android.Paths
448
449 // installed file for binary dependency
450 installFile android.Path
451
Colin Cross3108ce12021-11-10 14:38:50 -0800452 // installed file for hostdex copy
453 hostdexInstallFile android.InstallPath
454
Chaohui Wangdcbe33c2022-10-11 11:13:30 +0800455 // list of unique .java and .kt source files
456 uniqueSrcFiles android.Paths
457
458 // list of srcjars that was passed to javac
459 compiledSrcJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700460
461 // manifest file to use instead of properties.Manifest
462 overrideManifest android.OptionalPath
463
Jaewoong Jung26342642021-03-17 15:56:23 -0700464 // list of plugins that this java module is exporting
465 exportedPluginJars android.Paths
466
467 // list of plugins that this java module is exporting
468 exportedPluginClasses []string
469
470 // if true, the exported plugins generate API and require disabling turbine.
471 exportedDisableTurbine bool
472
473 // list of source files, collected from srcFiles with unique java and all kt files,
474 // will be used by android.IDEInfo struct
475 expandIDEInfoCompiledSrcs []string
476
477 // expanded Jarjar_rules
478 expandJarjarRules android.Path
479
Jaewoong Jung26342642021-03-17 15:56:23 -0700480 // Extra files generated by the module type to be added as java resources.
481 extraResources android.Paths
482
483 hiddenAPI
484 dexer
485 dexpreopter
486 usesLibrary
487 linter
488
489 // list of the xref extraction files
490 kytheFiles android.Paths
491
492 // Collect the module directory for IDE info in java/jdeps.go.
493 modulePaths []string
494
495 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900496
497 sdkVersion android.SdkSpec
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000498 minSdkVersion android.ApiLevel
Spandan Dasa26eda72023-03-02 00:56:06 +0000499 maxSdkVersion android.ApiLevel
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400500
501 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700502}
503
Jiyong Park92315372021-04-02 08:45:46 +0900504func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
505 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900506 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700507 return nil
508 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900509 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000510 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700511 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
512 } else {
513 // Treat stable core platform as stable.
514 return nil
515 }
516 } else {
517 return fmt.Errorf("non stable SDK %v", sdkVersion)
518 }
519}
520
521// checkSdkVersions enforces restrictions around SDK dependencies.
522func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
523 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900524 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900525 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700526 ctx.PropertyErrorf("sdk_version",
527 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
528 }
529 }
530 }
531
532 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
533 // See rank() for details.
534 ctx.VisitDirectDeps(func(module android.Module) {
535 tag := ctx.OtherModuleDependencyTag(module)
536 switch module.(type) {
537 // TODO(satayev): cover other types as well, e.g. imports
538 case *Library, *AndroidLibrary:
539 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -0400540 case bootClasspathTag, sdkLibTag, libTag, staticLibTag, java9LibTag:
Jaewoong Jung26342642021-03-17 15:56:23 -0700541 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
542 }
543 }
544 })
545}
546
547func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900548 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700549 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900550 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700551 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000552 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 -0700553 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000554 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 -0700555 }
556
557 }
558}
559
560func (j *Module) addHostProperties() {
561 j.AddProperties(
562 &j.properties,
563 &j.protoProperties,
564 &j.usesLibraryProperties,
565 )
566}
567
568func (j *Module) addHostAndDeviceProperties() {
569 j.addHostProperties()
570 j.AddProperties(
571 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900572 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700573 &j.dexer.dexProperties,
574 &j.dexpreoptProperties,
575 &j.linter.properties,
576 )
577}
578
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000579// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
580// makes it available through the hiddenAPIPropertyInfoProvider.
581func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
582 hiddenAPIInfo := newHiddenAPIPropertyInfo()
583
584 // Populate with flag file paths from the properties.
585 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
586
587 // Populate with package rules from the properties.
588 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
589
590 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
591}
592
Jaewoong Jung26342642021-03-17 15:56:23 -0700593func (j *Module) OutputFiles(tag string) (android.Paths, error) {
594 switch tag {
595 case "":
596 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
597 case android.DefaultDistTag:
598 return android.Paths{j.outputFile}, nil
599 case ".jar":
600 return android.Paths{j.implementationAndResourcesJar}, nil
Colin Crossab50dea2022-10-14 11:45:44 -0700601 case ".hjar":
602 return android.Paths{j.headerJarFile}, nil
Jaewoong Jung26342642021-03-17 15:56:23 -0700603 case ".proguard_map":
604 if j.dexer.proguardDictionary.Valid() {
605 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
606 }
607 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
608 default:
609 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
610 }
611}
612
613var _ android.OutputFileProducer = (*Module)(nil)
614
615func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
616 initJavaModule(module, hod, false)
617}
618
619func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
620 initJavaModule(module, hod, true)
621}
622
623func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
624 multilib := android.MultilibCommon
625 if multiTargets {
626 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
627 } else {
628 android.InitAndroidArchModule(module, hod, multilib)
629 }
630 android.InitDefaultableModule(module)
631}
632
633func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
634 return j.properties.Instrument &&
635 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
636 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
637}
638
639func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000640 return j.properties.Supports_static_instrumentation &&
641 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700642 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
643 ctx.Config().UnbundledBuild())
644}
645
646func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
647 // Force enable the instrumentation for java code that is built for APEXes ...
648 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
649 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
650 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
651 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
652 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
653 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
654 return true
655 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
656 return true
657 }
658 }
659 return false
660}
661
Sam Delmerico1e3f78f2022-09-07 12:07:07 -0400662func (j *Module) setInstrument(value bool) {
663 j.properties.Instrument = value
664}
665
Jiyong Park92315372021-04-02 08:45:46 +0900666func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
667 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700668}
669
Jiyong Parkf1691d22021-03-29 20:11:58 +0900670func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700671 return proptools.String(j.deviceProperties.System_modules)
672}
673
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000674func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jaewoong Jung26342642021-03-17 15:56:23 -0700675 if j.deviceProperties.Min_sdk_version != nil {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000676 return android.ApiLevelFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700677 }
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000678 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700679}
680
Spandan Dasa26eda72023-03-02 00:56:06 +0000681func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
682 if j.deviceProperties.Max_sdk_version != nil {
683 return android.ApiLevelFrom(ctx, *j.deviceProperties.Max_sdk_version)
684 }
685 // Default is PrivateApiLevel
686 return android.SdkSpecPrivate.ApiLevel
satayev0a420e72021-11-29 17:25:52 +0000687}
688
Spandan Dasa26eda72023-03-02 00:56:06 +0000689func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.ApiLevel {
690 if j.deviceProperties.Replace_max_sdk_version_placeholder != nil {
691 return android.ApiLevelFrom(ctx, *j.deviceProperties.Replace_max_sdk_version_placeholder)
692 }
693 // Default is PrivateApiLevel
694 return android.SdkSpecPrivate.ApiLevel
William Loh5a082f92022-05-17 20:21:50 +0000695}
696
Jiyong Parkf1691d22021-03-29 20:11:58 +0900697func (j *Module) MinSdkVersionString() string {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000698 return j.minSdkVersion.String()
Jiyong Park92315372021-04-02 08:45:46 +0900699}
700
Spandan Dasca70fc42023-03-01 23:38:49 +0000701func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel {
Jiyong Park92315372021-04-02 08:45:46 +0900702 if j.deviceProperties.Target_sdk_version != nil {
Spandan Dasca70fc42023-03-01 23:38:49 +0000703 return android.ApiLevelFrom(ctx, *j.deviceProperties.Target_sdk_version)
Jiyong Park92315372021-04-02 08:45:46 +0900704 }
Spandan Dasca70fc42023-03-01 23:38:49 +0000705 return j.SdkVersion(ctx).ApiLevel
Jaewoong Jung26342642021-03-17 15:56:23 -0700706}
707
708func (j *Module) AvailableFor(what string) bool {
709 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
710 // Exception: for hostdex: true libraries, the platform variant is created
711 // even if it's not marked as available to platform. In that case, the platform
712 // variant is used only for the hostdex and not installed to the device.
713 return true
714 }
715 return j.ApexModuleBase.AvailableFor(what)
716}
717
718func (j *Module) deps(ctx android.BottomUpMutatorContext) {
719 if ctx.Device() {
720 j.linter.deps(ctx)
721
Jiyong Parkf1691d22021-03-29 20:11:58 +0900722 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700723
724 if j.deviceProperties.SyspropPublicStub != "" {
725 // This is a sysprop implementation library that has a corresponding sysprop public
726 // stubs library, and a dependency on it so that dependencies on the implementation can
727 // be forwarded to the public stubs library when necessary.
728 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
729 }
730 }
731
732 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
Jihoon Kang381c2fa2023-06-01 22:17:32 +0000733
734 j.properties.Static_libs = android.RemoveListFromList(j.properties.Static_libs, j.properties.Exclude_static_libs)
Jaewoong Jung26342642021-03-17 15:56:23 -0700735 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
736
737 // Add dependency on libraries that provide additional hidden api annotations.
738 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
739
740 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
741 // Require java_sdk_library at inter-partition java dependency to ensure stable
742 // interface between partitions. If inter-partition java_library dependency is detected,
743 // raise build error because java_library doesn't have a stable interface.
744 //
745 // Inputs:
746 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
747 // if true, enable enforcement
748 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
749 // exception list of java_library names to allow inter-partition dependency
750 for idx := range j.properties.Libs {
751 if libDeps[idx] == nil {
752 continue
753 }
754
755 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
756 // java_sdk_library is always allowed at inter-partition dependency.
757 // So, skip check.
758 if _, ok := javaDep.(*SdkLibrary); ok {
759 continue
760 }
761
762 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
763 }
764 }
765 }
766
767 // For library dependencies that are component libraries (like stubs), add the implementation
768 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
769 for _, dep := range libDeps {
770 if dep != nil {
771 if component, ok := dep.(SdkLibraryComponentDependency); ok {
772 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100773 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100774 tag := usesLibReqTag
775 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
776 tag = usesLibOptTag
777 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100778 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700779 }
780 }
781 }
782 }
783
784 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
785 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
786 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
787
788 android.ProtoDeps(ctx, &j.protoProperties)
789 if j.hasSrcExt(".proto") {
790 protoDeps(ctx, &j.protoProperties)
791 }
792
793 if j.hasSrcExt(".kt") {
794 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
795 // Kotlin files
796 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
797 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700798 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700799 }
800
801 // Framework libraries need special handling in static coverage builds: they should not have
802 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
803 // the same jacoco classes coming from different bootclasspath jars.
804 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
805 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
806 j.properties.Instrument = true
807 }
808 } else if j.shouldInstrumentStatic(ctx) {
809 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
810 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700811
812 if j.useCompose() {
813 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
814 "androidx.compose.compiler_compiler-hosted")
815 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700816}
817
818func hasSrcExt(srcs []string, ext string) bool {
819 for _, src := range srcs {
820 if filepath.Ext(src) == ext {
821 return true
822 }
823 }
824
825 return false
826}
827
828func (j *Module) hasSrcExt(ext string) bool {
829 return hasSrcExt(j.properties.Srcs, ext)
830}
831
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100832func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
833 var flags string
834
835 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
836 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
837 flags = "-Wmissing-permission-annotation -Werror"
838 }
839 }
840 return flags
841}
842
Jaewoong Jung26342642021-03-17 15:56:23 -0700843func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000844 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700845
846 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
847 aidlIncludes = append(aidlIncludes,
848 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
849 aidlIncludes = append(aidlIncludes,
850 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
851
852 var flags []string
853 var deps android.Paths
Sam Delmerico2351eac2022-05-24 17:10:02 +0000854 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700855
856 flags = append(flags, j.deviceProperties.Aidl.Flags...)
857
858 if aidlPreprocess.Valid() {
859 flags = append(flags, "-p"+aidlPreprocess.String())
860 deps = append(deps, aidlPreprocess.Path())
861 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000862 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700863 }
864
865 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000866 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700867 }
868
869 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000870 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700871 }
872
Sam Delmerico2351eac2022-05-24 17:10:02 +0000873 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700874 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000875 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700876 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000877 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
878 // add flags for dirs containing AIDL srcs that haven't been specified yet
879 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700880
Zim8774ae12022-08-17 11:46:34 +0100881 sdkVersion := (j.SdkVersion(ctx)).Kind
Parth Sane000cbe02022-11-22 13:01:22 +0000882 defaultTrace := ((sdkVersion == android.SdkSystemServer) || (sdkVersion == android.SdkCore) || (sdkVersion == android.SdkCorePlatform) || (sdkVersion == android.SdkModule) || (sdkVersion == android.SdkSystem))
Zim8774ae12022-08-17 11:46:34 +0100883 if proptools.BoolDefault(j.deviceProperties.Aidl.Generate_traces, defaultTrace) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 flags = append(flags, "-t")
885 }
886
887 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
888 flags = append(flags, "--transaction_names")
889 }
890
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100891 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
892 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
893 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
894 }
895
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000896 aidlMinSdkVersion := j.MinSdkVersion(ctx).String()
Jooyung Han07f70c02021-11-06 07:08:45 +0900897 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
898
Jaewoong Jung26342642021-03-17 15:56:23 -0700899 return strings.Join(flags, " "), deps
900}
901
902func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
903
904 var flags javaBuilderFlags
905
906 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900907 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700908
Cole Faust2b1536e2021-06-18 12:25:54 -0700909 epEnabled := j.properties.Errorprone.Enabled
910 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Paul Duffin74135582022-10-06 11:01:59 +0100911 if config.ErrorProneClasspath == nil && !ctx.Config().RunningInsideUnitTest() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
913 }
914
915 errorProneFlags := []string{
916 "-Xplugin:ErrorProne",
917 "${config.ErrorProneChecks}",
918 }
919 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
920
Colin Cross8bf6cad2022-02-28 13:07:03 -0800921 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700922 "'" + strings.Join(errorProneFlags, " ") + "'"
923 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
924 }
925
926 // classpath
927 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
928 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700929 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700930 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
931 flags.processorPath = append(flags.processorPath, deps.processorPath...)
932 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
933
934 flags.processors = append(flags.processors, deps.processorClasses...)
935 flags.processors = android.FirstUniqueStrings(flags.processors)
936
937 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900938 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700939 // Give host-side tools a version of OpenJDK's standard libraries
940 // close to what they're targeting. As of Dec 2017, AOSP is only
941 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
942 //
943 // When building with OpenJDK 8, the following should have no
944 // effect since those jars would be available by default.
945 //
946 // When building with OpenJDK 9 but targeting a version < 1.8,
947 // putting them on the bootclasspath means that:
948 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
949 // b) references to existing APIs are not reinterpreted in an
950 // OpenJDK 9-specific way, eg. calls to subclasses of
951 // java.nio.Buffer as in http://b/70862583
952 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
953 flags.bootClasspath = append(flags.bootClasspath,
954 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
955 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
956 if Bool(j.properties.Use_tools_jar) {
957 flags.bootClasspath = append(flags.bootClasspath,
958 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
959 }
960 }
961
962 // systemModules
963 flags.systemModules = deps.systemModules
964
Jaewoong Jung26342642021-03-17 15:56:23 -0700965 return flags
966}
967
968func (j *Module) collectJavacFlags(
969 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
970 // javac flags.
971 javacFlags := j.properties.Javacflags
972
973 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
974 // For non-host binaries, override the -g flag passed globally to remove
975 // local variable debug info to reduce disk and memory usage.
976 javacFlags = append(javacFlags, "-g:source,lines")
977 }
978 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
979
980 if flags.javaVersion.usesJavaModules() {
981 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
982
983 if j.properties.Patch_module != nil {
984 // Manually specify build directory in case it is not under the repo root.
985 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
986 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200987 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700988
989 // b/150878007
990 //
991 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
992 // execution root for --patch-module. If this javac command line is
993 // invoked within Bazel's execution root working directory, the top
994 // level directories (e.g. libcore/, tools/, frameworks/) are all
995 // symlinks. JDK9 javac does not traverse into symlinks, which causes
996 // --patch-module to fail source file lookups when invoked in the
997 // execution root.
998 //
999 // Short of patching javac or enumerating *all* directories as possible
1000 // input dirs, manually add the top level dir of the source files to be
1001 // compiled.
1002 topLevelDirs := map[string]bool{}
1003 for _, srcFilePath := range srcFiles {
1004 srcFileParts := strings.Split(srcFilePath.String(), "/")
1005 // Ignore source files that are already in the top level directory
1006 // as well as generated files in the out directory. The out
1007 // directory may be an absolute path, which means srcFileParts[0] is the
1008 // empty string, so check that as well. Note that "out" in Bazel's execution
1009 // root is *not* a symlink, which doesn't cause problems for --patch-modules
1010 // anyway, so it's fine to not apply this workaround for generated
1011 // source files.
1012 if len(srcFileParts) > 1 &&
1013 srcFileParts[0] != "" &&
1014 srcFileParts[0] != "out" {
1015 topLevelDirs[srcFileParts[0]] = true
1016 }
1017 }
Cole Faust18994c72023-02-28 16:02:16 -08001018 patchPaths = append(patchPaths, android.SortedKeys(topLevelDirs)...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001019
1020 classPath := flags.classpath.FormJavaClassPath("")
1021 if classPath != "" {
1022 patchPaths = append(patchPaths, classPath)
1023 }
1024 javacFlags = append(
1025 javacFlags,
1026 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1027 }
1028 }
1029
1030 if len(javacFlags) > 0 {
1031 // optimization.
1032 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1033 flags.javacFlags = "$javacFlags"
1034 }
1035
1036 return flags
1037}
1038
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001039func (j *Module) AddJSONData(d *map[string]interface{}) {
1040 (&j.ModuleBase).AddJSONData(d)
1041 (*d)["Java"] = map[string]interface{}{
1042 "SourceExtensions": j.sourceExtensions,
1043 }
1044
1045}
1046
Joe Onorato175073c2023-06-01 14:42:59 -07001047func (module *Module) addGeneratedSrcJars(path android.Path) {
1048 module.properties.Generated_srcjars = append(module.properties.Generated_srcjars, path)
1049}
1050
Jaewoong Jung26342642021-03-17 15:56:23 -07001051func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1052 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1053
1054 deps := j.collectDeps(ctx)
1055 flags := j.collectBuilderFlags(ctx, deps)
1056
1057 if flags.javaVersion.usesJavaModules() {
1058 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1059 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001060
Jaewoong Jung26342642021-03-17 15:56:23 -07001061 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001062 j.sourceExtensions = []string{}
1063 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1064 if hasSrcExt(srcFiles.Strings(), ext) {
1065 j.sourceExtensions = append(j.sourceExtensions, ext)
1066 }
1067 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001068 if hasSrcExt(srcFiles.Strings(), ".proto") {
1069 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1070 }
1071
1072 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1073 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1074 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1075 }
1076
Sam Delmerico2351eac2022-05-24 17:10:02 +00001077 aidlSrcs := srcFiles.FilterByExt(".aidl")
1078 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1079
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001080 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001081 srcFiles = j.genSources(ctx, srcFiles, flags)
1082
1083 // Collect javac flags only after computing the full set of srcFiles to
1084 // ensure that the --patch-module lookup paths are complete.
1085 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1086
1087 srcJars := srcFiles.FilterByExt(".srcjar")
1088 srcJars = append(srcJars, deps.srcJars...)
1089 if aaptSrcJar != nil {
1090 srcJars = append(srcJars, aaptSrcJar)
1091 }
Joe Onorato175073c2023-06-01 14:42:59 -07001092 srcJars = append(srcJars, j.properties.Generated_srcjars...)
1093 if len(j.properties.Generated_srcjars) > 0 {
1094 fmt.Printf("Java module %s Generated_srcjars: %v\n", ctx.ModuleName(), j.properties.Generated_srcjars)
1095 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001096 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001097
1098 if j.properties.Jarjar_rules != nil {
1099 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1100 }
1101
1102 jarName := ctx.ModuleName() + ".jar"
1103
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001104 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001105 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001106 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 if _, found := set[v.String()]; !found {
1108 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001109 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001110 }
1111 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001112 var uniqueKtFiles android.Paths
1113 for _, v := range srcFiles.FilterByExt(".kt") {
1114 if _, found := set[v.String()]; !found {
1115 set[v.String()] = true
1116 uniqueKtFiles = append(uniqueKtFiles, v)
1117 }
1118 }
1119
1120 var uniqueSrcFiles android.Paths
1121 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1122 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1123 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001124
Colin Crossb5db4012022-03-28 17:12:39 -07001125 // We don't currently run annotation processors in turbine, which means we can't use turbine
1126 // generated header jars when an annotation processor that generates API is enabled. One
1127 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1128 // is used to run all of the annotation processors.
1129 disableTurbine := deps.disableTurbine
1130
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001131 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001132 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1133
1134 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001135 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001136
1137 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001138 // When using kotlin sources turbine is used to generate annotation processor sources,
1139 // including for annotation processors that generate API, so we can use turbine for
1140 // java sources too.
1141 disableTurbine = false
1142
Jaewoong Jung26342642021-03-17 15:56:23 -07001143 // user defined kotlin flags.
1144 kotlincFlags := j.properties.Kotlincflags
1145 CheckKotlincFlags(ctx, kotlincFlags)
1146
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001147 // Workaround for KT-46512
1148 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001149
1150 // If there are kotlin files, compile them first but pass all the kotlin and java files
1151 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1152 // won't emit any classes for them.
1153 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1154 if ctx.Device() {
1155 kotlincFlags = append(kotlincFlags, "-no-jdk")
1156 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001157
1158 for _, plugin := range deps.kotlinPlugins {
1159 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1160 }
1161 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1162
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 if len(kotlincFlags) > 0 {
1164 // optimization.
1165 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1166 flags.kotlincFlags += "$kotlincFlags"
1167 }
1168
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001169 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001170 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1171
1172 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1173 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1174
1175 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1176 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1177
Isaac Chioua23d9942022-04-06 06:14:38 +00001178 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001179 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001180 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1181 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001182 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001183 srcJars = append(srcJars, kaptSrcJar)
1184 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001185 // Disable annotation processing in javac, it's already been handled by kapt
1186 flags.processorPath = nil
1187 flags.processors = nil
1188 }
1189
1190 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001191 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001192 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 if ctx.Failed() {
1194 return
1195 }
1196
Isaac Chioua23d9942022-04-06 06:14:38 +00001197 // Make javac rule depend on the kotlinc rule
1198 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1199
Jaewoong Jung26342642021-03-17 15:56:23 -07001200 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001201 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1202
Jaewoong Jung26342642021-03-17 15:56:23 -07001203 // Jar kotlin classes into the final jar after javac
1204 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1205 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001206 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001207 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001208 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001209 } else {
1210 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001211 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001212 }
1213 }
1214
1215 jars := append(android.Paths(nil), kotlinJars...)
1216
Jaewoong Jung26342642021-03-17 15:56:23 -07001217 j.compiledSrcJars = srcJars
1218
1219 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001220 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001221 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001222 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1223 enableSharding = true
1224 // Formerly, there was a check here that prevented annotation processors
1225 // from being used when sharding was enabled, as some annotation processors
1226 // do not function correctly in sharded environments. It was removed to
1227 // allow for the use of annotation processors that do function correctly
1228 // with sharding enabled. See: b/77284273.
1229 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001230 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001231 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 if ctx.Failed() {
1233 return
1234 }
1235 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001236 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001237 hasErrorproneableFiles := false
1238 for _, ext := range j.sourceExtensions {
1239 if ext != ".proto" && ext != ".aidl" {
1240 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1241 // compile, and it's not useful to have warnings on these generated sources.
1242 hasErrorproneableFiles = true
1243 break
1244 }
1245 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001246 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001247 if Bool(j.properties.Errorprone.Enabled) {
1248 // If error-prone is enabled, enable errorprone flags on the regular
1249 // build.
1250 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001251 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001252 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1253 // a new jar file just for compiling with the errorprone compiler to.
1254 // This is because we don't want to cause the java files to get completely
1255 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1256 // We also don't want to run this if errorprone is enabled by default for
1257 // this module, or else we could have duplicated errorprone messages.
1258 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001259 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001260
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001261 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001262 "errorprone", "errorprone")
1263
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 extraJarDeps = append(extraJarDeps, errorprone)
1265 }
1266
1267 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001268 if headerJarFileWithoutDepsOrJarjar != nil {
1269 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1270 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001271 shardSize := int(*(j.properties.Javac_shard_size))
1272 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001273 if len(uniqueJavaFiles) > 0 {
1274 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001275 for idx, shardSrc := range shardSrcs {
1276 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1277 nil, flags, extraJarDeps)
1278 jars = append(jars, classes)
1279 }
1280 }
1281 if len(srcJars) > 0 {
1282 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1283 nil, srcJars, flags, extraJarDeps)
1284 jars = append(jars, classes)
1285 }
1286 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001287 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001288 jars = append(jars, classes)
1289 }
1290 if ctx.Failed() {
1291 return
1292 }
1293 }
1294
1295 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1296
1297 var includeSrcJar android.WritablePath
1298 if Bool(j.properties.Include_srcs) {
1299 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1300 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1301 }
1302
1303 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1304 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1305 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1306 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1307
1308 var resArgs []string
1309 var resDeps android.Paths
1310
1311 resArgs = append(resArgs, dirArgs...)
1312 resDeps = append(resDeps, dirDeps...)
1313
1314 resArgs = append(resArgs, fileArgs...)
1315 resDeps = append(resDeps, fileDeps...)
1316
1317 resArgs = append(resArgs, extraArgs...)
1318 resDeps = append(resDeps, extraDeps...)
1319
1320 if len(resArgs) > 0 {
1321 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1322 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1323 j.resourceJar = resourceJar
1324 if ctx.Failed() {
1325 return
1326 }
1327 }
1328
1329 var resourceJars android.Paths
1330 if j.resourceJar != nil {
1331 resourceJars = append(resourceJars, j.resourceJar)
1332 }
1333 if Bool(j.properties.Include_srcs) {
1334 resourceJars = append(resourceJars, includeSrcJar)
1335 }
1336 resourceJars = append(resourceJars, deps.staticResourceJars...)
1337
1338 if len(resourceJars) > 1 {
1339 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1340 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1341 false, nil, nil)
1342 j.resourceJar = combinedJar
1343 } else if len(resourceJars) == 1 {
1344 j.resourceJar = resourceJars[0]
1345 }
1346
1347 if len(deps.staticJars) > 0 {
1348 jars = append(jars, deps.staticJars...)
1349 }
1350
1351 manifest := j.overrideManifest
1352 if !manifest.Valid() && j.properties.Manifest != nil {
1353 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1354 }
1355
1356 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1357 if len(services) > 0 {
1358 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1359 var zipargs []string
1360 for _, file := range services {
1361 serviceFile := file.String()
1362 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1363 }
1364 rule := zip
1365 args := map[string]string{
1366 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1367 }
1368 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1369 rule = zipRE
1370 args["implicits"] = strings.Join(services.Strings(), ",")
1371 }
1372 ctx.Build(pctx, android.BuildParams{
1373 Rule: rule,
1374 Output: servicesJar,
1375 Implicits: services,
1376 Args: args,
1377 })
1378 jars = append(jars, servicesJar)
1379 }
1380
1381 // Combine the classes built from sources, any manifests, and any static libraries into
1382 // classes.jar. If there is only one input jar this step will be skipped.
1383 var outputFile android.OutputPath
1384
1385 if len(jars) == 1 && !manifest.Valid() {
1386 // Optimization: skip the combine step as there is nothing to do
1387 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1388 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1389 // any if len(jars) == 1.
1390
1391 // Transform the single path to the jar into an OutputPath as that is required by the following
1392 // code.
1393 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1394 // The path contains an embedded OutputPath so reuse that.
1395 outputFile = moduleOutPath.OutputPath
1396 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1397 // The path is an OutputPath so reuse it directly.
1398 outputFile = outputPath
1399 } else {
1400 // The file is not in the out directory so create an OutputPath into which it can be copied
1401 // and which the following code can use to refer to it.
1402 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1403 ctx.Build(pctx, android.BuildParams{
1404 Rule: android.Cp,
1405 Input: jars[0],
1406 Output: combinedJar,
1407 })
1408 outputFile = combinedJar.OutputPath
1409 }
1410 } else {
1411 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1412 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1413 false, nil, nil)
1414 outputFile = combinedJar.OutputPath
1415 }
1416
1417 // jarjar implementation jar if necessary
1418 if j.expandJarjarRules != nil {
1419 // Transform classes.jar into classes-jarjar.jar
1420 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1421 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1422 outputFile = jarjarFile
1423
1424 // jarjar resource jar if necessary
1425 if j.resourceJar != nil {
1426 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1427 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1428 j.resourceJar = resourceJarJarFile
1429 }
1430
1431 if ctx.Failed() {
1432 return
1433 }
1434 }
1435
1436 // Check package restrictions if necessary.
1437 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001438 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001439 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001440
1441 // Create a rule to copy the output jar to another path and add a validate dependency that
1442 // will check that the jar only contains the permitted packages. The new location will become
1443 // the output file of this module.
1444 inputFile := outputFile
1445 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1446 ctx.Build(pctx, android.BuildParams{
1447 Rule: android.Cp,
1448 Input: inputFile,
1449 Output: outputFile,
1450 // Make sure that any dependency on the output file will cause ninja to run the package check
1451 // rule.
1452 Validation: pkgckFile,
1453 })
1454
1455 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001457
1458 if ctx.Failed() {
1459 return
1460 }
1461 }
1462
1463 j.implementationJarFile = outputFile
1464 if j.headerJarFile == nil {
1465 j.headerJarFile = j.implementationJarFile
1466 }
1467
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001468 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1469 specs := j.jacocoModuleToZipCommand(ctx)
1470 if ctx.Failed() {
1471 return
1472 }
1473
Jaewoong Jung26342642021-03-17 15:56:23 -07001474 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001475 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 }
1477
1478 // merge implementation jar with resources if necessary
1479 implementationAndResourcesJar := outputFile
1480 if j.resourceJar != nil {
1481 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1482 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1483 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1484 false, nil, nil)
1485 implementationAndResourcesJar = combinedJar
1486 }
1487
1488 j.implementationAndResourcesJar = implementationAndResourcesJar
1489
1490 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001491 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001492 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1493 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001494 if compileDex == nil {
1495 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001496 }
1497 if j.deviceProperties.Hostdex == nil {
1498 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1499 }
1500 }
1501
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001502 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001503 if j.hasCode(ctx) {
1504 if j.shouldInstrumentStatic(ctx) {
1505 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1506 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1507 }
1508 // Dex compilation
1509 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001510 params := &compileDexParams{
1511 flags: flags,
1512 sdkVersion: j.SdkVersion(ctx),
1513 minSdkVersion: j.MinSdkVersion(ctx),
1514 classesJar: implementationAndResourcesJar,
1515 jarName: jarName,
1516 }
1517 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001518 if ctx.Failed() {
1519 return
1520 }
1521
Jaewoong Jung26342642021-03-17 15:56:23 -07001522 // merge dex jar with resources if necessary
1523 if j.resourceJar != nil {
1524 jars := android.Paths{dexOutputFile, j.resourceJar}
1525 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1526 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1527 false, nil, nil)
1528 if *j.dexProperties.Uncompress_dex {
1529 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1530 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1531 dexOutputFile = combinedAlignedJar
1532 } else {
1533 dexOutputFile = combinedJar
1534 }
1535 }
1536
Paul Duffin4de94502021-05-16 05:21:16 +01001537 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001538
1539 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001540
1541 // Encode hidden API flags in dex file, if needed.
1542 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1543
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001544 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001545
1546 // Dexpreopting
1547 j.dexpreopt(ctx, dexOutputFile)
1548
1549 outputFile = dexOutputFile
1550 } else {
1551 // There is no code to compile into a dex jar, make sure the resources are propagated
1552 // to the APK if this is an app.
1553 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001554 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001555 }
1556
1557 if ctx.Failed() {
1558 return
1559 }
1560 } else {
1561 outputFile = implementationAndResourcesJar
1562 }
1563
1564 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001565 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1566 if !apiLevel.IsPreview() {
1567 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001568 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001569 // When running metalava, we pass --version-codename. When that value
1570 // is not REL, metalava will add 1 to the --current-version argument.
1571 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1572 // branch) and the codename is REL, except potentially on the most
1573 // recent non-master branch. On that branch, it goes through two other
1574 // phases before it gets to the phase previously described:
1575 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1576 // is not rel. This happens for most of the internal branch's life
1577 // while the branch has been cut but is still under active development.
1578 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1579 // REL. This happens briefly during the release process. During this
1580 // state the code to add --current-version is commented out, and then
1581 // that commenting out is reverted after the codename is set to REL.
1582 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1583 // prior version and the codename is always non-REL.
1584 //
1585 // We need to add one here to match metalava adding 1. Technically
1586 // this means that in the state described in the second bullet point
1587 // above, this number is 1 higher than it should be.
1588 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 }
1590 }
1591
1592 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001593 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1594 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001595 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1596 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001597 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001598 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001599 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001600 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001601 j.linter.javaLanguageLevel = flags.javaVersion.String()
1602 j.linter.kotlinLanguageLevel = "1.3"
1603 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1604 j.linter.buildModuleReportZip = true
1605 }
1606 j.linter.lint(ctx)
1607 }
1608
1609 ctx.CheckbuildFile(outputFile)
1610
1611 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1612 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001613 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1614 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001615 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1616 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1617 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1618 AidlIncludeDirs: j.exportAidlIncludeDirs,
1619 SrcJarArgs: j.srcJarArgs,
1620 SrcJarDeps: j.srcJarDeps,
1621 ExportedPlugins: j.exportedPluginJars,
1622 ExportedPluginClasses: j.exportedPluginClasses,
1623 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1624 JacocoReportClassesFile: j.jacocoReportClassesFile,
1625 })
1626
1627 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1628 j.outputFile = outputFile.WithoutRel()
1629}
1630
Colin Crossa1ff7c62021-09-17 14:11:52 -07001631func (j *Module) useCompose() bool {
1632 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1633}
1634
Cole Faust75fffb12021-06-13 15:23:16 -07001635// Returns a copy of the supplied flags, but with all the errorprone-related
1636// fields copied to the regular build's fields.
1637func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1638 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1639
1640 if len(flags.errorProneExtraJavacFlags) > 0 {
1641 if len(flags.javacFlags) > 0 {
1642 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1643 } else {
1644 flags.javacFlags = flags.errorProneExtraJavacFlags
1645 }
1646 }
1647 return flags
1648}
1649
Jaewoong Jung26342642021-03-17 15:56:23 -07001650func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1651 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1652
1653 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1654 if idx >= 0 {
1655 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1656 jarName += strconv.Itoa(idx)
1657 }
1658
1659 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1660 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1661
1662 if ctx.Config().EmitXrefRules() {
1663 extractionFile := android.PathForModuleOut(ctx, kzipName)
1664 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1665 j.kytheFiles = append(j.kytheFiles, extractionFile)
1666 }
1667
1668 return classes
1669}
1670
1671// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1672// since some of these flags may be used internally.
1673func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1674 for _, flag := range flags {
1675 flag = strings.TrimSpace(flag)
1676
1677 if !strings.HasPrefix(flag, "-") {
1678 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1679 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1680 ctx.PropertyErrorf("kotlincflags",
1681 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1682 } else if inList(flag, config.KotlincIllegalFlags) {
1683 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1684 } else if flag == "-include-runtime" {
1685 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1686 } else {
1687 args := strings.Split(flag, " ")
1688 if args[0] == "-kotlin-home" {
1689 ctx.PropertyErrorf("kotlincflags",
1690 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1691 }
1692 }
1693 }
1694}
1695
1696func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1697 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001698 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001699
1700 var jars android.Paths
1701 if len(srcFiles) > 0 || len(srcJars) > 0 {
1702 // Compile java sources into turbine.jar.
1703 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1704 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1705 if ctx.Failed() {
1706 return nil, nil
1707 }
1708 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001709 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001710 }
1711
1712 jars = append(jars, extraJars...)
1713
1714 // Combine any static header libraries into classes-header.jar. If there is only
1715 // one input jar this step will be skipped.
1716 jars = append(jars, deps.staticHeaderJars...)
1717
1718 // we cannot skip the combine step for now if there is only one jar
1719 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1720 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1721 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1722 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001723 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001724
1725 if j.expandJarjarRules != nil {
1726 // Transform classes.jar into classes-jarjar.jar
1727 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001728 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1729 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001730 if ctx.Failed() {
1731 return nil, nil
1732 }
1733 }
1734
Colin Cross3d56ed52021-11-18 22:23:12 -08001735 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001736}
1737
1738func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001739 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001740
1741 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1742 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1743
1744 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1745
1746 j.jacocoReportClassesFile = jacocoReportClassesFile
1747
1748 return instrumentedJar
1749}
1750
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001751type providesTransitiveHeaderJars struct {
1752 // set of header jars for all transitive libs deps
1753 transitiveLibsHeaderJars *android.DepSet
1754 // set of header jars for all transitive static libs deps
1755 transitiveStaticLibsHeaderJars *android.DepSet
1756}
1757
1758func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
1759 return j.transitiveLibsHeaderJars
1760}
1761
1762func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
1763 return j.transitiveStaticLibsHeaderJars
1764}
1765
1766func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1767 directLibs := android.Paths{}
1768 directStaticLibs := android.Paths{}
1769 transitiveLibs := []*android.DepSet{}
1770 transitiveStaticLibs := []*android.DepSet{}
1771 ctx.VisitDirectDeps(func(module android.Module) {
1772 // don't add deps of the prebuilt version of the same library
1773 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1774 return
1775 }
1776
1777 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1778 if dep.TransitiveLibsHeaderJars != nil {
1779 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1780 }
1781 if dep.TransitiveStaticLibsHeaderJars != nil {
1782 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1783 }
1784
1785 tag := ctx.OtherModuleDependencyTag(module)
1786 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1787 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1788 directLibs = append(directLibs, dep.HeaderJars...)
1789 } else if tag == staticLibTag {
1790 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1791 }
1792 })
1793 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1794 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1795}
1796
Jaewoong Jung26342642021-03-17 15:56:23 -07001797func (j *Module) HeaderJars() android.Paths {
1798 if j.headerJarFile == nil {
1799 return nil
1800 }
1801 return android.Paths{j.headerJarFile}
1802}
1803
1804func (j *Module) ImplementationJars() android.Paths {
1805 if j.implementationJarFile == nil {
1806 return nil
1807 }
1808 return android.Paths{j.implementationJarFile}
1809}
1810
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001811func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001812 return j.dexJarFile
1813}
1814
1815func (j *Module) DexJarInstallPath() android.Path {
1816 return j.installFile
1817}
1818
1819func (j *Module) ImplementationAndResourcesJars() android.Paths {
1820 if j.implementationAndResourcesJar == nil {
1821 return nil
1822 }
1823 return android.Paths{j.implementationAndResourcesJar}
1824}
1825
1826func (j *Module) AidlIncludeDirs() android.Paths {
1827 // exportAidlIncludeDirs is type android.Paths already
1828 return j.exportAidlIncludeDirs
1829}
1830
1831func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1832 return j.classLoaderContexts
1833}
1834
1835// Collect information for opening IDE project files in java/jdeps.go.
1836func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1837 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1838 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1839 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1840 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1841 if j.expandJarjarRules != nil {
1842 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1843 }
1844 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001845 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1846 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001847}
1848
1849func (j *Module) CompilerDeps() []string {
1850 jdeps := []string{}
1851 jdeps = append(jdeps, j.properties.Libs...)
1852 jdeps = append(jdeps, j.properties.Static_libs...)
1853 return jdeps
1854}
1855
1856func (j *Module) hasCode(ctx android.ModuleContext) bool {
1857 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1858 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1859}
1860
1861// Implements android.ApexModule
1862func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1863 return j.depIsInSameApex(ctx, dep)
1864}
1865
1866// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001867func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001868 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001869 minSdkVersion := j.MinSdkVersion(ctx)
1870 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001871 return fmt.Errorf("min_sdk_version is not specified")
1872 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001873 // If the module is compiling against core (via sdk_version), skip comparison check.
1874 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 return nil
1876 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001877 if minSdkVersion.GreaterThan(sdkVersion) {
1878 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001879 }
1880 return nil
1881}
1882
1883func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001884 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001885}
1886
Jaewoong Jung26342642021-03-17 15:56:23 -07001887func (j *Module) JacocoReportClassesFile() android.Path {
1888 return j.jacocoReportClassesFile
1889}
1890
1891func (j *Module) IsInstallable() bool {
1892 return Bool(j.properties.Installable)
1893}
1894
1895type sdkLinkType int
1896
1897const (
1898 // TODO(jiyong) rename these for better readability. Make the allowed
1899 // and disallowed link types explicit
1900 // order is important here. See rank()
1901 javaCore sdkLinkType = iota
1902 javaSdk
1903 javaSystem
1904 javaModule
1905 javaSystemServer
1906 javaPlatform
1907)
1908
1909func (lt sdkLinkType) String() string {
1910 switch lt {
1911 case javaCore:
1912 return "core Java API"
1913 case javaSdk:
1914 return "Android API"
1915 case javaSystem:
1916 return "system API"
1917 case javaModule:
1918 return "module API"
1919 case javaSystemServer:
1920 return "system server API"
1921 case javaPlatform:
1922 return "private API"
1923 default:
1924 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1925 }
1926}
1927
1928// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1929// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1930// can't statically depend on modules that use Platform API.
1931func (lt sdkLinkType) rank() int {
1932 return int(lt)
1933}
1934
1935type moduleWithSdkDep interface {
1936 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001937 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001938}
1939
Jiyong Park92315372021-04-02 08:45:46 +09001940func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001941 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001942 case android.SdkCore.DefaultJavaLibraryName(),
1943 "legacy.core.platform.api.stubs",
1944 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001945 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001946 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001947 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001948 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001949 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001950 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001951 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001952 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001953 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001954 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001955 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001956 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001957 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001958 return javaSystem, true
1959 }
1960
1961 if stub, linkType := moduleStubLinkType(name); stub {
1962 return linkType, true
1963 }
1964
Jiyong Park92315372021-04-02 08:45:46 +09001965 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001966 switch ver.Kind {
1967 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001968 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001969 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001970 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001971 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001972 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001973 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001974 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001975 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001977 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001978 return javaPlatform, false
1979 }
1980
Jiyong Parkf1691d22021-03-29 20:11:58 +09001981 if !ver.Valid() {
1982 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001983 }
1984 return javaSdk, false
1985}
1986
1987// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1988// this module's. See the comment on rank() for details and an example.
1989func (j *Module) checkSdkLinkType(
1990 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1991 if ctx.Host() {
1992 return
1993 }
1994
Jiyong Park92315372021-04-02 08:45:46 +09001995 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001996 if stubs {
1997 return
1998 }
Jiyong Park92315372021-04-02 08:45:46 +09001999 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002000
2001 if myLinkType.rank() < depLinkType.rank() {
2002 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2003 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2004 "property of the source or target module so that target module is built "+
2005 "with the same or smaller API set when compared to the source.",
2006 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2007 }
2008}
2009
2010func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2011 var deps deps
2012
2013 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002014 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002015 if sdkDep.invalidVersion {
2016 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2017 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2018 } else if sdkDep.useFiles {
2019 // sdkDep.jar is actually equivalent to turbine header.jar.
2020 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002021 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002022 deps.aidlPreprocess = sdkDep.aidl
2023 } else {
2024 deps.aidlPreprocess = sdkDep.aidl
2025 }
2026 }
2027
Jiyong Park92315372021-04-02 08:45:46 +09002028 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002029
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002030 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002031 ctx.VisitDirectDeps(func(module android.Module) {
2032 otherName := ctx.OtherModuleName(module)
2033 tag := ctx.OtherModuleDependencyTag(module)
2034
2035 if IsJniDepTag(tag) {
2036 // Handled by AndroidApp.collectAppDeps
2037 return
2038 }
2039 if tag == certificateTag {
2040 // Handled by AndroidApp.collectAppDeps
2041 return
2042 }
2043
2044 if dep, ok := module.(SdkLibraryDependency); ok {
2045 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002046 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002047 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2048 deps.classpath = append(deps.classpath, depHeaderJars...)
2049 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002050 case staticLibTag:
2051 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2052 }
2053 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2054 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2055 if sdkLinkType != javaPlatform &&
2056 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2057 // dep is a sysprop implementation library, but this module is not linking against
2058 // the platform, so it gets the sysprop public stubs library instead. Replace
2059 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2060 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2061 dep = syspropDep.JavaInfo
2062 }
2063 switch tag {
2064 case bootClasspathTag:
2065 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002066 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002067 if _, ok := module.(*Plugin); ok {
2068 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2069 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002070 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002071 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002072 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2073 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2074 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2075 case java9LibTag:
2076 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2077 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002078 if _, ok := module.(*Plugin); ok {
2079 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2080 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002081 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2082 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2083 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2084 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2085 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2086 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2087 // Turbine doesn't run annotation processors, so any module that uses an
2088 // annotation processor that generates API is incompatible with the turbine
2089 // optimization.
2090 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2091 case pluginTag:
2092 if plugin, ok := module.(*Plugin); ok {
2093 if plugin.pluginProperties.Processor_class != nil {
2094 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2095 } else {
2096 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2097 }
2098 // Turbine doesn't run annotation processors, so any module that uses an
2099 // annotation processor that generates API is incompatible with the turbine
2100 // optimization.
2101 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2102 } else {
2103 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2104 }
2105 case errorpronePluginTag:
2106 if _, ok := module.(*Plugin); ok {
2107 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2108 } else {
2109 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2110 }
2111 case exportedPluginTag:
2112 if plugin, ok := module.(*Plugin); ok {
2113 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2114 if plugin.pluginProperties.Processor_class != nil {
2115 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2116 }
2117 // Turbine doesn't run annotation processors, so any module that uses an
2118 // annotation processor that generates API is incompatible with the turbine
2119 // optimization.
2120 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2121 } else {
2122 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2123 }
2124 case kotlinStdlibTag:
2125 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2126 case kotlinAnnotationsTag:
2127 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002128 case kotlinPluginTag:
2129 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002130 case syspropPublicStubDepTag:
2131 // This is a sysprop implementation library, forward the JavaInfoProvider from
2132 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2133 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2134 JavaInfo: dep,
2135 })
2136 }
2137 } else if dep, ok := module.(android.SourceFileProducer); ok {
2138 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002139 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002140 checkProducesJars(ctx, dep)
2141 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002142 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002143 case staticLibTag:
2144 checkProducesJars(ctx, dep)
2145 deps.classpath = append(deps.classpath, dep.Srcs()...)
2146 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2147 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2148 }
2149 } else {
2150 switch tag {
2151 case bootClasspathTag:
2152 // If a system modules dependency has been added to the bootclasspath
2153 // then add its libs to the bootclasspath.
2154 sm := module.(SystemModulesProvider)
2155 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2156
2157 case systemModulesTag:
2158 if deps.systemModules != nil {
2159 panic("Found two system module dependencies")
2160 }
2161 sm := module.(SystemModulesProvider)
2162 outputDir, outputDeps := sm.OutputDirAndDeps()
2163 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002164
2165 case instrumentationForTag:
2166 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 -07002167 }
2168 }
2169
2170 addCLCFromDep(ctx, module, j.classLoaderContexts)
2171 })
2172
2173 return deps
2174}
2175
2176func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2177 deps.processorPath = append(deps.processorPath, pluginJars...)
2178 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2179}
2180
2181// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2182// this interface.
2183type ProvidesUsesLib interface {
2184 ProvidesUsesLib() *string
2185}
2186
2187func (j *Module) ProvidesUsesLib() *string {
2188 return j.usesLibraryProperties.Provides_uses_lib
2189}
satayev1c564cc2021-05-25 19:50:30 +01002190
2191type ModuleWithStem interface {
2192 Stem() string
2193}
2194
2195var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002196
2197func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2198 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002199 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002200 if lib, ok := ctx.Module().(*Library); ok {
2201 javaLibraryBp2Build(ctx, lib)
2202 }
2203 case "java_binary_host":
2204 if binary, ok := ctx.Module().(*Binary); ok {
2205 javaBinaryHostBp2Build(ctx, binary)
2206 }
Zi Wang65b36722023-05-23 15:18:33 -07002207 case "java_test_host":
2208 if testHost, ok := ctx.Module().(*TestHost); ok {
2209 javaTestHostBp2Build(ctx, testHost)
2210 }
Wei Libafb6d62021-12-10 03:14:59 -08002211 }
Wei Libafb6d62021-12-10 03:14:59 -08002212}