blob: 94daf37fc0cebd5ddc6816eba73be131a5786eb0 [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
Cole Faust2b1536e2021-06-18 12:25:54 -0700159 // This property can be in 3 states. When set to true, errorprone will
160 // be run during the regular build. When set to false, errorprone will
161 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
162 // environment variable is true. Setting this to false will improve build
163 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700164 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700165 }
166
167 Proto struct {
168 // List of extra options that will be passed to the proto generator.
169 Output_params []string
170 }
171
172 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000173 // If true, then the module supports statically including the jacocoagent
174 // into the library.
175 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700176
177 // List of files to include in the META-INF/services folder of the resulting jar.
178 Services []string `android:"path,arch_variant"`
179
180 // If true, package the kotlin stdlib into the jar. Defaults to true.
181 Static_kotlin_stdlib *bool `android:"arch_variant"`
182
183 // A list of java_library instances that provide additional hiddenapi annotations for the library.
184 Hiddenapi_additional_annotations []string
185}
186
187// Properties that are specific to device modules. Host module factories should not add these when
188// constructing a new module.
189type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000190 // If not blank, set to the version of the sdk to compile against.
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000191 // Defaults to private.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000192 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000193 // 1) numerical API level, "current", "none", or "core_platform"
194 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
195 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
196 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700197 Sdk_version *string
198
199 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000200 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700201 Min_sdk_version *string
202
satayev0a420e72021-11-29 17:25:52 +0000203 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
204 // Defaults to empty string "". See sdk_version for possible values.
205 Max_sdk_version *string
206
William Loh5a082f92022-05-17 20:21:50 +0000207 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
208 // Defaults to empty string "". See sdk_version for possible values.
209 Replace_max_sdk_version_placeholder *string
210
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000212 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700213 Target_sdk_version *string
214
215 // Whether to compile against the platform APIs instead of an SDK.
216 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000217 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700218 Platform_apis *bool
219
220 Aidl struct {
221 // Top level directories to pass to aidl tool
222 Include_dirs []string
223
224 // Directories rooted at the Android.bp file to pass to aidl tool
225 Local_include_dirs []string
226
227 // directories that should be added as include directories for any aidl sources of modules
228 // that depend on this module, as well as to aidl for this module.
229 Export_include_dirs []string
230
231 // whether to generate traces (for systrace) for this interface
232 Generate_traces *bool
233
234 // whether to generate Binder#GetTransaction name method.
235 Generate_get_transaction_name *bool
236
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100237 // whether all interfaces should be annotated with required permissions.
238 Enforce_permissions *bool
239
240 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
241 Enforce_permissions_exceptions []string `android:"path"`
242
Jaewoong Jung26342642021-03-17 15:56:23 -0700243 // list of flags that will be passed to the AIDL compiler
244 Flags []string
245 }
246
247 // If true, export a copy of the module as a -hostdex module for host testing.
248 Hostdex *bool
249
250 Target struct {
251 Hostdex struct {
252 // Additional required dependencies to add to -hostdex modules.
253 Required []string
254 }
255 }
256
257 // When targeting 1.9 and above, override the modules to use with --system,
258 // otherwise provides defaults libraries to add to the bootclasspath.
259 System_modules *string
260
Jaewoong Jung26342642021-03-17 15:56:23 -0700261 IsSDKLibrary bool `blueprint:"mutated"`
262
263 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
264 // Defaults to false.
265 V4_signature *bool
266
267 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
268 // public stubs library.
269 SyspropPublicStub string `blueprint:"mutated"`
270}
271
Jooyung Han01d80d82022-01-08 12:16:32 +0900272// Device properties that can be overridden by overriding module (e.g. override_android_app)
273type OverridableDeviceProperties struct {
274 // set the name of the output. If not set, `name` is used.
275 // To override a module with this property set, overriding module might need to set this as well.
276 // Otherwise, both the overridden and the overriding modules will have the same output name, which
277 // can cause the duplicate output error.
278 Stem *string
279}
280
Jaewoong Jung26342642021-03-17 15:56:23 -0700281// Functionality common to Module and Import
282//
283// It is embedded in Module so its functionality can be used by methods in Module
284// but it is currently only initialized by Import and Library.
285type embeddableInModuleAndImport struct {
286
287 // Functionality related to this being used as a component of a java_sdk_library.
288 EmbeddableSdkLibraryComponent
289}
290
Paul Duffin71b33cc2021-06-23 11:39:47 +0100291func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
292 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700293}
294
295// Module/Import's DepIsInSameApex(...) delegates to this method.
296//
297// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
298// the one provided by ApexModuleBase.
299func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
300 // dependencies other than the static linkage are all considered crossing APEX boundary
301 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
302 return true
303 }
304 return false
305}
306
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100307// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
308// or an invalid path describing the reason it is invalid.
309//
310// It is unset if a dex jar isn't applicable, i.e. no build rule has been
311// requested to create one.
312//
313// If a dex jar has been requested to be built then it is set, and it may be
314// either a valid android.Path, or invalid with a reason message. The latter
315// happens if the source that should produce the dex file isn't able to.
316//
317// E.g. it is invalid with a reason message if there is a prebuilt APEX that
318// could produce the dex jar through a deapexer module, but the APEX isn't
319// installable so doing so wouldn't be safe.
320type OptionalDexJarPath struct {
321 isSet bool
322 path android.OptionalPath
323}
324
325// IsSet returns true if a path has been set, either invalid or valid.
326func (o OptionalDexJarPath) IsSet() bool {
327 return o.isSet
328}
329
330// Valid returns true if there is a path that is valid.
331func (o OptionalDexJarPath) Valid() bool {
332 return o.isSet && o.path.Valid()
333}
334
335// Path returns the valid path, or panics if it's either not set or is invalid.
336func (o OptionalDexJarPath) Path() android.Path {
337 if !o.isSet {
338 panic("path isn't set")
339 }
340 return o.path.Path()
341}
342
343// PathOrNil returns the path if it's set and valid, or else nil.
344func (o OptionalDexJarPath) PathOrNil() android.Path {
345 if o.Valid() {
346 return o.Path()
347 }
348 return nil
349}
350
351// InvalidReason returns the reason for an invalid path, which is never "". It
352// returns "" for an unset or valid path.
353func (o OptionalDexJarPath) InvalidReason() string {
354 if !o.isSet {
355 return ""
356 }
357 return o.path.InvalidReason()
358}
359
360func (o OptionalDexJarPath) String() string {
361 if !o.isSet {
362 return "<unset>"
363 }
364 return o.path.String()
365}
366
367// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
368func makeUnsetDexJarPath() OptionalDexJarPath {
369 return OptionalDexJarPath{isSet: false}
370}
371
372// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
373// the given OptionalPath, which may be valid or invalid.
374func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
375 return OptionalDexJarPath{isSet: true, path: path}
376}
377
378// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
379// valid given path. It returns an unset OptionalDexJarPath if the given path is
380// nil.
381func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
382 if path == nil {
383 return makeUnsetDexJarPath()
384 }
385 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
386}
387
Jaewoong Jung26342642021-03-17 15:56:23 -0700388// Module contains the properties and members used by all java module types
389type Module struct {
390 android.ModuleBase
391 android.DefaultableModuleBase
392 android.ApexModuleBase
393 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800394 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700395
396 // Functionality common to Module and Import.
397 embeddableInModuleAndImport
398
399 properties CommonProperties
400 protoProperties android.ProtoProperties
401 deviceProperties DeviceProperties
402
Jooyung Han01d80d82022-01-08 12:16:32 +0900403 overridableDeviceProperties OverridableDeviceProperties
404
Jaewoong Jung26342642021-03-17 15:56:23 -0700405 // jar file containing header classes including static library dependencies, suitable for
406 // inserting into the bootclasspath/classpath of another compile
407 headerJarFile android.Path
408
409 // jar file containing implementation classes including static library dependencies but no
410 // resources
411 implementationJarFile android.Path
412
413 // jar file containing only resources including from static library dependencies
414 resourceJar android.Path
415
416 // args and dependencies to package source files into a srcjar
417 srcJarArgs []string
418 srcJarDeps android.Paths
419
420 // jar file containing implementation classes and resources including static library
421 // dependencies
422 implementationAndResourcesJar android.Path
423
424 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100425 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700426
427 // output file containing uninstrumented classes that will be instrumented by jacoco
428 jacocoReportClassesFile android.Path
429
430 // output file of the module, which may be a classes jar or a dex jar
431 outputFile android.Path
432 extraOutputFiles android.Paths
433
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100434 exportAidlIncludeDirs android.Paths
435 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700436
437 logtagsSrcs android.Paths
438
439 // installed file for binary dependency
440 installFile android.Path
441
Colin Cross3108ce12021-11-10 14:38:50 -0800442 // installed file for hostdex copy
443 hostdexInstallFile android.InstallPath
444
Jaewoong Jung26342642021-03-17 15:56:23 -0700445 // list of .java files and srcjars that was passed to javac
446 compiledJavaSrcs android.Paths
447 compiledSrcJars android.Paths
448
449 // manifest file to use instead of properties.Manifest
450 overrideManifest android.OptionalPath
451
Jaewoong Jung26342642021-03-17 15:56:23 -0700452 // list of plugins that this java module is exporting
453 exportedPluginJars android.Paths
454
455 // list of plugins that this java module is exporting
456 exportedPluginClasses []string
457
458 // if true, the exported plugins generate API and require disabling turbine.
459 exportedDisableTurbine bool
460
461 // list of source files, collected from srcFiles with unique java and all kt files,
462 // will be used by android.IDEInfo struct
463 expandIDEInfoCompiledSrcs []string
464
465 // expanded Jarjar_rules
466 expandJarjarRules android.Path
467
Jaewoong Jung26342642021-03-17 15:56:23 -0700468 // Extra files generated by the module type to be added as java resources.
469 extraResources android.Paths
470
471 hiddenAPI
472 dexer
473 dexpreopter
474 usesLibrary
475 linter
476
477 // list of the xref extraction files
478 kytheFiles android.Paths
479
480 // Collect the module directory for IDE info in java/jdeps.go.
481 modulePaths []string
482
483 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900484
485 sdkVersion android.SdkSpec
486 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000487 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400488
489 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700490}
491
Jiyong Park92315372021-04-02 08:45:46 +0900492func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
493 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900494 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700495 return nil
496 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900497 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000498 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700499 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
500 } else {
501 // Treat stable core platform as stable.
502 return nil
503 }
504 } else {
505 return fmt.Errorf("non stable SDK %v", sdkVersion)
506 }
507}
508
509// checkSdkVersions enforces restrictions around SDK dependencies.
510func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
511 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900512 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900513 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700514 ctx.PropertyErrorf("sdk_version",
515 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
516 }
517 }
518 }
519
520 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
521 // See rank() for details.
522 ctx.VisitDirectDeps(func(module android.Module) {
523 tag := ctx.OtherModuleDependencyTag(module)
524 switch module.(type) {
525 // TODO(satayev): cover other types as well, e.g. imports
526 case *Library, *AndroidLibrary:
527 switch tag {
528 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
529 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
530 }
531 }
532 })
533}
534
535func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900536 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700537 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900538 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700539 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000540 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 -0700541 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000542 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 -0700543 }
544
545 }
546}
547
548func (j *Module) addHostProperties() {
549 j.AddProperties(
550 &j.properties,
551 &j.protoProperties,
552 &j.usesLibraryProperties,
553 )
554}
555
556func (j *Module) addHostAndDeviceProperties() {
557 j.addHostProperties()
558 j.AddProperties(
559 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900560 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700561 &j.dexer.dexProperties,
562 &j.dexpreoptProperties,
563 &j.linter.properties,
564 )
565}
566
567func (j *Module) OutputFiles(tag string) (android.Paths, error) {
568 switch tag {
569 case "":
570 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
571 case android.DefaultDistTag:
572 return android.Paths{j.outputFile}, nil
573 case ".jar":
574 return android.Paths{j.implementationAndResourcesJar}, nil
575 case ".proguard_map":
576 if j.dexer.proguardDictionary.Valid() {
577 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
578 }
579 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
580 default:
581 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
582 }
583}
584
585var _ android.OutputFileProducer = (*Module)(nil)
586
587func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
588 initJavaModule(module, hod, false)
589}
590
591func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
592 initJavaModule(module, hod, true)
593}
594
595func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
596 multilib := android.MultilibCommon
597 if multiTargets {
598 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
599 } else {
600 android.InitAndroidArchModule(module, hod, multilib)
601 }
602 android.InitDefaultableModule(module)
603}
604
605func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
606 return j.properties.Instrument &&
607 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
608 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
609}
610
611func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000612 return j.properties.Supports_static_instrumentation &&
613 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700614 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
615 ctx.Config().UnbundledBuild())
616}
617
618func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
619 // Force enable the instrumentation for java code that is built for APEXes ...
620 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
621 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
622 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
623 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
624 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
625 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
626 return true
627 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
628 return true
629 }
630 }
631 return false
632}
633
Jiyong Park92315372021-04-02 08:45:46 +0900634func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
635 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700636}
637
Jiyong Parkf1691d22021-03-29 20:11:58 +0900638func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700639 return proptools.String(j.deviceProperties.System_modules)
640}
641
Jiyong Park92315372021-04-02 08:45:46 +0900642func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700643 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900644 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700645 }
Jiyong Park92315372021-04-02 08:45:46 +0900646 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700647}
648
satayev0a420e72021-11-29 17:25:52 +0000649func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
650 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
651 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
652 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
653 return android.SdkSpecFrom(ctx, maxSdkVersion)
654}
655
William Loh5a082f92022-05-17 20:21:50 +0000656func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
657 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
658 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
659}
660
Jiyong Parkf1691d22021-03-29 20:11:58 +0900661func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900662 return j.minSdkVersion.Raw
663}
664
665func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
666 if j.deviceProperties.Target_sdk_version != nil {
667 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
668 }
669 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700670}
671
672func (j *Module) AvailableFor(what string) bool {
673 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
674 // Exception: for hostdex: true libraries, the platform variant is created
675 // even if it's not marked as available to platform. In that case, the platform
676 // variant is used only for the hostdex and not installed to the device.
677 return true
678 }
679 return j.ApexModuleBase.AvailableFor(what)
680}
681
682func (j *Module) deps(ctx android.BottomUpMutatorContext) {
683 if ctx.Device() {
684 j.linter.deps(ctx)
685
Jiyong Parkf1691d22021-03-29 20:11:58 +0900686 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700687
688 if j.deviceProperties.SyspropPublicStub != "" {
689 // This is a sysprop implementation library that has a corresponding sysprop public
690 // stubs library, and a dependency on it so that dependencies on the implementation can
691 // be forwarded to the public stubs library when necessary.
692 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
693 }
694 }
695
696 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
697 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
698
699 // Add dependency on libraries that provide additional hidden api annotations.
700 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
701
702 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
703 // Require java_sdk_library at inter-partition java dependency to ensure stable
704 // interface between partitions. If inter-partition java_library dependency is detected,
705 // raise build error because java_library doesn't have a stable interface.
706 //
707 // Inputs:
708 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
709 // if true, enable enforcement
710 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
711 // exception list of java_library names to allow inter-partition dependency
712 for idx := range j.properties.Libs {
713 if libDeps[idx] == nil {
714 continue
715 }
716
717 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
718 // java_sdk_library is always allowed at inter-partition dependency.
719 // So, skip check.
720 if _, ok := javaDep.(*SdkLibrary); ok {
721 continue
722 }
723
724 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
725 }
726 }
727 }
728
729 // For library dependencies that are component libraries (like stubs), add the implementation
730 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
731 for _, dep := range libDeps {
732 if dep != nil {
733 if component, ok := dep.(SdkLibraryComponentDependency); ok {
734 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100735 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100736 tag := usesLibReqTag
737 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
738 tag = usesLibOptTag
739 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100740 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700741 }
742 }
743 }
744 }
745
746 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
747 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
748 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
749
750 android.ProtoDeps(ctx, &j.protoProperties)
751 if j.hasSrcExt(".proto") {
752 protoDeps(ctx, &j.protoProperties)
753 }
754
755 if j.hasSrcExt(".kt") {
756 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
757 // Kotlin files
758 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
759 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700760 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700761 }
762
763 // Framework libraries need special handling in static coverage builds: they should not have
764 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
765 // the same jacoco classes coming from different bootclasspath jars.
766 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
767 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
768 j.properties.Instrument = true
769 }
770 } else if j.shouldInstrumentStatic(ctx) {
771 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
772 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700773
774 if j.useCompose() {
775 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
776 "androidx.compose.compiler_compiler-hosted")
777 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700778}
779
780func hasSrcExt(srcs []string, ext string) bool {
781 for _, src := range srcs {
782 if filepath.Ext(src) == ext {
783 return true
784 }
785 }
786
787 return false
788}
789
790func (j *Module) hasSrcExt(ext string) bool {
791 return hasSrcExt(j.properties.Srcs, ext)
792}
793
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100794func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
795 var flags string
796
797 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
798 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
799 flags = "-Wmissing-permission-annotation -Werror"
800 }
801 }
802 return flags
803}
804
Jaewoong Jung26342642021-03-17 15:56:23 -0700805func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
806 aidlIncludeDirs android.Paths) (string, android.Paths) {
807
808 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
809 aidlIncludes = append(aidlIncludes,
810 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
811 aidlIncludes = append(aidlIncludes,
812 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
813
814 var flags []string
815 var deps android.Paths
816
817 flags = append(flags, j.deviceProperties.Aidl.Flags...)
818
819 if aidlPreprocess.Valid() {
820 flags = append(flags, "-p"+aidlPreprocess.String())
821 deps = append(deps, aidlPreprocess.Path())
822 } else if len(aidlIncludeDirs) > 0 {
823 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
824 }
825
826 if len(j.exportAidlIncludeDirs) > 0 {
827 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
828 }
829
830 if len(aidlIncludes) > 0 {
831 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
832 }
833
834 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
835 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
836 flags = append(flags, "-I"+src.String())
837 }
838
839 if Bool(j.deviceProperties.Aidl.Generate_traces) {
840 flags = append(flags, "-t")
841 }
842
843 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
844 flags = append(flags, "--transaction_names")
845 }
846
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100847 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
848 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
849 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
850 }
851
Jooyung Han07f70c02021-11-06 07:08:45 +0900852 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
853 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
854
Jaewoong Jung26342642021-03-17 15:56:23 -0700855 return strings.Join(flags, " "), deps
856}
857
858func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
859
860 var flags javaBuilderFlags
861
862 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900863 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700864
Cole Faust2b1536e2021-06-18 12:25:54 -0700865 epEnabled := j.properties.Errorprone.Enabled
866 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700867 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
868 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
869 }
870
871 errorProneFlags := []string{
872 "-Xplugin:ErrorProne",
873 "${config.ErrorProneChecks}",
874 }
875 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
876
Colin Cross8bf6cad2022-02-28 13:07:03 -0800877 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700878 "'" + strings.Join(errorProneFlags, " ") + "'"
879 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
880 }
881
882 // classpath
883 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
884 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700885 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700886 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
887 flags.processorPath = append(flags.processorPath, deps.processorPath...)
888 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
889
890 flags.processors = append(flags.processors, deps.processorClasses...)
891 flags.processors = android.FirstUniqueStrings(flags.processors)
892
893 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900894 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700895 // Give host-side tools a version of OpenJDK's standard libraries
896 // close to what they're targeting. As of Dec 2017, AOSP is only
897 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
898 //
899 // When building with OpenJDK 8, the following should have no
900 // effect since those jars would be available by default.
901 //
902 // When building with OpenJDK 9 but targeting a version < 1.8,
903 // putting them on the bootclasspath means that:
904 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
905 // b) references to existing APIs are not reinterpreted in an
906 // OpenJDK 9-specific way, eg. calls to subclasses of
907 // java.nio.Buffer as in http://b/70862583
908 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
909 flags.bootClasspath = append(flags.bootClasspath,
910 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
911 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
912 if Bool(j.properties.Use_tools_jar) {
913 flags.bootClasspath = append(flags.bootClasspath,
914 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
915 }
916 }
917
918 // systemModules
919 flags.systemModules = deps.systemModules
920
921 // aidl flags.
922 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
923
924 return flags
925}
926
927func (j *Module) collectJavacFlags(
928 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
929 // javac flags.
930 javacFlags := j.properties.Javacflags
931
932 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
933 // For non-host binaries, override the -g flag passed globally to remove
934 // local variable debug info to reduce disk and memory usage.
935 javacFlags = append(javacFlags, "-g:source,lines")
936 }
937 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
938
939 if flags.javaVersion.usesJavaModules() {
940 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
941
942 if j.properties.Patch_module != nil {
943 // Manually specify build directory in case it is not under the repo root.
944 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
945 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200946 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700947
948 // b/150878007
949 //
950 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
951 // execution root for --patch-module. If this javac command line is
952 // invoked within Bazel's execution root working directory, the top
953 // level directories (e.g. libcore/, tools/, frameworks/) are all
954 // symlinks. JDK9 javac does not traverse into symlinks, which causes
955 // --patch-module to fail source file lookups when invoked in the
956 // execution root.
957 //
958 // Short of patching javac or enumerating *all* directories as possible
959 // input dirs, manually add the top level dir of the source files to be
960 // compiled.
961 topLevelDirs := map[string]bool{}
962 for _, srcFilePath := range srcFiles {
963 srcFileParts := strings.Split(srcFilePath.String(), "/")
964 // Ignore source files that are already in the top level directory
965 // as well as generated files in the out directory. The out
966 // directory may be an absolute path, which means srcFileParts[0] is the
967 // empty string, so check that as well. Note that "out" in Bazel's execution
968 // root is *not* a symlink, which doesn't cause problems for --patch-modules
969 // anyway, so it's fine to not apply this workaround for generated
970 // source files.
971 if len(srcFileParts) > 1 &&
972 srcFileParts[0] != "" &&
973 srcFileParts[0] != "out" {
974 topLevelDirs[srcFileParts[0]] = true
975 }
976 }
977 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
978
979 classPath := flags.classpath.FormJavaClassPath("")
980 if classPath != "" {
981 patchPaths = append(patchPaths, classPath)
982 }
983 javacFlags = append(
984 javacFlags,
985 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
986 }
987 }
988
989 if len(javacFlags) > 0 {
990 // optimization.
991 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
992 flags.javacFlags = "$javacFlags"
993 }
994
995 return flags
996}
997
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400998func (j *Module) AddJSONData(d *map[string]interface{}) {
999 (&j.ModuleBase).AddJSONData(d)
1000 (*d)["Java"] = map[string]interface{}{
1001 "SourceExtensions": j.sourceExtensions,
1002 }
1003
1004}
1005
Jaewoong Jung26342642021-03-17 15:56:23 -07001006func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1007 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1008
1009 deps := j.collectDeps(ctx)
1010 flags := j.collectBuilderFlags(ctx, deps)
1011
1012 if flags.javaVersion.usesJavaModules() {
1013 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1014 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001015
Jaewoong Jung26342642021-03-17 15:56:23 -07001016 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001017 j.sourceExtensions = []string{}
1018 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1019 if hasSrcExt(srcFiles.Strings(), ext) {
1020 j.sourceExtensions = append(j.sourceExtensions, ext)
1021 }
1022 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001023 if hasSrcExt(srcFiles.Strings(), ".proto") {
1024 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1025 }
1026
1027 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1028 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1029 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1030 }
1031
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001032 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001033 srcFiles = j.genSources(ctx, srcFiles, flags)
1034
1035 // Collect javac flags only after computing the full set of srcFiles to
1036 // ensure that the --patch-module lookup paths are complete.
1037 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1038
1039 srcJars := srcFiles.FilterByExt(".srcjar")
1040 srcJars = append(srcJars, deps.srcJars...)
1041 if aaptSrcJar != nil {
1042 srcJars = append(srcJars, aaptSrcJar)
1043 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001044 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001045
1046 if j.properties.Jarjar_rules != nil {
1047 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1048 }
1049
1050 jarName := ctx.ModuleName() + ".jar"
1051
1052 javaSrcFiles := srcFiles.FilterByExt(".java")
1053 var uniqueSrcFiles android.Paths
1054 set := make(map[string]bool)
1055 for _, v := range javaSrcFiles {
1056 if _, found := set[v.String()]; !found {
1057 set[v.String()] = true
1058 uniqueSrcFiles = append(uniqueSrcFiles, v)
1059 }
1060 }
1061
Colin Crossb5db4012022-03-28 17:12:39 -07001062 // We don't currently run annotation processors in turbine, which means we can't use turbine
1063 // generated header jars when an annotation processor that generates API is enabled. One
1064 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1065 // is used to run all of the annotation processors.
1066 disableTurbine := deps.disableTurbine
1067
Jaewoong Jung26342642021-03-17 15:56:23 -07001068 // Collect .java files for AIDEGen
1069 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1070
1071 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001072 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001073
1074 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001075 // When using kotlin sources turbine is used to generate annotation processor sources,
1076 // including for annotation processors that generate API, so we can use turbine for
1077 // java sources too.
1078 disableTurbine = false
1079
Jaewoong Jung26342642021-03-17 15:56:23 -07001080 // user defined kotlin flags.
1081 kotlincFlags := j.properties.Kotlincflags
1082 CheckKotlincFlags(ctx, kotlincFlags)
1083
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001084 // Workaround for KT-46512
1085 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001086
1087 // If there are kotlin files, compile them first but pass all the kotlin and java files
1088 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1089 // won't emit any classes for them.
1090 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1091 if ctx.Device() {
1092 kotlincFlags = append(kotlincFlags, "-no-jdk")
1093 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001094
1095 for _, plugin := range deps.kotlinPlugins {
1096 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1097 }
1098 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1099
Jaewoong Jung26342642021-03-17 15:56:23 -07001100 if len(kotlincFlags) > 0 {
1101 // optimization.
1102 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1103 flags.kotlincFlags += "$kotlincFlags"
1104 }
1105
1106 var kotlinSrcFiles android.Paths
1107 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1108 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1109
1110 // Collect .kt files for AIDEGen
1111 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1112 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1113
1114 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1115 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1116
1117 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1118 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1119
Isaac Chioua23d9942022-04-06 06:14:38 +00001120 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001121 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001122 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1123 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1124 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1125 srcJars = append(srcJars, kaptSrcJar)
1126 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001127 // Disable annotation processing in javac, it's already been handled by kapt
1128 flags.processorPath = nil
1129 flags.processors = nil
1130 }
1131
1132 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001133 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1134 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001135 if ctx.Failed() {
1136 return
1137 }
1138
Isaac Chioua23d9942022-04-06 06:14:38 +00001139 // Make javac rule depend on the kotlinc rule
1140 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1141
Jaewoong Jung26342642021-03-17 15:56:23 -07001142 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001143 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1144
Jaewoong Jung26342642021-03-17 15:56:23 -07001145 // Jar kotlin classes into the final jar after javac
1146 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1147 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001148 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001149 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001150 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001151 } else {
1152 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001153 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 }
1155 }
1156
1157 jars := append(android.Paths(nil), kotlinJars...)
1158
1159 // Store the list of .java files that was passed to javac
1160 j.compiledJavaSrcs = uniqueSrcFiles
1161 j.compiledSrcJars = srcJars
1162
1163 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001164 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001165 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001166 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1167 enableSharding = true
1168 // Formerly, there was a check here that prevented annotation processors
1169 // from being used when sharding was enabled, as some annotation processors
1170 // do not function correctly in sharded environments. It was removed to
1171 // allow for the use of annotation processors that do function correctly
1172 // with sharding enabled. See: b/77284273.
1173 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001174 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001175 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001176 if ctx.Failed() {
1177 return
1178 }
1179 }
1180 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1181 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001182 if Bool(j.properties.Errorprone.Enabled) {
1183 // If error-prone is enabled, enable errorprone flags on the regular
1184 // build.
1185 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001186 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001187 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1188 // a new jar file just for compiling with the errorprone compiler to.
1189 // This is because we don't want to cause the java files to get completely
1190 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1191 // We also don't want to run this if errorprone is enabled by default for
1192 // this module, or else we could have duplicated errorprone messages.
1193 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001194 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001195
1196 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1197 "errorprone", "errorprone")
1198
Jaewoong Jung26342642021-03-17 15:56:23 -07001199 extraJarDeps = append(extraJarDeps, errorprone)
1200 }
1201
1202 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001203 if headerJarFileWithoutDepsOrJarjar != nil {
1204 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1205 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001206 shardSize := int(*(j.properties.Javac_shard_size))
1207 var shardSrcs []android.Paths
1208 if len(uniqueSrcFiles) > 0 {
1209 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1210 for idx, shardSrc := range shardSrcs {
1211 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1212 nil, flags, extraJarDeps)
1213 jars = append(jars, classes)
1214 }
1215 }
1216 if len(srcJars) > 0 {
1217 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1218 nil, srcJars, flags, extraJarDeps)
1219 jars = append(jars, classes)
1220 }
1221 } else {
1222 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1223 jars = append(jars, classes)
1224 }
1225 if ctx.Failed() {
1226 return
1227 }
1228 }
1229
1230 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1231
1232 var includeSrcJar android.WritablePath
1233 if Bool(j.properties.Include_srcs) {
1234 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1235 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1236 }
1237
1238 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1239 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1240 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1241 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1242
1243 var resArgs []string
1244 var resDeps android.Paths
1245
1246 resArgs = append(resArgs, dirArgs...)
1247 resDeps = append(resDeps, dirDeps...)
1248
1249 resArgs = append(resArgs, fileArgs...)
1250 resDeps = append(resDeps, fileDeps...)
1251
1252 resArgs = append(resArgs, extraArgs...)
1253 resDeps = append(resDeps, extraDeps...)
1254
1255 if len(resArgs) > 0 {
1256 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1257 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1258 j.resourceJar = resourceJar
1259 if ctx.Failed() {
1260 return
1261 }
1262 }
1263
1264 var resourceJars android.Paths
1265 if j.resourceJar != nil {
1266 resourceJars = append(resourceJars, j.resourceJar)
1267 }
1268 if Bool(j.properties.Include_srcs) {
1269 resourceJars = append(resourceJars, includeSrcJar)
1270 }
1271 resourceJars = append(resourceJars, deps.staticResourceJars...)
1272
1273 if len(resourceJars) > 1 {
1274 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1275 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1276 false, nil, nil)
1277 j.resourceJar = combinedJar
1278 } else if len(resourceJars) == 1 {
1279 j.resourceJar = resourceJars[0]
1280 }
1281
1282 if len(deps.staticJars) > 0 {
1283 jars = append(jars, deps.staticJars...)
1284 }
1285
1286 manifest := j.overrideManifest
1287 if !manifest.Valid() && j.properties.Manifest != nil {
1288 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1289 }
1290
1291 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1292 if len(services) > 0 {
1293 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1294 var zipargs []string
1295 for _, file := range services {
1296 serviceFile := file.String()
1297 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1298 }
1299 rule := zip
1300 args := map[string]string{
1301 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1302 }
1303 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1304 rule = zipRE
1305 args["implicits"] = strings.Join(services.Strings(), ",")
1306 }
1307 ctx.Build(pctx, android.BuildParams{
1308 Rule: rule,
1309 Output: servicesJar,
1310 Implicits: services,
1311 Args: args,
1312 })
1313 jars = append(jars, servicesJar)
1314 }
1315
1316 // Combine the classes built from sources, any manifests, and any static libraries into
1317 // classes.jar. If there is only one input jar this step will be skipped.
1318 var outputFile android.OutputPath
1319
1320 if len(jars) == 1 && !manifest.Valid() {
1321 // Optimization: skip the combine step as there is nothing to do
1322 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1323 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1324 // any if len(jars) == 1.
1325
1326 // Transform the single path to the jar into an OutputPath as that is required by the following
1327 // code.
1328 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1329 // The path contains an embedded OutputPath so reuse that.
1330 outputFile = moduleOutPath.OutputPath
1331 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1332 // The path is an OutputPath so reuse it directly.
1333 outputFile = outputPath
1334 } else {
1335 // The file is not in the out directory so create an OutputPath into which it can be copied
1336 // and which the following code can use to refer to it.
1337 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1338 ctx.Build(pctx, android.BuildParams{
1339 Rule: android.Cp,
1340 Input: jars[0],
1341 Output: combinedJar,
1342 })
1343 outputFile = combinedJar.OutputPath
1344 }
1345 } else {
1346 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1347 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1348 false, nil, nil)
1349 outputFile = combinedJar.OutputPath
1350 }
1351
1352 // jarjar implementation jar if necessary
1353 if j.expandJarjarRules != nil {
1354 // Transform classes.jar into classes-jarjar.jar
1355 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1356 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1357 outputFile = jarjarFile
1358
1359 // jarjar resource jar if necessary
1360 if j.resourceJar != nil {
1361 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1362 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1363 j.resourceJar = resourceJarJarFile
1364 }
1365
1366 if ctx.Failed() {
1367 return
1368 }
1369 }
1370
1371 // Check package restrictions if necessary.
1372 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001373 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001374 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001375
1376 // Create a rule to copy the output jar to another path and add a validate dependency that
1377 // will check that the jar only contains the permitted packages. The new location will become
1378 // the output file of this module.
1379 inputFile := outputFile
1380 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1381 ctx.Build(pctx, android.BuildParams{
1382 Rule: android.Cp,
1383 Input: inputFile,
1384 Output: outputFile,
1385 // Make sure that any dependency on the output file will cause ninja to run the package check
1386 // rule.
1387 Validation: pkgckFile,
1388 })
1389
1390 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001391 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001392
1393 if ctx.Failed() {
1394 return
1395 }
1396 }
1397
1398 j.implementationJarFile = outputFile
1399 if j.headerJarFile == nil {
1400 j.headerJarFile = j.implementationJarFile
1401 }
1402
1403 if j.shouldInstrumentInApex(ctx) {
1404 j.properties.Instrument = true
1405 }
1406
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001407 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1408 specs := j.jacocoModuleToZipCommand(ctx)
1409 if ctx.Failed() {
1410 return
1411 }
1412
Jaewoong Jung26342642021-03-17 15:56:23 -07001413 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001414 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001415 }
1416
1417 // merge implementation jar with resources if necessary
1418 implementationAndResourcesJar := outputFile
1419 if j.resourceJar != nil {
1420 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1421 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1422 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1423 false, nil, nil)
1424 implementationAndResourcesJar = combinedJar
1425 }
1426
1427 j.implementationAndResourcesJar = implementationAndResourcesJar
1428
1429 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001430 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001431 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1432 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001433 if compileDex == nil {
1434 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001435 }
1436 if j.deviceProperties.Hostdex == nil {
1437 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1438 }
1439 }
1440
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001441 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001442 if j.hasCode(ctx) {
1443 if j.shouldInstrumentStatic(ctx) {
1444 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1445 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1446 }
1447 // Dex compilation
1448 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001449 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001450 if ctx.Failed() {
1451 return
1452 }
1453
Jaewoong Jung26342642021-03-17 15:56:23 -07001454 // merge dex jar with resources if necessary
1455 if j.resourceJar != nil {
1456 jars := android.Paths{dexOutputFile, j.resourceJar}
1457 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1458 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1459 false, nil, nil)
1460 if *j.dexProperties.Uncompress_dex {
1461 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1462 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1463 dexOutputFile = combinedAlignedJar
1464 } else {
1465 dexOutputFile = combinedJar
1466 }
1467 }
1468
Paul Duffin4de94502021-05-16 05:21:16 +01001469 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001470
1471 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001472
1473 // Encode hidden API flags in dex file, if needed.
1474 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1475
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001476 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001477
1478 // Dexpreopting
1479 j.dexpreopt(ctx, dexOutputFile)
1480
1481 outputFile = dexOutputFile
1482 } else {
1483 // There is no code to compile into a dex jar, make sure the resources are propagated
1484 // to the APK if this is an app.
1485 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001486 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001487 }
1488
1489 if ctx.Failed() {
1490 return
1491 }
1492 } else {
1493 outputFile = implementationAndResourcesJar
1494 }
1495
1496 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001497 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001498 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001499 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001500 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001501 // When running metalava, we pass --version-codename. When that value
1502 // is not REL, metalava will add 1 to the --current-version argument.
1503 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1504 // branch) and the codename is REL, except potentially on the most
1505 // recent non-master branch. On that branch, it goes through two other
1506 // phases before it gets to the phase previously described:
1507 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1508 // is not rel. This happens for most of the internal branch's life
1509 // while the branch has been cut but is still under active development.
1510 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1511 // REL. This happens briefly during the release process. During this
1512 // state the code to add --current-version is commented out, and then
1513 // that commenting out is reverted after the codename is set to REL.
1514 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1515 // prior version and the codename is always non-REL.
1516 //
1517 // We need to add one here to match metalava adding 1. Technically
1518 // this means that in the state described in the second bullet point
1519 // above, this number is 1 higher than it should be.
1520 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001521 }
1522 }
1523
1524 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001525 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1526 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001527 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1528 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001529 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1530 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1531 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001532 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001533 j.linter.javaLanguageLevel = flags.javaVersion.String()
1534 j.linter.kotlinLanguageLevel = "1.3"
1535 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1536 j.linter.buildModuleReportZip = true
1537 }
1538 j.linter.lint(ctx)
1539 }
1540
1541 ctx.CheckbuildFile(outputFile)
1542
1543 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1544 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1545 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1546 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1547 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1548 AidlIncludeDirs: j.exportAidlIncludeDirs,
1549 SrcJarArgs: j.srcJarArgs,
1550 SrcJarDeps: j.srcJarDeps,
1551 ExportedPlugins: j.exportedPluginJars,
1552 ExportedPluginClasses: j.exportedPluginClasses,
1553 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1554 JacocoReportClassesFile: j.jacocoReportClassesFile,
1555 })
1556
1557 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1558 j.outputFile = outputFile.WithoutRel()
1559}
1560
Colin Crossa1ff7c62021-09-17 14:11:52 -07001561func (j *Module) useCompose() bool {
1562 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1563}
1564
Cole Faust75fffb12021-06-13 15:23:16 -07001565// Returns a copy of the supplied flags, but with all the errorprone-related
1566// fields copied to the regular build's fields.
1567func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1568 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1569
1570 if len(flags.errorProneExtraJavacFlags) > 0 {
1571 if len(flags.javacFlags) > 0 {
1572 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1573 } else {
1574 flags.javacFlags = flags.errorProneExtraJavacFlags
1575 }
1576 }
1577 return flags
1578}
1579
Jaewoong Jung26342642021-03-17 15:56:23 -07001580func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1581 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1582
1583 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1584 if idx >= 0 {
1585 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1586 jarName += strconv.Itoa(idx)
1587 }
1588
1589 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1590 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1591
1592 if ctx.Config().EmitXrefRules() {
1593 extractionFile := android.PathForModuleOut(ctx, kzipName)
1594 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1595 j.kytheFiles = append(j.kytheFiles, extractionFile)
1596 }
1597
1598 return classes
1599}
1600
1601// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1602// since some of these flags may be used internally.
1603func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1604 for _, flag := range flags {
1605 flag = strings.TrimSpace(flag)
1606
1607 if !strings.HasPrefix(flag, "-") {
1608 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1609 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1610 ctx.PropertyErrorf("kotlincflags",
1611 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1612 } else if inList(flag, config.KotlincIllegalFlags) {
1613 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1614 } else if flag == "-include-runtime" {
1615 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1616 } else {
1617 args := strings.Split(flag, " ")
1618 if args[0] == "-kotlin-home" {
1619 ctx.PropertyErrorf("kotlincflags",
1620 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1621 }
1622 }
1623 }
1624}
1625
1626func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1627 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001628 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001629
1630 var jars android.Paths
1631 if len(srcFiles) > 0 || len(srcJars) > 0 {
1632 // Compile java sources into turbine.jar.
1633 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1634 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1635 if ctx.Failed() {
1636 return nil, nil
1637 }
1638 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001639 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001640 }
1641
1642 jars = append(jars, extraJars...)
1643
1644 // Combine any static header libraries into classes-header.jar. If there is only
1645 // one input jar this step will be skipped.
1646 jars = append(jars, deps.staticHeaderJars...)
1647
1648 // we cannot skip the combine step for now if there is only one jar
1649 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1650 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1651 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1652 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001653 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001654
1655 if j.expandJarjarRules != nil {
1656 // Transform classes.jar into classes-jarjar.jar
1657 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001658 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1659 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001660 if ctx.Failed() {
1661 return nil, nil
1662 }
1663 }
1664
Colin Cross3d56ed52021-11-18 22:23:12 -08001665 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001666}
1667
1668func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001669 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001670
1671 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1672 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1673
1674 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1675
1676 j.jacocoReportClassesFile = jacocoReportClassesFile
1677
1678 return instrumentedJar
1679}
1680
1681func (j *Module) HeaderJars() android.Paths {
1682 if j.headerJarFile == nil {
1683 return nil
1684 }
1685 return android.Paths{j.headerJarFile}
1686}
1687
1688func (j *Module) ImplementationJars() android.Paths {
1689 if j.implementationJarFile == nil {
1690 return nil
1691 }
1692 return android.Paths{j.implementationJarFile}
1693}
1694
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001695func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001696 return j.dexJarFile
1697}
1698
1699func (j *Module) DexJarInstallPath() android.Path {
1700 return j.installFile
1701}
1702
1703func (j *Module) ImplementationAndResourcesJars() android.Paths {
1704 if j.implementationAndResourcesJar == nil {
1705 return nil
1706 }
1707 return android.Paths{j.implementationAndResourcesJar}
1708}
1709
1710func (j *Module) AidlIncludeDirs() android.Paths {
1711 // exportAidlIncludeDirs is type android.Paths already
1712 return j.exportAidlIncludeDirs
1713}
1714
1715func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1716 return j.classLoaderContexts
1717}
1718
1719// Collect information for opening IDE project files in java/jdeps.go.
1720func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1721 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1722 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1723 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1724 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1725 if j.expandJarjarRules != nil {
1726 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1727 }
1728 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001729 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1730 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001731}
1732
1733func (j *Module) CompilerDeps() []string {
1734 jdeps := []string{}
1735 jdeps = append(jdeps, j.properties.Libs...)
1736 jdeps = append(jdeps, j.properties.Static_libs...)
1737 return jdeps
1738}
1739
1740func (j *Module) hasCode(ctx android.ModuleContext) bool {
1741 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1742 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1743}
1744
1745// Implements android.ApexModule
1746func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1747 return j.depIsInSameApex(ctx, dep)
1748}
1749
1750// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001751func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001752 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001753 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001754 return fmt.Errorf("min_sdk_version is not specified")
1755 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001756 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001757 return nil
1758 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001759 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1760 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001761 }
1762 return nil
1763}
1764
1765func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001766 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001767}
1768
Jaewoong Jung26342642021-03-17 15:56:23 -07001769func (j *Module) JacocoReportClassesFile() android.Path {
1770 return j.jacocoReportClassesFile
1771}
1772
1773func (j *Module) IsInstallable() bool {
1774 return Bool(j.properties.Installable)
1775}
1776
1777type sdkLinkType int
1778
1779const (
1780 // TODO(jiyong) rename these for better readability. Make the allowed
1781 // and disallowed link types explicit
1782 // order is important here. See rank()
1783 javaCore sdkLinkType = iota
1784 javaSdk
1785 javaSystem
1786 javaModule
1787 javaSystemServer
1788 javaPlatform
1789)
1790
1791func (lt sdkLinkType) String() string {
1792 switch lt {
1793 case javaCore:
1794 return "core Java API"
1795 case javaSdk:
1796 return "Android API"
1797 case javaSystem:
1798 return "system API"
1799 case javaModule:
1800 return "module API"
1801 case javaSystemServer:
1802 return "system server API"
1803 case javaPlatform:
1804 return "private API"
1805 default:
1806 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1807 }
1808}
1809
1810// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1811// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1812// can't statically depend on modules that use Platform API.
1813func (lt sdkLinkType) rank() int {
1814 return int(lt)
1815}
1816
1817type moduleWithSdkDep interface {
1818 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001819 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001820}
1821
Jiyong Park92315372021-04-02 08:45:46 +09001822func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001823 switch name {
1824 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1825 "stub-annotations", "private-stub-annotations-jar",
1826 "core-lambda-stubs", "core-generated-annotation-stubs":
1827 return javaCore, true
1828 case "android_stubs_current":
1829 return javaSdk, true
1830 case "android_system_stubs_current":
1831 return javaSystem, true
1832 case "android_module_lib_stubs_current":
1833 return javaModule, true
1834 case "android_system_server_stubs_current":
1835 return javaSystemServer, true
1836 case "android_test_stubs_current":
1837 return javaSystem, true
1838 }
1839
1840 if stub, linkType := moduleStubLinkType(name); stub {
1841 return linkType, true
1842 }
1843
Jiyong Park92315372021-04-02 08:45:46 +09001844 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001845 switch ver.Kind {
1846 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001847 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001848 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001849 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001850 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001851 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001852 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001853 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001854 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001855 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001856 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001857 return javaPlatform, false
1858 }
1859
Jiyong Parkf1691d22021-03-29 20:11:58 +09001860 if !ver.Valid() {
1861 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001862 }
1863 return javaSdk, false
1864}
1865
1866// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1867// this module's. See the comment on rank() for details and an example.
1868func (j *Module) checkSdkLinkType(
1869 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1870 if ctx.Host() {
1871 return
1872 }
1873
Jiyong Park92315372021-04-02 08:45:46 +09001874 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 if stubs {
1876 return
1877 }
Jiyong Park92315372021-04-02 08:45:46 +09001878 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001879
1880 if myLinkType.rank() < depLinkType.rank() {
1881 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1882 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1883 "property of the source or target module so that target module is built "+
1884 "with the same or smaller API set when compared to the source.",
1885 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1886 }
1887}
1888
1889func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1890 var deps deps
1891
1892 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001893 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001894 if sdkDep.invalidVersion {
1895 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1896 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1897 } else if sdkDep.useFiles {
1898 // sdkDep.jar is actually equivalent to turbine header.jar.
1899 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001900 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001901 deps.aidlPreprocess = sdkDep.aidl
1902 } else {
1903 deps.aidlPreprocess = sdkDep.aidl
1904 }
1905 }
1906
Jiyong Park92315372021-04-02 08:45:46 +09001907 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001908
1909 ctx.VisitDirectDeps(func(module android.Module) {
1910 otherName := ctx.OtherModuleName(module)
1911 tag := ctx.OtherModuleDependencyTag(module)
1912
1913 if IsJniDepTag(tag) {
1914 // Handled by AndroidApp.collectAppDeps
1915 return
1916 }
1917 if tag == certificateTag {
1918 // Handled by AndroidApp.collectAppDeps
1919 return
1920 }
1921
1922 if dep, ok := module.(SdkLibraryDependency); ok {
1923 switch tag {
1924 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001925 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1926 deps.classpath = append(deps.classpath, depHeaderJars...)
1927 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001928 case staticLibTag:
1929 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1930 }
1931 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1932 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1933 if sdkLinkType != javaPlatform &&
1934 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1935 // dep is a sysprop implementation library, but this module is not linking against
1936 // the platform, so it gets the sysprop public stubs library instead. Replace
1937 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1938 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1939 dep = syspropDep.JavaInfo
1940 }
1941 switch tag {
1942 case bootClasspathTag:
1943 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1944 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001945 if _, ok := module.(*Plugin); ok {
1946 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1947 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001948 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001949 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001950 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1951 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1952 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1953 case java9LibTag:
1954 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1955 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001956 if _, ok := module.(*Plugin); ok {
1957 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1958 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001959 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1960 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1961 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1962 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1963 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1964 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1965 // Turbine doesn't run annotation processors, so any module that uses an
1966 // annotation processor that generates API is incompatible with the turbine
1967 // optimization.
1968 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1969 case pluginTag:
1970 if plugin, ok := module.(*Plugin); ok {
1971 if plugin.pluginProperties.Processor_class != nil {
1972 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1973 } else {
1974 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1975 }
1976 // Turbine doesn't run annotation processors, so any module that uses an
1977 // annotation processor that generates API is incompatible with the turbine
1978 // optimization.
1979 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1980 } else {
1981 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1982 }
1983 case errorpronePluginTag:
1984 if _, ok := module.(*Plugin); ok {
1985 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1986 } else {
1987 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1988 }
1989 case exportedPluginTag:
1990 if plugin, ok := module.(*Plugin); ok {
1991 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1992 if plugin.pluginProperties.Processor_class != nil {
1993 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1994 }
1995 // Turbine doesn't run annotation processors, so any module that uses an
1996 // annotation processor that generates API is incompatible with the turbine
1997 // optimization.
1998 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1999 } else {
2000 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2001 }
2002 case kotlinStdlibTag:
2003 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2004 case kotlinAnnotationsTag:
2005 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002006 case kotlinPluginTag:
2007 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002008 case syspropPublicStubDepTag:
2009 // This is a sysprop implementation library, forward the JavaInfoProvider from
2010 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2011 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2012 JavaInfo: dep,
2013 })
2014 }
2015 } else if dep, ok := module.(android.SourceFileProducer); ok {
2016 switch tag {
2017 case libTag:
2018 checkProducesJars(ctx, dep)
2019 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002020 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002021 case staticLibTag:
2022 checkProducesJars(ctx, dep)
2023 deps.classpath = append(deps.classpath, dep.Srcs()...)
2024 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2025 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2026 }
2027 } else {
2028 switch tag {
2029 case bootClasspathTag:
2030 // If a system modules dependency has been added to the bootclasspath
2031 // then add its libs to the bootclasspath.
2032 sm := module.(SystemModulesProvider)
2033 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2034
2035 case systemModulesTag:
2036 if deps.systemModules != nil {
2037 panic("Found two system module dependencies")
2038 }
2039 sm := module.(SystemModulesProvider)
2040 outputDir, outputDeps := sm.OutputDirAndDeps()
2041 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002042
2043 case instrumentationForTag:
2044 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 -07002045 }
2046 }
2047
2048 addCLCFromDep(ctx, module, j.classLoaderContexts)
2049 })
2050
2051 return deps
2052}
2053
2054func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2055 deps.processorPath = append(deps.processorPath, pluginJars...)
2056 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2057}
2058
2059// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2060// this interface.
2061type ProvidesUsesLib interface {
2062 ProvidesUsesLib() *string
2063}
2064
2065func (j *Module) ProvidesUsesLib() *string {
2066 return j.usesLibraryProperties.Provides_uses_lib
2067}
satayev1c564cc2021-05-25 19:50:30 +01002068
2069type ModuleWithStem interface {
2070 Stem() string
2071}
2072
2073var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002074
2075func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2076 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002077 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002078 if lib, ok := ctx.Module().(*Library); ok {
2079 javaLibraryBp2Build(ctx, lib)
2080 }
2081 case "java_binary_host":
2082 if binary, ok := ctx.Module().(*Binary); ok {
2083 javaBinaryHostBp2Build(ctx, binary)
2084 }
2085 }
Wei Libafb6d62021-12-10 03:14:59 -08002086}