blob: 646ed9dd3784aecc1050ee2ec8d9beb123901d46 [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
Jihoon Kang1147b312023-06-08 23:25:57 +00001391 // moduleStubLinkType determines if the module is the TopLevelStubLibrary generated
1392 // from sdk_library. The TopLevelStubLibrary contains only one static lib,
1393 // either with .from-source or .from-text suffix.
1394 // outputFile should be agnostic to the build configuration,
1395 // thus "combine" the single static lib in order to prevent the static lib from being exposed
1396 // to the copy rules.
1397 stub, _ := moduleStubLinkType(ctx.ModuleName())
1398
Jaewoong Jung26342642021-03-17 15:56:23 -07001399 // Transform the single path to the jar into an OutputPath as that is required by the following
1400 // code.
Jihoon Kang1147b312023-06-08 23:25:57 +00001401 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001402 // The path contains an embedded OutputPath so reuse that.
1403 outputFile = moduleOutPath.OutputPath
Jihoon Kang1147b312023-06-08 23:25:57 +00001404 } else if outputPath, ok := jars[0].(android.OutputPath); ok && !stub {
Jaewoong Jung26342642021-03-17 15:56:23 -07001405 // The path is an OutputPath so reuse it directly.
1406 outputFile = outputPath
1407 } else {
1408 // The file is not in the out directory so create an OutputPath into which it can be copied
1409 // and which the following code can use to refer to it.
1410 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1411 ctx.Build(pctx, android.BuildParams{
1412 Rule: android.Cp,
1413 Input: jars[0],
1414 Output: combinedJar,
1415 })
1416 outputFile = combinedJar.OutputPath
1417 }
1418 } else {
1419 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1420 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1421 false, nil, nil)
1422 outputFile = combinedJar.OutputPath
1423 }
1424
1425 // jarjar implementation jar if necessary
1426 if j.expandJarjarRules != nil {
1427 // Transform classes.jar into classes-jarjar.jar
1428 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1429 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1430 outputFile = jarjarFile
1431
1432 // jarjar resource jar if necessary
1433 if j.resourceJar != nil {
1434 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1435 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1436 j.resourceJar = resourceJarJarFile
1437 }
1438
1439 if ctx.Failed() {
1440 return
1441 }
1442 }
1443
1444 // Check package restrictions if necessary.
1445 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001446 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001447 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001448
1449 // Create a rule to copy the output jar to another path and add a validate dependency that
1450 // will check that the jar only contains the permitted packages. The new location will become
1451 // the output file of this module.
1452 inputFile := outputFile
1453 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1454 ctx.Build(pctx, android.BuildParams{
1455 Rule: android.Cp,
1456 Input: inputFile,
1457 Output: outputFile,
1458 // Make sure that any dependency on the output file will cause ninja to run the package check
1459 // rule.
1460 Validation: pkgckFile,
1461 })
1462
1463 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001464 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001465
1466 if ctx.Failed() {
1467 return
1468 }
1469 }
1470
1471 j.implementationJarFile = outputFile
1472 if j.headerJarFile == nil {
1473 j.headerJarFile = j.implementationJarFile
1474 }
1475
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001476 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1477 specs := j.jacocoModuleToZipCommand(ctx)
1478 if ctx.Failed() {
1479 return
1480 }
1481
Jaewoong Jung26342642021-03-17 15:56:23 -07001482 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001483 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001484 }
1485
1486 // merge implementation jar with resources if necessary
1487 implementationAndResourcesJar := outputFile
1488 if j.resourceJar != nil {
1489 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1490 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1491 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1492 false, nil, nil)
1493 implementationAndResourcesJar = combinedJar
1494 }
1495
1496 j.implementationAndResourcesJar = implementationAndResourcesJar
1497
1498 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001499 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001500 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1501 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001502 if compileDex == nil {
1503 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 }
1505 if j.deviceProperties.Hostdex == nil {
1506 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1507 }
1508 }
1509
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001510 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 if j.hasCode(ctx) {
1512 if j.shouldInstrumentStatic(ctx) {
1513 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1514 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1515 }
1516 // Dex compilation
1517 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001518 params := &compileDexParams{
1519 flags: flags,
1520 sdkVersion: j.SdkVersion(ctx),
1521 minSdkVersion: j.MinSdkVersion(ctx),
1522 classesJar: implementationAndResourcesJar,
1523 jarName: jarName,
1524 }
1525 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001526 if ctx.Failed() {
1527 return
1528 }
1529
Jaewoong Jung26342642021-03-17 15:56:23 -07001530 // merge dex jar with resources if necessary
1531 if j.resourceJar != nil {
1532 jars := android.Paths{dexOutputFile, j.resourceJar}
1533 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1534 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1535 false, nil, nil)
1536 if *j.dexProperties.Uncompress_dex {
1537 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1538 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1539 dexOutputFile = combinedAlignedJar
1540 } else {
1541 dexOutputFile = combinedJar
1542 }
1543 }
1544
Paul Duffin4de94502021-05-16 05:21:16 +01001545 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001546
1547 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001548
1549 // Encode hidden API flags in dex file, if needed.
1550 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1551
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001552 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001553
1554 // Dexpreopting
1555 j.dexpreopt(ctx, dexOutputFile)
1556
1557 outputFile = dexOutputFile
1558 } else {
1559 // There is no code to compile into a dex jar, make sure the resources are propagated
1560 // to the APK if this is an app.
1561 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001562 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001563 }
1564
1565 if ctx.Failed() {
1566 return
1567 }
1568 } else {
1569 outputFile = implementationAndResourcesJar
1570 }
1571
1572 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001573 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1574 if !apiLevel.IsPreview() {
1575 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001576 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001577 // When running metalava, we pass --version-codename. When that value
1578 // is not REL, metalava will add 1 to the --current-version argument.
1579 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1580 // branch) and the codename is REL, except potentially on the most
1581 // recent non-master branch. On that branch, it goes through two other
1582 // phases before it gets to the phase previously described:
1583 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1584 // is not rel. This happens for most of the internal branch's life
1585 // while the branch has been cut but is still under active development.
1586 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1587 // REL. This happens briefly during the release process. During this
1588 // state the code to add --current-version is commented out, and then
1589 // that commenting out is reverted after the codename is set to REL.
1590 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1591 // prior version and the codename is always non-REL.
1592 //
1593 // We need to add one here to match metalava adding 1. Technically
1594 // this means that in the state described in the second bullet point
1595 // above, this number is 1 higher than it should be.
1596 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001597 }
1598 }
1599
1600 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001601 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1602 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001603 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1604 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001605 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001606 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001607 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001608 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001609 j.linter.javaLanguageLevel = flags.javaVersion.String()
1610 j.linter.kotlinLanguageLevel = "1.3"
1611 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1612 j.linter.buildModuleReportZip = true
1613 }
1614 j.linter.lint(ctx)
1615 }
1616
1617 ctx.CheckbuildFile(outputFile)
1618
1619 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1620 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001621 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1622 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001623 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1624 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1625 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1626 AidlIncludeDirs: j.exportAidlIncludeDirs,
1627 SrcJarArgs: j.srcJarArgs,
1628 SrcJarDeps: j.srcJarDeps,
1629 ExportedPlugins: j.exportedPluginJars,
1630 ExportedPluginClasses: j.exportedPluginClasses,
1631 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1632 JacocoReportClassesFile: j.jacocoReportClassesFile,
1633 })
1634
1635 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1636 j.outputFile = outputFile.WithoutRel()
1637}
1638
Colin Crossa1ff7c62021-09-17 14:11:52 -07001639func (j *Module) useCompose() bool {
1640 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1641}
1642
Cole Faust75fffb12021-06-13 15:23:16 -07001643// Returns a copy of the supplied flags, but with all the errorprone-related
1644// fields copied to the regular build's fields.
1645func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1646 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1647
1648 if len(flags.errorProneExtraJavacFlags) > 0 {
1649 if len(flags.javacFlags) > 0 {
1650 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1651 } else {
1652 flags.javacFlags = flags.errorProneExtraJavacFlags
1653 }
1654 }
1655 return flags
1656}
1657
Jaewoong Jung26342642021-03-17 15:56:23 -07001658func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1659 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1660
1661 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1662 if idx >= 0 {
1663 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1664 jarName += strconv.Itoa(idx)
1665 }
1666
1667 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1668 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1669
1670 if ctx.Config().EmitXrefRules() {
1671 extractionFile := android.PathForModuleOut(ctx, kzipName)
1672 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1673 j.kytheFiles = append(j.kytheFiles, extractionFile)
1674 }
1675
1676 return classes
1677}
1678
1679// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1680// since some of these flags may be used internally.
1681func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1682 for _, flag := range flags {
1683 flag = strings.TrimSpace(flag)
1684
1685 if !strings.HasPrefix(flag, "-") {
1686 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1687 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1688 ctx.PropertyErrorf("kotlincflags",
1689 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1690 } else if inList(flag, config.KotlincIllegalFlags) {
1691 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1692 } else if flag == "-include-runtime" {
1693 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1694 } else {
1695 args := strings.Split(flag, " ")
1696 if args[0] == "-kotlin-home" {
1697 ctx.PropertyErrorf("kotlincflags",
1698 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1699 }
1700 }
1701 }
1702}
1703
1704func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1705 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001706 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001707
1708 var jars android.Paths
1709 if len(srcFiles) > 0 || len(srcJars) > 0 {
1710 // Compile java sources into turbine.jar.
1711 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1712 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1713 if ctx.Failed() {
1714 return nil, nil
1715 }
1716 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001717 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001718 }
1719
1720 jars = append(jars, extraJars...)
1721
1722 // Combine any static header libraries into classes-header.jar. If there is only
1723 // one input jar this step will be skipped.
1724 jars = append(jars, deps.staticHeaderJars...)
1725
1726 // we cannot skip the combine step for now if there is only one jar
1727 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1728 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1729 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1730 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001731 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001732
1733 if j.expandJarjarRules != nil {
1734 // Transform classes.jar into classes-jarjar.jar
1735 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001736 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1737 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001738 if ctx.Failed() {
1739 return nil, nil
1740 }
1741 }
1742
Colin Cross3d56ed52021-11-18 22:23:12 -08001743 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001744}
1745
1746func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001747 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001748
1749 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1750 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1751
1752 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1753
1754 j.jacocoReportClassesFile = jacocoReportClassesFile
1755
1756 return instrumentedJar
1757}
1758
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001759type providesTransitiveHeaderJars struct {
1760 // set of header jars for all transitive libs deps
1761 transitiveLibsHeaderJars *android.DepSet
1762 // set of header jars for all transitive static libs deps
1763 transitiveStaticLibsHeaderJars *android.DepSet
1764}
1765
1766func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet {
1767 return j.transitiveLibsHeaderJars
1768}
1769
1770func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet {
1771 return j.transitiveStaticLibsHeaderJars
1772}
1773
1774func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1775 directLibs := android.Paths{}
1776 directStaticLibs := android.Paths{}
1777 transitiveLibs := []*android.DepSet{}
1778 transitiveStaticLibs := []*android.DepSet{}
1779 ctx.VisitDirectDeps(func(module android.Module) {
1780 // don't add deps of the prebuilt version of the same library
1781 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1782 return
1783 }
1784
1785 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1786 if dep.TransitiveLibsHeaderJars != nil {
1787 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1788 }
1789 if dep.TransitiveStaticLibsHeaderJars != nil {
1790 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1791 }
1792
1793 tag := ctx.OtherModuleDependencyTag(module)
1794 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1795 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1796 directLibs = append(directLibs, dep.HeaderJars...)
1797 } else if tag == staticLibTag {
1798 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1799 }
1800 })
1801 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1802 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1803}
1804
Jaewoong Jung26342642021-03-17 15:56:23 -07001805func (j *Module) HeaderJars() android.Paths {
1806 if j.headerJarFile == nil {
1807 return nil
1808 }
1809 return android.Paths{j.headerJarFile}
1810}
1811
1812func (j *Module) ImplementationJars() android.Paths {
1813 if j.implementationJarFile == nil {
1814 return nil
1815 }
1816 return android.Paths{j.implementationJarFile}
1817}
1818
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001819func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001820 return j.dexJarFile
1821}
1822
1823func (j *Module) DexJarInstallPath() android.Path {
1824 return j.installFile
1825}
1826
1827func (j *Module) ImplementationAndResourcesJars() android.Paths {
1828 if j.implementationAndResourcesJar == nil {
1829 return nil
1830 }
1831 return android.Paths{j.implementationAndResourcesJar}
1832}
1833
1834func (j *Module) AidlIncludeDirs() android.Paths {
1835 // exportAidlIncludeDirs is type android.Paths already
1836 return j.exportAidlIncludeDirs
1837}
1838
1839func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1840 return j.classLoaderContexts
1841}
1842
1843// Collect information for opening IDE project files in java/jdeps.go.
1844func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1845 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1846 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1847 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1848 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1849 if j.expandJarjarRules != nil {
1850 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1851 }
1852 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001853 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1854 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001855}
1856
1857func (j *Module) CompilerDeps() []string {
1858 jdeps := []string{}
1859 jdeps = append(jdeps, j.properties.Libs...)
1860 jdeps = append(jdeps, j.properties.Static_libs...)
1861 return jdeps
1862}
1863
1864func (j *Module) hasCode(ctx android.ModuleContext) bool {
1865 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1866 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1867}
1868
1869// Implements android.ApexModule
1870func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1871 return j.depIsInSameApex(ctx, dep)
1872}
1873
1874// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001875func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001876 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001877 minSdkVersion := j.MinSdkVersion(ctx)
1878 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001879 return fmt.Errorf("min_sdk_version is not specified")
1880 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001881 // If the module is compiling against core (via sdk_version), skip comparison check.
1882 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001883 return nil
1884 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001885 if minSdkVersion.GreaterThan(sdkVersion) {
1886 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001887 }
1888 return nil
1889}
1890
1891func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001892 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001893}
1894
Jaewoong Jung26342642021-03-17 15:56:23 -07001895func (j *Module) JacocoReportClassesFile() android.Path {
1896 return j.jacocoReportClassesFile
1897}
1898
1899func (j *Module) IsInstallable() bool {
1900 return Bool(j.properties.Installable)
1901}
1902
1903type sdkLinkType int
1904
1905const (
1906 // TODO(jiyong) rename these for better readability. Make the allowed
1907 // and disallowed link types explicit
1908 // order is important here. See rank()
1909 javaCore sdkLinkType = iota
1910 javaSdk
1911 javaSystem
1912 javaModule
1913 javaSystemServer
1914 javaPlatform
1915)
1916
1917func (lt sdkLinkType) String() string {
1918 switch lt {
1919 case javaCore:
1920 return "core Java API"
1921 case javaSdk:
1922 return "Android API"
1923 case javaSystem:
1924 return "system API"
1925 case javaModule:
1926 return "module API"
1927 case javaSystemServer:
1928 return "system server API"
1929 case javaPlatform:
1930 return "private API"
1931 default:
1932 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1933 }
1934}
1935
1936// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1937// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1938// can't statically depend on modules that use Platform API.
1939func (lt sdkLinkType) rank() int {
1940 return int(lt)
1941}
1942
1943type moduleWithSdkDep interface {
1944 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001945 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001946}
1947
Jiyong Park92315372021-04-02 08:45:46 +09001948func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001949 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001950 case android.SdkCore.DefaultJavaLibraryName(),
1951 "legacy.core.platform.api.stubs",
1952 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001953 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001954 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001955 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001956 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001957 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001958 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001959 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001960 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001961 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001962 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001963 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001964 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001965 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001966 return javaSystem, true
1967 }
1968
1969 if stub, linkType := moduleStubLinkType(name); stub {
1970 return linkType, true
1971 }
1972
Jiyong Park92315372021-04-02 08:45:46 +09001973 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001974 switch ver.Kind {
1975 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001977 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001978 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001979 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001980 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001981 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001982 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001983 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001984 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001985 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001986 return javaPlatform, false
1987 }
1988
Jiyong Parkf1691d22021-03-29 20:11:58 +09001989 if !ver.Valid() {
1990 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001991 }
1992 return javaSdk, false
1993}
1994
1995// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1996// this module's. See the comment on rank() for details and an example.
1997func (j *Module) checkSdkLinkType(
1998 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1999 if ctx.Host() {
2000 return
2001 }
2002
Jiyong Park92315372021-04-02 08:45:46 +09002003 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002004 if stubs {
2005 return
2006 }
Jiyong Park92315372021-04-02 08:45:46 +09002007 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07002008
2009 if myLinkType.rank() < depLinkType.rank() {
2010 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2011 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2012 "property of the source or target module so that target module is built "+
2013 "with the same or smaller API set when compared to the source.",
2014 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2015 }
2016}
2017
2018func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2019 var deps deps
2020
2021 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002022 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002023 if sdkDep.invalidVersion {
2024 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2025 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2026 } else if sdkDep.useFiles {
2027 // sdkDep.jar is actually equivalent to turbine header.jar.
2028 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002029 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002030 deps.aidlPreprocess = sdkDep.aidl
2031 } else {
2032 deps.aidlPreprocess = sdkDep.aidl
2033 }
2034 }
2035
Jiyong Park92315372021-04-02 08:45:46 +09002036 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002037
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002038 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002039 ctx.VisitDirectDeps(func(module android.Module) {
2040 otherName := ctx.OtherModuleName(module)
2041 tag := ctx.OtherModuleDependencyTag(module)
2042
2043 if IsJniDepTag(tag) {
2044 // Handled by AndroidApp.collectAppDeps
2045 return
2046 }
2047 if tag == certificateTag {
2048 // Handled by AndroidApp.collectAppDeps
2049 return
2050 }
2051
2052 if dep, ok := module.(SdkLibraryDependency); ok {
2053 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002054 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002055 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2056 deps.classpath = append(deps.classpath, depHeaderJars...)
2057 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002058 case staticLibTag:
2059 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2060 }
2061 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2062 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2063 if sdkLinkType != javaPlatform &&
2064 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2065 // dep is a sysprop implementation library, but this module is not linking against
2066 // the platform, so it gets the sysprop public stubs library instead. Replace
2067 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2068 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2069 dep = syspropDep.JavaInfo
2070 }
2071 switch tag {
2072 case bootClasspathTag:
2073 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002074 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002075 if _, ok := module.(*Plugin); ok {
2076 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2077 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002078 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002079 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002080 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2081 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2082 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2083 case java9LibTag:
2084 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2085 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002086 if _, ok := module.(*Plugin); ok {
2087 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
2088 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002089 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2090 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2091 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2092 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2093 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2094 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2095 // Turbine doesn't run annotation processors, so any module that uses an
2096 // annotation processor that generates API is incompatible with the turbine
2097 // optimization.
2098 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2099 case pluginTag:
2100 if plugin, ok := module.(*Plugin); ok {
2101 if plugin.pluginProperties.Processor_class != nil {
2102 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2103 } else {
2104 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2105 }
2106 // Turbine doesn't run annotation processors, so any module that uses an
2107 // annotation processor that generates API is incompatible with the turbine
2108 // optimization.
2109 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2110 } else {
2111 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2112 }
2113 case errorpronePluginTag:
2114 if _, ok := module.(*Plugin); ok {
2115 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2116 } else {
2117 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2118 }
2119 case exportedPluginTag:
2120 if plugin, ok := module.(*Plugin); ok {
2121 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2122 if plugin.pluginProperties.Processor_class != nil {
2123 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2124 }
2125 // Turbine doesn't run annotation processors, so any module that uses an
2126 // annotation processor that generates API is incompatible with the turbine
2127 // optimization.
2128 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2129 } else {
2130 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2131 }
2132 case kotlinStdlibTag:
2133 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2134 case kotlinAnnotationsTag:
2135 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002136 case kotlinPluginTag:
2137 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002138 case syspropPublicStubDepTag:
2139 // This is a sysprop implementation library, forward the JavaInfoProvider from
2140 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2141 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2142 JavaInfo: dep,
2143 })
2144 }
2145 } else if dep, ok := module.(android.SourceFileProducer); ok {
2146 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002147 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002148 checkProducesJars(ctx, dep)
2149 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002150 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002151 case staticLibTag:
2152 checkProducesJars(ctx, dep)
2153 deps.classpath = append(deps.classpath, dep.Srcs()...)
2154 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2155 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2156 }
2157 } else {
2158 switch tag {
2159 case bootClasspathTag:
2160 // If a system modules dependency has been added to the bootclasspath
2161 // then add its libs to the bootclasspath.
2162 sm := module.(SystemModulesProvider)
2163 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2164
2165 case systemModulesTag:
2166 if deps.systemModules != nil {
2167 panic("Found two system module dependencies")
2168 }
2169 sm := module.(SystemModulesProvider)
2170 outputDir, outputDeps := sm.OutputDirAndDeps()
2171 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002172
2173 case instrumentationForTag:
2174 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 -07002175 }
2176 }
2177
2178 addCLCFromDep(ctx, module, j.classLoaderContexts)
2179 })
2180
2181 return deps
2182}
2183
2184func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2185 deps.processorPath = append(deps.processorPath, pluginJars...)
2186 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2187}
2188
2189// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2190// this interface.
2191type ProvidesUsesLib interface {
2192 ProvidesUsesLib() *string
2193}
2194
2195func (j *Module) ProvidesUsesLib() *string {
2196 return j.usesLibraryProperties.Provides_uses_lib
2197}
satayev1c564cc2021-05-25 19:50:30 +01002198
2199type ModuleWithStem interface {
2200 Stem() string
2201}
2202
2203var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002204
2205func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2206 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002207 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002208 if lib, ok := ctx.Module().(*Library); ok {
2209 javaLibraryBp2Build(ctx, lib)
2210 }
2211 case "java_binary_host":
2212 if binary, ok := ctx.Module().(*Binary); ok {
2213 javaBinaryHostBp2Build(ctx, binary)
2214 }
Zi Wang65b36722023-05-23 15:18:33 -07002215 case "java_test_host":
2216 if testHost, ok := ctx.Module().(*TestHost); ok {
2217 javaTestHostBp2Build(ctx, testHost)
2218 }
Wei Libafb6d62021-12-10 03:14:59 -08002219 }
Wei Libafb6d62021-12-10 03:14:59 -08002220}