blob: 3fd5a450731127e6b812396530b8f4e1888f06ad [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...)
Colin Crossb0ef30a2021-06-29 10:42:00 -07001093 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001094
1095 if j.properties.Jarjar_rules != nil {
1096 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1097 }
1098
1099 jarName := ctx.ModuleName() + ".jar"
1100
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001101 var uniqueJavaFiles android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001102 set := make(map[string]bool)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001103 for _, v := range srcFiles.FilterByExt(".java") {
Jaewoong Jung26342642021-03-17 15:56:23 -07001104 if _, found := set[v.String()]; !found {
1105 set[v.String()] = true
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001106 uniqueJavaFiles = append(uniqueJavaFiles, v)
Jaewoong Jung26342642021-03-17 15:56:23 -07001107 }
1108 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001109 var uniqueKtFiles android.Paths
1110 for _, v := range srcFiles.FilterByExt(".kt") {
1111 if _, found := set[v.String()]; !found {
1112 set[v.String()] = true
1113 uniqueKtFiles = append(uniqueKtFiles, v)
1114 }
1115 }
1116
1117 var uniqueSrcFiles android.Paths
1118 uniqueSrcFiles = append(uniqueSrcFiles, uniqueJavaFiles...)
1119 uniqueSrcFiles = append(uniqueSrcFiles, uniqueKtFiles...)
1120 j.uniqueSrcFiles = uniqueSrcFiles
Jaewoong Jung26342642021-03-17 15:56:23 -07001121
Colin Crossb5db4012022-03-28 17:12:39 -07001122 // We don't currently run annotation processors in turbine, which means we can't use turbine
1123 // generated header jars when an annotation processor that generates API is enabled. One
1124 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1125 // is used to run all of the annotation processors.
1126 disableTurbine := deps.disableTurbine
1127
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001128 // Collect .java and .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001129 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1130
1131 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001132 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001133
1134 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001135 // When using kotlin sources turbine is used to generate annotation processor sources,
1136 // including for annotation processors that generate API, so we can use turbine for
1137 // java sources too.
1138 disableTurbine = false
1139
Jaewoong Jung26342642021-03-17 15:56:23 -07001140 // user defined kotlin flags.
1141 kotlincFlags := j.properties.Kotlincflags
1142 CheckKotlincFlags(ctx, kotlincFlags)
1143
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001144 // Workaround for KT-46512
1145 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001146
1147 // If there are kotlin files, compile them first but pass all the kotlin and java files
1148 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1149 // won't emit any classes for them.
1150 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1151 if ctx.Device() {
1152 kotlincFlags = append(kotlincFlags, "-no-jdk")
1153 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001154
1155 for _, plugin := range deps.kotlinPlugins {
1156 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1157 }
1158 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1159
Jaewoong Jung26342642021-03-17 15:56:23 -07001160 if len(kotlincFlags) > 0 {
1161 // optimization.
1162 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1163 flags.kotlincFlags += "$kotlincFlags"
1164 }
1165
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001166 // Collect common .kt files for AIDEGen
Jaewoong Jung26342642021-03-17 15:56:23 -07001167 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1168
1169 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1170 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1171
1172 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1173 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1174
Isaac Chioua23d9942022-04-06 06:14:38 +00001175 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001176 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001177 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1178 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001179 kotlinKapt(ctx, kaptSrcJar, kaptResJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Isaac Chioua23d9942022-04-06 06:14:38 +00001180 srcJars = append(srcJars, kaptSrcJar)
1181 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001182 // Disable annotation processing in javac, it's already been handled by kapt
1183 flags.processorPath = nil
1184 flags.processors = nil
1185 }
1186
1187 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001188 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001189 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, uniqueSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001190 if ctx.Failed() {
1191 return
1192 }
1193
Isaac Chioua23d9942022-04-06 06:14:38 +00001194 // Make javac rule depend on the kotlinc rule
1195 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1196
Jaewoong Jung26342642021-03-17 15:56:23 -07001197 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001198 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1199
Jaewoong Jung26342642021-03-17 15:56:23 -07001200 // Jar kotlin classes into the final jar after javac
1201 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1202 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001203 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001204 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001205 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001206 } else {
1207 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001208 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001209 }
1210 }
1211
1212 jars := append(android.Paths(nil), kotlinJars...)
1213
Jaewoong Jung26342642021-03-17 15:56:23 -07001214 j.compiledSrcJars = srcJars
1215
1216 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001217 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001218 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001219 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1220 enableSharding = true
1221 // Formerly, there was a check here that prevented annotation processors
1222 // from being used when sharding was enabled, as some annotation processors
1223 // do not function correctly in sharded environments. It was removed to
1224 // allow for the use of annotation processors that do function correctly
1225 // with sharding enabled. See: b/77284273.
1226 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001227 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001228 j.compileJavaHeader(ctx, uniqueJavaFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001229 if ctx.Failed() {
1230 return
1231 }
1232 }
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001233 if len(uniqueJavaFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001234 hasErrorproneableFiles := false
1235 for _, ext := range j.sourceExtensions {
1236 if ext != ".proto" && ext != ".aidl" {
1237 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1238 // compile, and it's not useful to have warnings on these generated sources.
1239 hasErrorproneableFiles = true
1240 break
1241 }
1242 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001243 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001244 if Bool(j.properties.Errorprone.Enabled) {
1245 // If error-prone is enabled, enable errorprone flags on the regular
1246 // build.
1247 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001248 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001249 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1250 // a new jar file just for compiling with the errorprone compiler to.
1251 // This is because we don't want to cause the java files to get completely
1252 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1253 // We also don't want to run this if errorprone is enabled by default for
1254 // this module, or else we could have duplicated errorprone messages.
1255 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001256 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001257
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001258 transformJavaToClasses(ctx, errorprone, -1, uniqueJavaFiles, srcJars, errorproneFlags, nil,
Cole Faust75fffb12021-06-13 15:23:16 -07001259 "errorprone", "errorprone")
1260
Jaewoong Jung26342642021-03-17 15:56:23 -07001261 extraJarDeps = append(extraJarDeps, errorprone)
1262 }
1263
1264 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001265 if headerJarFileWithoutDepsOrJarjar != nil {
1266 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1267 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001268 shardSize := int(*(j.properties.Javac_shard_size))
1269 var shardSrcs []android.Paths
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001270 if len(uniqueJavaFiles) > 0 {
1271 shardSrcs = android.ShardPaths(uniqueJavaFiles, shardSize)
Jaewoong Jung26342642021-03-17 15:56:23 -07001272 for idx, shardSrc := range shardSrcs {
1273 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1274 nil, flags, extraJarDeps)
1275 jars = append(jars, classes)
1276 }
1277 }
1278 if len(srcJars) > 0 {
1279 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1280 nil, srcJars, flags, extraJarDeps)
1281 jars = append(jars, classes)
1282 }
1283 } else {
Chaohui Wangdcbe33c2022-10-11 11:13:30 +08001284 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueJavaFiles, srcJars, flags, extraJarDeps)
Jaewoong Jung26342642021-03-17 15:56:23 -07001285 jars = append(jars, classes)
1286 }
1287 if ctx.Failed() {
1288 return
1289 }
1290 }
1291
1292 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1293
1294 var includeSrcJar android.WritablePath
1295 if Bool(j.properties.Include_srcs) {
1296 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1297 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1298 }
1299
1300 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1301 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1302 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1303 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1304
1305 var resArgs []string
1306 var resDeps android.Paths
1307
1308 resArgs = append(resArgs, dirArgs...)
1309 resDeps = append(resDeps, dirDeps...)
1310
1311 resArgs = append(resArgs, fileArgs...)
1312 resDeps = append(resDeps, fileDeps...)
1313
1314 resArgs = append(resArgs, extraArgs...)
1315 resDeps = append(resDeps, extraDeps...)
1316
1317 if len(resArgs) > 0 {
1318 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1319 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1320 j.resourceJar = resourceJar
1321 if ctx.Failed() {
1322 return
1323 }
1324 }
1325
1326 var resourceJars android.Paths
1327 if j.resourceJar != nil {
1328 resourceJars = append(resourceJars, j.resourceJar)
1329 }
1330 if Bool(j.properties.Include_srcs) {
1331 resourceJars = append(resourceJars, includeSrcJar)
1332 }
1333 resourceJars = append(resourceJars, deps.staticResourceJars...)
1334
1335 if len(resourceJars) > 1 {
1336 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1337 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1338 false, nil, nil)
1339 j.resourceJar = combinedJar
1340 } else if len(resourceJars) == 1 {
1341 j.resourceJar = resourceJars[0]
1342 }
1343
1344 if len(deps.staticJars) > 0 {
1345 jars = append(jars, deps.staticJars...)
1346 }
1347
1348 manifest := j.overrideManifest
1349 if !manifest.Valid() && j.properties.Manifest != nil {
1350 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1351 }
1352
1353 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1354 if len(services) > 0 {
1355 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1356 var zipargs []string
1357 for _, file := range services {
1358 serviceFile := file.String()
1359 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1360 }
1361 rule := zip
1362 args := map[string]string{
1363 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1364 }
1365 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1366 rule = zipRE
1367 args["implicits"] = strings.Join(services.Strings(), ",")
1368 }
1369 ctx.Build(pctx, android.BuildParams{
1370 Rule: rule,
1371 Output: servicesJar,
1372 Implicits: services,
1373 Args: args,
1374 })
1375 jars = append(jars, servicesJar)
1376 }
1377
1378 // Combine the classes built from sources, any manifests, and any static libraries into
1379 // classes.jar. If there is only one input jar this step will be skipped.
1380 var outputFile android.OutputPath
1381
1382 if len(jars) == 1 && !manifest.Valid() {
1383 // Optimization: skip the combine step as there is nothing to do
1384 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1385 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1386 // any if len(jars) == 1.
1387
1388 // Transform the single path to the jar into an OutputPath as that is required by the following
1389 // code.
1390 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1391 // The path contains an embedded OutputPath so reuse that.
1392 outputFile = moduleOutPath.OutputPath
1393 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1394 // The path is an OutputPath so reuse it directly.
1395 outputFile = outputPath
1396 } else {
1397 // The file is not in the out directory so create an OutputPath into which it can be copied
1398 // and which the following code can use to refer to it.
1399 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1400 ctx.Build(pctx, android.BuildParams{
1401 Rule: android.Cp,
1402 Input: jars[0],
1403 Output: combinedJar,
1404 })
1405 outputFile = combinedJar.OutputPath
1406 }
1407 } else {
1408 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1409 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1410 false, nil, nil)
1411 outputFile = combinedJar.OutputPath
1412 }
1413
1414 // jarjar implementation jar if necessary
1415 if j.expandJarjarRules != nil {
1416 // Transform classes.jar into classes-jarjar.jar
1417 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1418 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1419 outputFile = jarjarFile
1420
1421 // jarjar resource jar if necessary
1422 if j.resourceJar != nil {
1423 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1424 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1425 j.resourceJar = resourceJarJarFile
1426 }
1427
1428 if ctx.Failed() {
1429 return
1430 }
1431 }
1432
1433 // Check package restrictions if necessary.
1434 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001435 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001436 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001437
1438 // Create a rule to copy the output jar to another path and add a validate dependency that
1439 // will check that the jar only contains the permitted packages. The new location will become
1440 // the output file of this module.
1441 inputFile := outputFile
1442 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1443 ctx.Build(pctx, android.BuildParams{
1444 Rule: android.Cp,
1445 Input: inputFile,
1446 Output: outputFile,
1447 // Make sure that any dependency on the output file will cause ninja to run the package check
1448 // rule.
1449 Validation: pkgckFile,
1450 })
1451
1452 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001453 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001454
1455 if ctx.Failed() {
1456 return
1457 }
1458 }
1459
1460 j.implementationJarFile = outputFile
1461 if j.headerJarFile == nil {
1462 j.headerJarFile = j.implementationJarFile
1463 }
1464
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001465 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1466 specs := j.jacocoModuleToZipCommand(ctx)
1467 if ctx.Failed() {
1468 return
1469 }
1470
Jaewoong Jung26342642021-03-17 15:56:23 -07001471 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001472 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001473 }
1474
1475 // merge implementation jar with resources if necessary
1476 implementationAndResourcesJar := outputFile
1477 if j.resourceJar != nil {
1478 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1479 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1480 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1481 false, nil, nil)
1482 implementationAndResourcesJar = combinedJar
1483 }
1484
1485 j.implementationAndResourcesJar = implementationAndResourcesJar
1486
1487 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001488 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001489 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1490 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001491 if compileDex == nil {
1492 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001493 }
1494 if j.deviceProperties.Hostdex == nil {
1495 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1496 }
1497 }
1498
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001499 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001500 if j.hasCode(ctx) {
1501 if j.shouldInstrumentStatic(ctx) {
1502 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1503 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1504 }
1505 // Dex compilation
1506 var dexOutputFile android.OutputPath
Spandan Dasc404cc72023-02-23 18:05:05 +00001507 params := &compileDexParams{
1508 flags: flags,
1509 sdkVersion: j.SdkVersion(ctx),
1510 minSdkVersion: j.MinSdkVersion(ctx),
1511 classesJar: implementationAndResourcesJar,
1512 jarName: jarName,
1513 }
1514 dexOutputFile = j.dexer.compileDex(ctx, params)
Jaewoong Jung26342642021-03-17 15:56:23 -07001515 if ctx.Failed() {
1516 return
1517 }
1518
Jaewoong Jung26342642021-03-17 15:56:23 -07001519 // merge dex jar with resources if necessary
1520 if j.resourceJar != nil {
1521 jars := android.Paths{dexOutputFile, j.resourceJar}
1522 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1523 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1524 false, nil, nil)
1525 if *j.dexProperties.Uncompress_dex {
1526 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1527 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1528 dexOutputFile = combinedAlignedJar
1529 } else {
1530 dexOutputFile = combinedJar
1531 }
1532 }
1533
Paul Duffin4de94502021-05-16 05:21:16 +01001534 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001535
1536 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001537
1538 // Encode hidden API flags in dex file, if needed.
1539 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1540
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001541 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001542
1543 // Dexpreopting
1544 j.dexpreopt(ctx, dexOutputFile)
1545
1546 outputFile = dexOutputFile
1547 } else {
1548 // There is no code to compile into a dex jar, make sure the resources are propagated
1549 // to the APK if this is an app.
1550 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001551 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001552 }
1553
1554 if ctx.Failed() {
1555 return
1556 }
1557 } else {
1558 outputFile = implementationAndResourcesJar
1559 }
1560
1561 if ctx.Device() {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001562 lintSDKVersion := func(apiLevel android.ApiLevel) int {
1563 if !apiLevel.IsPreview() {
1564 return apiLevel.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001565 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001566 // When running metalava, we pass --version-codename. When that value
1567 // is not REL, metalava will add 1 to the --current-version argument.
1568 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1569 // branch) and the codename is REL, except potentially on the most
1570 // recent non-master branch. On that branch, it goes through two other
1571 // phases before it gets to the phase previously described:
1572 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1573 // is not rel. This happens for most of the internal branch's life
1574 // while the branch has been cut but is still under active development.
1575 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1576 // REL. This happens briefly during the release process. During this
1577 // state the code to add --current-version is commented out, and then
1578 // that commenting out is reverted after the codename is set to REL.
1579 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1580 // prior version and the codename is always non-REL.
1581 //
1582 // We need to add one here to match metalava adding 1. Technically
1583 // this means that in the state described in the second bullet point
1584 // above, this number is 1 higher than it should be.
1585 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001586 }
1587 }
1588
1589 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001590 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1591 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001592 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1593 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001594 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
Spandan Dasca70fc42023-03-01 23:38:49 +00001595 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001596 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx).ApiLevel)
Pedro Loureiro18233a22021-06-08 18:11:21 +00001597 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001598 j.linter.javaLanguageLevel = flags.javaVersion.String()
1599 j.linter.kotlinLanguageLevel = "1.3"
1600 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1601 j.linter.buildModuleReportZip = true
1602 }
1603 j.linter.lint(ctx)
1604 }
1605
1606 ctx.CheckbuildFile(outputFile)
1607
1608 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1609 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001610 TransitiveLibsHeaderJars: j.transitiveLibsHeaderJars,
1611 TransitiveStaticLibsHeaderJars: j.transitiveStaticLibsHeaderJars,
Jaewoong Jung26342642021-03-17 15:56:23 -07001612 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1613 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1614 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1615 AidlIncludeDirs: j.exportAidlIncludeDirs,
1616 SrcJarArgs: j.srcJarArgs,
1617 SrcJarDeps: j.srcJarDeps,
1618 ExportedPlugins: j.exportedPluginJars,
1619 ExportedPluginClasses: j.exportedPluginClasses,
1620 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1621 JacocoReportClassesFile: j.jacocoReportClassesFile,
1622 })
1623
1624 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1625 j.outputFile = outputFile.WithoutRel()
1626}
1627
Colin Crossa1ff7c62021-09-17 14:11:52 -07001628func (j *Module) useCompose() bool {
1629 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1630}
1631
Cole Faust75fffb12021-06-13 15:23:16 -07001632// Returns a copy of the supplied flags, but with all the errorprone-related
1633// fields copied to the regular build's fields.
1634func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1635 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1636
1637 if len(flags.errorProneExtraJavacFlags) > 0 {
1638 if len(flags.javacFlags) > 0 {
1639 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1640 } else {
1641 flags.javacFlags = flags.errorProneExtraJavacFlags
1642 }
1643 }
1644 return flags
1645}
1646
Jaewoong Jung26342642021-03-17 15:56:23 -07001647func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1648 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1649
1650 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1651 if idx >= 0 {
1652 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1653 jarName += strconv.Itoa(idx)
1654 }
1655
1656 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1657 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1658
1659 if ctx.Config().EmitXrefRules() {
1660 extractionFile := android.PathForModuleOut(ctx, kzipName)
1661 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1662 j.kytheFiles = append(j.kytheFiles, extractionFile)
1663 }
1664
1665 return classes
1666}
1667
1668// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1669// since some of these flags may be used internally.
1670func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1671 for _, flag := range flags {
1672 flag = strings.TrimSpace(flag)
1673
1674 if !strings.HasPrefix(flag, "-") {
1675 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1676 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1677 ctx.PropertyErrorf("kotlincflags",
1678 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1679 } else if inList(flag, config.KotlincIllegalFlags) {
1680 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1681 } else if flag == "-include-runtime" {
1682 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1683 } else {
1684 args := strings.Split(flag, " ")
1685 if args[0] == "-kotlin-home" {
1686 ctx.PropertyErrorf("kotlincflags",
1687 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1688 }
1689 }
1690 }
1691}
1692
1693func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1694 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001695 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001696
1697 var jars android.Paths
1698 if len(srcFiles) > 0 || len(srcJars) > 0 {
1699 // Compile java sources into turbine.jar.
1700 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1701 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1702 if ctx.Failed() {
1703 return nil, nil
1704 }
1705 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001706 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001707 }
1708
1709 jars = append(jars, extraJars...)
1710
1711 // Combine any static header libraries into classes-header.jar. If there is only
1712 // one input jar this step will be skipped.
1713 jars = append(jars, deps.staticHeaderJars...)
1714
1715 // we cannot skip the combine step for now if there is only one jar
1716 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1717 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1718 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1719 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001720 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001721
1722 if j.expandJarjarRules != nil {
1723 // Transform classes.jar into classes-jarjar.jar
1724 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001725 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1726 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001727 if ctx.Failed() {
1728 return nil, nil
1729 }
1730 }
1731
Colin Cross3d56ed52021-11-18 22:23:12 -08001732 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001733}
1734
1735func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001736 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001737
1738 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1739 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1740
1741 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1742
1743 j.jacocoReportClassesFile = jacocoReportClassesFile
1744
1745 return instrumentedJar
1746}
1747
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001748type providesTransitiveHeaderJars struct {
1749 // set of header jars for all transitive libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001750 transitiveLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001751 // set of header jars for all transitive static libs deps
Colin Crossc85750b2022-04-21 12:50:51 -07001752 transitiveStaticLibsHeaderJars *android.DepSet[android.Path]
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001753}
1754
Colin Crossc85750b2022-04-21 12:50:51 -07001755func (j *providesTransitiveHeaderJars) TransitiveLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001756 return j.transitiveLibsHeaderJars
1757}
1758
Colin Crossc85750b2022-04-21 12:50:51 -07001759func (j *providesTransitiveHeaderJars) TransitiveStaticLibsHeaderJars() *android.DepSet[android.Path] {
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001760 return j.transitiveStaticLibsHeaderJars
1761}
1762
1763func (j *providesTransitiveHeaderJars) collectTransitiveHeaderJars(ctx android.ModuleContext) {
1764 directLibs := android.Paths{}
1765 directStaticLibs := android.Paths{}
Colin Crossc85750b2022-04-21 12:50:51 -07001766 transitiveLibs := []*android.DepSet[android.Path]{}
1767 transitiveStaticLibs := []*android.DepSet[android.Path]{}
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05001768 ctx.VisitDirectDeps(func(module android.Module) {
1769 // don't add deps of the prebuilt version of the same library
1770 if ctx.ModuleName() == android.RemoveOptionalPrebuiltPrefix(module.Name()) {
1771 return
1772 }
1773
1774 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1775 if dep.TransitiveLibsHeaderJars != nil {
1776 transitiveLibs = append(transitiveLibs, dep.TransitiveLibsHeaderJars)
1777 }
1778 if dep.TransitiveStaticLibsHeaderJars != nil {
1779 transitiveStaticLibs = append(transitiveStaticLibs, dep.TransitiveStaticLibsHeaderJars)
1780 }
1781
1782 tag := ctx.OtherModuleDependencyTag(module)
1783 _, isUsesLibDep := tag.(usesLibraryDependencyTag)
1784 if tag == libTag || tag == r8LibraryJarTag || isUsesLibDep {
1785 directLibs = append(directLibs, dep.HeaderJars...)
1786 } else if tag == staticLibTag {
1787 directStaticLibs = append(directStaticLibs, dep.HeaderJars...)
1788 }
1789 })
1790 j.transitiveLibsHeaderJars = android.NewDepSet(android.POSTORDER, directLibs, transitiveLibs)
1791 j.transitiveStaticLibsHeaderJars = android.NewDepSet(android.POSTORDER, directStaticLibs, transitiveStaticLibs)
1792}
1793
Jaewoong Jung26342642021-03-17 15:56:23 -07001794func (j *Module) HeaderJars() android.Paths {
1795 if j.headerJarFile == nil {
1796 return nil
1797 }
1798 return android.Paths{j.headerJarFile}
1799}
1800
1801func (j *Module) ImplementationJars() android.Paths {
1802 if j.implementationJarFile == nil {
1803 return nil
1804 }
1805 return android.Paths{j.implementationJarFile}
1806}
1807
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001808func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001809 return j.dexJarFile
1810}
1811
1812func (j *Module) DexJarInstallPath() android.Path {
1813 return j.installFile
1814}
1815
1816func (j *Module) ImplementationAndResourcesJars() android.Paths {
1817 if j.implementationAndResourcesJar == nil {
1818 return nil
1819 }
1820 return android.Paths{j.implementationAndResourcesJar}
1821}
1822
1823func (j *Module) AidlIncludeDirs() android.Paths {
1824 // exportAidlIncludeDirs is type android.Paths already
1825 return j.exportAidlIncludeDirs
1826}
1827
1828func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1829 return j.classLoaderContexts
1830}
1831
1832// Collect information for opening IDE project files in java/jdeps.go.
1833func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1834 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1835 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1836 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1837 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1838 if j.expandJarjarRules != nil {
1839 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1840 }
1841 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001842 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1843 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001844}
1845
1846func (j *Module) CompilerDeps() []string {
1847 jdeps := []string{}
1848 jdeps = append(jdeps, j.properties.Libs...)
1849 jdeps = append(jdeps, j.properties.Static_libs...)
1850 return jdeps
1851}
1852
1853func (j *Module) hasCode(ctx android.ModuleContext) bool {
1854 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1855 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1856}
1857
1858// Implements android.ApexModule
1859func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1860 return j.depIsInSameApex(ctx, dep)
1861}
1862
1863// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001864func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Spandan Das7fa982c2023-02-24 18:38:56 +00001865 sdkVersionSpec := j.SdkVersion(ctx)
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001866 minSdkVersion := j.MinSdkVersion(ctx)
1867 if !minSdkVersion.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001868 return fmt.Errorf("min_sdk_version is not specified")
1869 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001870 // If the module is compiling against core (via sdk_version), skip comparison check.
1871 if sdkVersionSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001872 return nil
1873 }
Spandan Das7fa982c2023-02-24 18:38:56 +00001874 if minSdkVersion.GreaterThan(sdkVersion) {
1875 return fmt.Errorf("newer SDK(%v)", minSdkVersion)
Jaewoong Jung26342642021-03-17 15:56:23 -07001876 }
1877 return nil
1878}
1879
1880func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001881 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001882}
1883
Jaewoong Jung26342642021-03-17 15:56:23 -07001884func (j *Module) JacocoReportClassesFile() android.Path {
1885 return j.jacocoReportClassesFile
1886}
1887
1888func (j *Module) IsInstallable() bool {
1889 return Bool(j.properties.Installable)
1890}
1891
1892type sdkLinkType int
1893
1894const (
1895 // TODO(jiyong) rename these for better readability. Make the allowed
1896 // and disallowed link types explicit
1897 // order is important here. See rank()
1898 javaCore sdkLinkType = iota
1899 javaSdk
1900 javaSystem
1901 javaModule
1902 javaSystemServer
1903 javaPlatform
1904)
1905
1906func (lt sdkLinkType) String() string {
1907 switch lt {
1908 case javaCore:
1909 return "core Java API"
1910 case javaSdk:
1911 return "Android API"
1912 case javaSystem:
1913 return "system API"
1914 case javaModule:
1915 return "module API"
1916 case javaSystemServer:
1917 return "system server API"
1918 case javaPlatform:
1919 return "private API"
1920 default:
1921 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1922 }
1923}
1924
1925// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1926// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1927// can't statically depend on modules that use Platform API.
1928func (lt sdkLinkType) rank() int {
1929 return int(lt)
1930}
1931
1932type moduleWithSdkDep interface {
1933 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001934 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001935}
1936
Jiyong Park92315372021-04-02 08:45:46 +09001937func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001938 switch name {
Jihoon Kang91c83952023-05-30 19:12:28 +00001939 case android.SdkCore.DefaultJavaLibraryName(),
1940 "legacy.core.platform.api.stubs",
1941 "stable.core.platform.api.stubs",
Jaewoong Jung26342642021-03-17 15:56:23 -07001942 "stub-annotations", "private-stub-annotations-jar",
Jihoon Kang91c83952023-05-30 19:12:28 +00001943 "core-lambda-stubs",
Jihoon Kangb5078312023-03-29 23:25:49 +00001944 "core-generated-annotation-stubs":
Jaewoong Jung26342642021-03-17 15:56:23 -07001945 return javaCore, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001946 case android.SdkPublic.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001947 return javaSdk, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001948 case android.SdkSystem.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001949 return javaSystem, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001950 case android.SdkModule.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001951 return javaModule, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001952 case android.SdkSystemServer.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001953 return javaSystemServer, true
Jihoon Kang91c83952023-05-30 19:12:28 +00001954 case android.SdkTest.DefaultJavaLibraryName():
Jaewoong Jung26342642021-03-17 15:56:23 -07001955 return javaSystem, true
1956 }
1957
1958 if stub, linkType := moduleStubLinkType(name); stub {
1959 return linkType, true
1960 }
1961
Jiyong Park92315372021-04-02 08:45:46 +09001962 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001963 switch ver.Kind {
1964 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001965 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001966 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001967 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001968 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001969 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001970 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001971 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001972 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001973 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001974 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001975 return javaPlatform, false
1976 }
1977
Jiyong Parkf1691d22021-03-29 20:11:58 +09001978 if !ver.Valid() {
1979 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001980 }
1981 return javaSdk, false
1982}
1983
1984// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1985// this module's. See the comment on rank() for details and an example.
1986func (j *Module) checkSdkLinkType(
1987 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1988 if ctx.Host() {
1989 return
1990 }
1991
Jiyong Park92315372021-04-02 08:45:46 +09001992 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001993 if stubs {
1994 return
1995 }
Jiyong Park92315372021-04-02 08:45:46 +09001996 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001997
1998 if myLinkType.rank() < depLinkType.rank() {
1999 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
2000 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
2001 "property of the source or target module so that target module is built "+
2002 "with the same or smaller API set when compared to the source.",
2003 myLinkType, ctx.OtherModuleName(dep), depLinkType)
2004 }
2005}
2006
2007func (j *Module) collectDeps(ctx android.ModuleContext) deps {
2008 var deps deps
2009
2010 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09002011 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07002012 if sdkDep.invalidVersion {
2013 ctx.AddMissingDependencies(sdkDep.bootclasspath)
2014 ctx.AddMissingDependencies(sdkDep.java9Classpath)
2015 } else if sdkDep.useFiles {
2016 // sdkDep.jar is actually equivalent to turbine header.jar.
2017 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002018 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002019 deps.aidlPreprocess = sdkDep.aidl
2020 } else {
2021 deps.aidlPreprocess = sdkDep.aidl
2022 }
2023 }
2024
Jiyong Park92315372021-04-02 08:45:46 +09002025 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07002026
Sam Delmerico9f9c0a22022-11-29 11:19:37 -05002027 j.collectTransitiveHeaderJars(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07002028 ctx.VisitDirectDeps(func(module android.Module) {
2029 otherName := ctx.OtherModuleName(module)
2030 tag := ctx.OtherModuleDependencyTag(module)
2031
2032 if IsJniDepTag(tag) {
2033 // Handled by AndroidApp.collectAppDeps
2034 return
2035 }
2036 if tag == certificateTag {
2037 // Handled by AndroidApp.collectAppDeps
2038 return
2039 }
2040
2041 if dep, ok := module.(SdkLibraryDependency); ok {
2042 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002043 case sdkLibTag, libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002044 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
2045 deps.classpath = append(deps.classpath, depHeaderJars...)
2046 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002047 case staticLibTag:
2048 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
2049 }
2050 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
2051 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
2052 if sdkLinkType != javaPlatform &&
2053 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
2054 // dep is a sysprop implementation library, but this module is not linking against
2055 // the platform, so it gets the sysprop public stubs library instead. Replace
2056 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
2057 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
2058 dep = syspropDep.JavaInfo
2059 }
2060 switch tag {
2061 case bootClasspathTag:
2062 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
Liz Kammeref28a4c2022-09-23 16:50:56 -04002063 case sdkLibTag, libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00002064 if _, ok := module.(*Plugin); ok {
2065 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
2066 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002067 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002068 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002069 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2070 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2071 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2072 case java9LibTag:
2073 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
2074 case staticLibTag:
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 static_libs dependency", otherName)
2077 }
Jaewoong Jung26342642021-03-17 15:56:23 -07002078 deps.classpath = append(deps.classpath, dep.HeaderJars...)
2079 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
2080 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
2081 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
2082 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
2083 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
2084 // Turbine doesn't run annotation processors, so any module that uses an
2085 // annotation processor that generates API is incompatible with the turbine
2086 // optimization.
2087 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
2088 case pluginTag:
2089 if plugin, ok := module.(*Plugin); ok {
2090 if plugin.pluginProperties.Processor_class != nil {
2091 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
2092 } else {
2093 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2094 }
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 || Bool(plugin.pluginProperties.Generates_api)
2099 } else {
2100 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2101 }
2102 case errorpronePluginTag:
2103 if _, ok := module.(*Plugin); ok {
2104 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2105 } else {
2106 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2107 }
2108 case exportedPluginTag:
2109 if plugin, ok := module.(*Plugin); ok {
2110 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2111 if plugin.pluginProperties.Processor_class != nil {
2112 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2113 }
2114 // Turbine doesn't run annotation processors, so any module that uses an
2115 // annotation processor that generates API is incompatible with the turbine
2116 // optimization.
2117 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2118 } else {
2119 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2120 }
2121 case kotlinStdlibTag:
2122 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2123 case kotlinAnnotationsTag:
2124 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002125 case kotlinPluginTag:
2126 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002127 case syspropPublicStubDepTag:
2128 // This is a sysprop implementation library, forward the JavaInfoProvider from
2129 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2130 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2131 JavaInfo: dep,
2132 })
2133 }
2134 } else if dep, ok := module.(android.SourceFileProducer); ok {
2135 switch tag {
Liz Kammeref28a4c2022-09-23 16:50:56 -04002136 case sdkLibTag, libTag:
Jaewoong Jung26342642021-03-17 15:56:23 -07002137 checkProducesJars(ctx, dep)
2138 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002139 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002140 case staticLibTag:
2141 checkProducesJars(ctx, dep)
2142 deps.classpath = append(deps.classpath, dep.Srcs()...)
2143 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2144 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2145 }
2146 } else {
2147 switch tag {
2148 case bootClasspathTag:
2149 // If a system modules dependency has been added to the bootclasspath
2150 // then add its libs to the bootclasspath.
2151 sm := module.(SystemModulesProvider)
2152 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2153
2154 case systemModulesTag:
2155 if deps.systemModules != nil {
2156 panic("Found two system module dependencies")
2157 }
2158 sm := module.(SystemModulesProvider)
2159 outputDir, outputDeps := sm.OutputDirAndDeps()
2160 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002161
2162 case instrumentationForTag:
2163 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 -07002164 }
2165 }
2166
2167 addCLCFromDep(ctx, module, j.classLoaderContexts)
2168 })
2169
2170 return deps
2171}
2172
2173func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2174 deps.processorPath = append(deps.processorPath, pluginJars...)
2175 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2176}
2177
2178// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2179// this interface.
2180type ProvidesUsesLib interface {
2181 ProvidesUsesLib() *string
2182}
2183
2184func (j *Module) ProvidesUsesLib() *string {
2185 return j.usesLibraryProperties.Provides_uses_lib
2186}
satayev1c564cc2021-05-25 19:50:30 +01002187
2188type ModuleWithStem interface {
2189 Stem() string
2190}
2191
2192var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002193
2194func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2195 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002196 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002197 if lib, ok := ctx.Module().(*Library); ok {
2198 javaLibraryBp2Build(ctx, lib)
2199 }
2200 case "java_binary_host":
2201 if binary, ok := ctx.Module().(*Binary); ok {
2202 javaBinaryHostBp2Build(ctx, binary)
2203 }
Zi Wang65b36722023-05-23 15:18:33 -07002204 case "java_test_host":
2205 if testHost, ok := ctx.Module().(*TestHost); ok {
2206 javaTestHostBp2Build(ctx, testHost)
2207 }
Wei Libafb6d62021-12-10 03:14:59 -08002208 }
Wei Libafb6d62021-12-10 03:14:59 -08002209}