blob: 2da7cbd412e6d83f52bf99ce8fd0d7acdb964db0 [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"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000270
271 HiddenAPIPackageProperties
272 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700273}
274
Jooyung Han01d80d82022-01-08 12:16:32 +0900275// Device properties that can be overridden by overriding module (e.g. override_android_app)
276type OverridableDeviceProperties struct {
277 // set the name of the output. If not set, `name` is used.
278 // To override a module with this property set, overriding module might need to set this as well.
279 // Otherwise, both the overridden and the overriding modules will have the same output name, which
280 // can cause the duplicate output error.
281 Stem *string
282}
283
Jaewoong Jung26342642021-03-17 15:56:23 -0700284// Functionality common to Module and Import
285//
286// It is embedded in Module so its functionality can be used by methods in Module
287// but it is currently only initialized by Import and Library.
288type embeddableInModuleAndImport struct {
289
290 // Functionality related to this being used as a component of a java_sdk_library.
291 EmbeddableSdkLibraryComponent
292}
293
Paul Duffin71b33cc2021-06-23 11:39:47 +0100294func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
295 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700296}
297
298// Module/Import's DepIsInSameApex(...) delegates to this method.
299//
300// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
301// the one provided by ApexModuleBase.
302func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
303 // dependencies other than the static linkage are all considered crossing APEX boundary
304 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
305 return true
306 }
307 return false
308}
309
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100310// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
311// or an invalid path describing the reason it is invalid.
312//
313// It is unset if a dex jar isn't applicable, i.e. no build rule has been
314// requested to create one.
315//
316// If a dex jar has been requested to be built then it is set, and it may be
317// either a valid android.Path, or invalid with a reason message. The latter
318// happens if the source that should produce the dex file isn't able to.
319//
320// E.g. it is invalid with a reason message if there is a prebuilt APEX that
321// could produce the dex jar through a deapexer module, but the APEX isn't
322// installable so doing so wouldn't be safe.
323type OptionalDexJarPath struct {
324 isSet bool
325 path android.OptionalPath
326}
327
328// IsSet returns true if a path has been set, either invalid or valid.
329func (o OptionalDexJarPath) IsSet() bool {
330 return o.isSet
331}
332
333// Valid returns true if there is a path that is valid.
334func (o OptionalDexJarPath) Valid() bool {
335 return o.isSet && o.path.Valid()
336}
337
338// Path returns the valid path, or panics if it's either not set or is invalid.
339func (o OptionalDexJarPath) Path() android.Path {
340 if !o.isSet {
341 panic("path isn't set")
342 }
343 return o.path.Path()
344}
345
346// PathOrNil returns the path if it's set and valid, or else nil.
347func (o OptionalDexJarPath) PathOrNil() android.Path {
348 if o.Valid() {
349 return o.Path()
350 }
351 return nil
352}
353
354// InvalidReason returns the reason for an invalid path, which is never "". It
355// returns "" for an unset or valid path.
356func (o OptionalDexJarPath) InvalidReason() string {
357 if !o.isSet {
358 return ""
359 }
360 return o.path.InvalidReason()
361}
362
363func (o OptionalDexJarPath) String() string {
364 if !o.isSet {
365 return "<unset>"
366 }
367 return o.path.String()
368}
369
370// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
371func makeUnsetDexJarPath() OptionalDexJarPath {
372 return OptionalDexJarPath{isSet: false}
373}
374
375// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
376// the given OptionalPath, which may be valid or invalid.
377func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
378 return OptionalDexJarPath{isSet: true, path: path}
379}
380
381// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
382// valid given path. It returns an unset OptionalDexJarPath if the given path is
383// nil.
384func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
385 if path == nil {
386 return makeUnsetDexJarPath()
387 }
388 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
389}
390
Jaewoong Jung26342642021-03-17 15:56:23 -0700391// Module contains the properties and members used by all java module types
392type Module struct {
393 android.ModuleBase
394 android.DefaultableModuleBase
395 android.ApexModuleBase
396 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800397 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700398
399 // Functionality common to Module and Import.
400 embeddableInModuleAndImport
401
402 properties CommonProperties
403 protoProperties android.ProtoProperties
404 deviceProperties DeviceProperties
405
Jooyung Han01d80d82022-01-08 12:16:32 +0900406 overridableDeviceProperties OverridableDeviceProperties
407
Jaewoong Jung26342642021-03-17 15:56:23 -0700408 // jar file containing header classes including static library dependencies, suitable for
409 // inserting into the bootclasspath/classpath of another compile
410 headerJarFile android.Path
411
412 // jar file containing implementation classes including static library dependencies but no
413 // resources
414 implementationJarFile android.Path
415
416 // jar file containing only resources including from static library dependencies
417 resourceJar android.Path
418
419 // args and dependencies to package source files into a srcjar
420 srcJarArgs []string
421 srcJarDeps android.Paths
422
423 // jar file containing implementation classes and resources including static library
424 // dependencies
425 implementationAndResourcesJar android.Path
426
427 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100428 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700429
430 // output file containing uninstrumented classes that will be instrumented by jacoco
431 jacocoReportClassesFile android.Path
432
433 // output file of the module, which may be a classes jar or a dex jar
434 outputFile android.Path
435 extraOutputFiles android.Paths
436
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100437 exportAidlIncludeDirs android.Paths
438 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700439
440 logtagsSrcs android.Paths
441
442 // installed file for binary dependency
443 installFile android.Path
444
Colin Cross3108ce12021-11-10 14:38:50 -0800445 // installed file for hostdex copy
446 hostdexInstallFile android.InstallPath
447
Jaewoong Jung26342642021-03-17 15:56:23 -0700448 // list of .java files and srcjars that was passed to javac
449 compiledJavaSrcs android.Paths
450 compiledSrcJars android.Paths
451
452 // manifest file to use instead of properties.Manifest
453 overrideManifest android.OptionalPath
454
Jaewoong Jung26342642021-03-17 15:56:23 -0700455 // list of plugins that this java module is exporting
456 exportedPluginJars android.Paths
457
458 // list of plugins that this java module is exporting
459 exportedPluginClasses []string
460
461 // if true, the exported plugins generate API and require disabling turbine.
462 exportedDisableTurbine bool
463
464 // list of source files, collected from srcFiles with unique java and all kt files,
465 // will be used by android.IDEInfo struct
466 expandIDEInfoCompiledSrcs []string
467
468 // expanded Jarjar_rules
469 expandJarjarRules android.Path
470
Jaewoong Jung26342642021-03-17 15:56:23 -0700471 // Extra files generated by the module type to be added as java resources.
472 extraResources android.Paths
473
474 hiddenAPI
475 dexer
476 dexpreopter
477 usesLibrary
478 linter
479
480 // list of the xref extraction files
481 kytheFiles android.Paths
482
483 // Collect the module directory for IDE info in java/jdeps.go.
484 modulePaths []string
485
486 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900487
488 sdkVersion android.SdkSpec
489 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000490 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400491
492 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700493}
494
Jiyong Park92315372021-04-02 08:45:46 +0900495func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
496 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900497 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700498 return nil
499 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900500 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000501 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700502 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
503 } else {
504 // Treat stable core platform as stable.
505 return nil
506 }
507 } else {
508 return fmt.Errorf("non stable SDK %v", sdkVersion)
509 }
510}
511
512// checkSdkVersions enforces restrictions around SDK dependencies.
513func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
514 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900515 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900516 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700517 ctx.PropertyErrorf("sdk_version",
518 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
519 }
520 }
521 }
522
523 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
524 // See rank() for details.
525 ctx.VisitDirectDeps(func(module android.Module) {
526 tag := ctx.OtherModuleDependencyTag(module)
527 switch module.(type) {
528 // TODO(satayev): cover other types as well, e.g. imports
529 case *Library, *AndroidLibrary:
530 switch tag {
531 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
532 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
533 }
534 }
535 })
536}
537
538func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900539 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700540 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900541 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700542 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000543 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 -0700544 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000545 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 -0700546 }
547
548 }
549}
550
551func (j *Module) addHostProperties() {
552 j.AddProperties(
553 &j.properties,
554 &j.protoProperties,
555 &j.usesLibraryProperties,
556 )
557}
558
559func (j *Module) addHostAndDeviceProperties() {
560 j.addHostProperties()
561 j.AddProperties(
562 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900563 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700564 &j.dexer.dexProperties,
565 &j.dexpreoptProperties,
566 &j.linter.properties,
567 )
568}
569
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000570// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
571// makes it available through the hiddenAPIPropertyInfoProvider.
572func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
573 hiddenAPIInfo := newHiddenAPIPropertyInfo()
574
575 // Populate with flag file paths from the properties.
576 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
577
578 // Populate with package rules from the properties.
579 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
580
581 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
582}
583
Jaewoong Jung26342642021-03-17 15:56:23 -0700584func (j *Module) OutputFiles(tag string) (android.Paths, error) {
585 switch tag {
586 case "":
587 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
588 case android.DefaultDistTag:
589 return android.Paths{j.outputFile}, nil
590 case ".jar":
591 return android.Paths{j.implementationAndResourcesJar}, nil
592 case ".proguard_map":
593 if j.dexer.proguardDictionary.Valid() {
594 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
595 }
596 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
597 default:
598 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
599 }
600}
601
602var _ android.OutputFileProducer = (*Module)(nil)
603
604func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
605 initJavaModule(module, hod, false)
606}
607
608func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
609 initJavaModule(module, hod, true)
610}
611
612func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
613 multilib := android.MultilibCommon
614 if multiTargets {
615 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
616 } else {
617 android.InitAndroidArchModule(module, hod, multilib)
618 }
619 android.InitDefaultableModule(module)
620}
621
622func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
623 return j.properties.Instrument &&
624 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
625 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
626}
627
628func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000629 return j.properties.Supports_static_instrumentation &&
630 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700631 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
632 ctx.Config().UnbundledBuild())
633}
634
635func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
636 // Force enable the instrumentation for java code that is built for APEXes ...
637 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
638 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
639 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
640 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
641 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
642 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
643 return true
644 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
645 return true
646 }
647 }
648 return false
649}
650
Jiyong Park92315372021-04-02 08:45:46 +0900651func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
652 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700653}
654
Jiyong Parkf1691d22021-03-29 20:11:58 +0900655func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700656 return proptools.String(j.deviceProperties.System_modules)
657}
658
Jiyong Park92315372021-04-02 08:45:46 +0900659func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700660 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900661 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700662 }
Jiyong Park92315372021-04-02 08:45:46 +0900663 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700664}
665
satayev0a420e72021-11-29 17:25:52 +0000666func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
667 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
668 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
669 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
670 return android.SdkSpecFrom(ctx, maxSdkVersion)
671}
672
William Loh5a082f92022-05-17 20:21:50 +0000673func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
674 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
675 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
676}
677
Jiyong Parkf1691d22021-03-29 20:11:58 +0900678func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900679 return j.minSdkVersion.Raw
680}
681
682func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
683 if j.deviceProperties.Target_sdk_version != nil {
684 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
685 }
686 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700687}
688
689func (j *Module) AvailableFor(what string) bool {
690 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
691 // Exception: for hostdex: true libraries, the platform variant is created
692 // even if it's not marked as available to platform. In that case, the platform
693 // variant is used only for the hostdex and not installed to the device.
694 return true
695 }
696 return j.ApexModuleBase.AvailableFor(what)
697}
698
699func (j *Module) deps(ctx android.BottomUpMutatorContext) {
700 if ctx.Device() {
701 j.linter.deps(ctx)
702
Jiyong Parkf1691d22021-03-29 20:11:58 +0900703 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700704
705 if j.deviceProperties.SyspropPublicStub != "" {
706 // This is a sysprop implementation library that has a corresponding sysprop public
707 // stubs library, and a dependency on it so that dependencies on the implementation can
708 // be forwarded to the public stubs library when necessary.
709 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
710 }
711 }
712
713 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
714 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
715
716 // Add dependency on libraries that provide additional hidden api annotations.
717 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
718
719 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
720 // Require java_sdk_library at inter-partition java dependency to ensure stable
721 // interface between partitions. If inter-partition java_library dependency is detected,
722 // raise build error because java_library doesn't have a stable interface.
723 //
724 // Inputs:
725 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
726 // if true, enable enforcement
727 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
728 // exception list of java_library names to allow inter-partition dependency
729 for idx := range j.properties.Libs {
730 if libDeps[idx] == nil {
731 continue
732 }
733
734 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
735 // java_sdk_library is always allowed at inter-partition dependency.
736 // So, skip check.
737 if _, ok := javaDep.(*SdkLibrary); ok {
738 continue
739 }
740
741 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
742 }
743 }
744 }
745
746 // For library dependencies that are component libraries (like stubs), add the implementation
747 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
748 for _, dep := range libDeps {
749 if dep != nil {
750 if component, ok := dep.(SdkLibraryComponentDependency); ok {
751 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100752 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100753 tag := usesLibReqTag
754 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
755 tag = usesLibOptTag
756 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100757 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700758 }
759 }
760 }
761 }
762
763 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
764 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
765 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
766
767 android.ProtoDeps(ctx, &j.protoProperties)
768 if j.hasSrcExt(".proto") {
769 protoDeps(ctx, &j.protoProperties)
770 }
771
772 if j.hasSrcExt(".kt") {
773 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
774 // Kotlin files
775 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
776 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700777 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700778 }
779
780 // Framework libraries need special handling in static coverage builds: they should not have
781 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
782 // the same jacoco classes coming from different bootclasspath jars.
783 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
784 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
785 j.properties.Instrument = true
786 }
787 } else if j.shouldInstrumentStatic(ctx) {
788 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
789 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700790
791 if j.useCompose() {
792 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
793 "androidx.compose.compiler_compiler-hosted")
794 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700795}
796
797func hasSrcExt(srcs []string, ext string) bool {
798 for _, src := range srcs {
799 if filepath.Ext(src) == ext {
800 return true
801 }
802 }
803
804 return false
805}
806
807func (j *Module) hasSrcExt(ext string) bool {
808 return hasSrcExt(j.properties.Srcs, ext)
809}
810
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100811func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
812 var flags string
813
814 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
815 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
816 flags = "-Wmissing-permission-annotation -Werror"
817 }
818 }
819 return flags
820}
821
Jaewoong Jung26342642021-03-17 15:56:23 -0700822func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
823 aidlIncludeDirs android.Paths) (string, android.Paths) {
824
825 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
826 aidlIncludes = append(aidlIncludes,
827 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
828 aidlIncludes = append(aidlIncludes,
829 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
830
831 var flags []string
832 var deps android.Paths
833
834 flags = append(flags, j.deviceProperties.Aidl.Flags...)
835
836 if aidlPreprocess.Valid() {
837 flags = append(flags, "-p"+aidlPreprocess.String())
838 deps = append(deps, aidlPreprocess.Path())
839 } else if len(aidlIncludeDirs) > 0 {
840 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
841 }
842
843 if len(j.exportAidlIncludeDirs) > 0 {
844 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
845 }
846
847 if len(aidlIncludes) > 0 {
848 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
849 }
850
851 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
852 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
853 flags = append(flags, "-I"+src.String())
854 }
855
856 if Bool(j.deviceProperties.Aidl.Generate_traces) {
857 flags = append(flags, "-t")
858 }
859
860 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
861 flags = append(flags, "--transaction_names")
862 }
863
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100864 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
865 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
866 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
867 }
868
Jooyung Han07f70c02021-11-06 07:08:45 +0900869 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
870 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
871
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 return strings.Join(flags, " "), deps
873}
874
875func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
876
877 var flags javaBuilderFlags
878
879 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900880 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
Cole Faust2b1536e2021-06-18 12:25:54 -0700882 epEnabled := j.properties.Errorprone.Enabled
883 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
885 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
886 }
887
888 errorProneFlags := []string{
889 "-Xplugin:ErrorProne",
890 "${config.ErrorProneChecks}",
891 }
892 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
893
Colin Cross8bf6cad2022-02-28 13:07:03 -0800894 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700895 "'" + strings.Join(errorProneFlags, " ") + "'"
896 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
897 }
898
899 // classpath
900 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
901 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700902 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700903 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
904 flags.processorPath = append(flags.processorPath, deps.processorPath...)
905 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
906
907 flags.processors = append(flags.processors, deps.processorClasses...)
908 flags.processors = android.FirstUniqueStrings(flags.processors)
909
910 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900911 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 // Give host-side tools a version of OpenJDK's standard libraries
913 // close to what they're targeting. As of Dec 2017, AOSP is only
914 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
915 //
916 // When building with OpenJDK 8, the following should have no
917 // effect since those jars would be available by default.
918 //
919 // When building with OpenJDK 9 but targeting a version < 1.8,
920 // putting them on the bootclasspath means that:
921 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
922 // b) references to existing APIs are not reinterpreted in an
923 // OpenJDK 9-specific way, eg. calls to subclasses of
924 // java.nio.Buffer as in http://b/70862583
925 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
926 flags.bootClasspath = append(flags.bootClasspath,
927 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
928 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
929 if Bool(j.properties.Use_tools_jar) {
930 flags.bootClasspath = append(flags.bootClasspath,
931 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
932 }
933 }
934
935 // systemModules
936 flags.systemModules = deps.systemModules
937
938 // aidl flags.
939 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
940
941 return flags
942}
943
944func (j *Module) collectJavacFlags(
945 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
946 // javac flags.
947 javacFlags := j.properties.Javacflags
948
949 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
950 // For non-host binaries, override the -g flag passed globally to remove
951 // local variable debug info to reduce disk and memory usage.
952 javacFlags = append(javacFlags, "-g:source,lines")
953 }
954 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
955
956 if flags.javaVersion.usesJavaModules() {
957 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
958
959 if j.properties.Patch_module != nil {
960 // Manually specify build directory in case it is not under the repo root.
961 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
962 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200963 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700964
965 // b/150878007
966 //
967 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
968 // execution root for --patch-module. If this javac command line is
969 // invoked within Bazel's execution root working directory, the top
970 // level directories (e.g. libcore/, tools/, frameworks/) are all
971 // symlinks. JDK9 javac does not traverse into symlinks, which causes
972 // --patch-module to fail source file lookups when invoked in the
973 // execution root.
974 //
975 // Short of patching javac or enumerating *all* directories as possible
976 // input dirs, manually add the top level dir of the source files to be
977 // compiled.
978 topLevelDirs := map[string]bool{}
979 for _, srcFilePath := range srcFiles {
980 srcFileParts := strings.Split(srcFilePath.String(), "/")
981 // Ignore source files that are already in the top level directory
982 // as well as generated files in the out directory. The out
983 // directory may be an absolute path, which means srcFileParts[0] is the
984 // empty string, so check that as well. Note that "out" in Bazel's execution
985 // root is *not* a symlink, which doesn't cause problems for --patch-modules
986 // anyway, so it's fine to not apply this workaround for generated
987 // source files.
988 if len(srcFileParts) > 1 &&
989 srcFileParts[0] != "" &&
990 srcFileParts[0] != "out" {
991 topLevelDirs[srcFileParts[0]] = true
992 }
993 }
994 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
995
996 classPath := flags.classpath.FormJavaClassPath("")
997 if classPath != "" {
998 patchPaths = append(patchPaths, classPath)
999 }
1000 javacFlags = append(
1001 javacFlags,
1002 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1003 }
1004 }
1005
1006 if len(javacFlags) > 0 {
1007 // optimization.
1008 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1009 flags.javacFlags = "$javacFlags"
1010 }
1011
1012 return flags
1013}
1014
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001015func (j *Module) AddJSONData(d *map[string]interface{}) {
1016 (&j.ModuleBase).AddJSONData(d)
1017 (*d)["Java"] = map[string]interface{}{
1018 "SourceExtensions": j.sourceExtensions,
1019 }
1020
1021}
1022
Jaewoong Jung26342642021-03-17 15:56:23 -07001023func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1024 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1025
1026 deps := j.collectDeps(ctx)
1027 flags := j.collectBuilderFlags(ctx, deps)
1028
1029 if flags.javaVersion.usesJavaModules() {
1030 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1031 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001032
Jaewoong Jung26342642021-03-17 15:56:23 -07001033 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001034 j.sourceExtensions = []string{}
1035 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1036 if hasSrcExt(srcFiles.Strings(), ext) {
1037 j.sourceExtensions = append(j.sourceExtensions, ext)
1038 }
1039 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001040 if hasSrcExt(srcFiles.Strings(), ".proto") {
1041 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1042 }
1043
1044 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1045 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1046 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1047 }
1048
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001049 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001050 srcFiles = j.genSources(ctx, srcFiles, flags)
1051
1052 // Collect javac flags only after computing the full set of srcFiles to
1053 // ensure that the --patch-module lookup paths are complete.
1054 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1055
1056 srcJars := srcFiles.FilterByExt(".srcjar")
1057 srcJars = append(srcJars, deps.srcJars...)
1058 if aaptSrcJar != nil {
1059 srcJars = append(srcJars, aaptSrcJar)
1060 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001061 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001062
1063 if j.properties.Jarjar_rules != nil {
1064 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1065 }
1066
1067 jarName := ctx.ModuleName() + ".jar"
1068
1069 javaSrcFiles := srcFiles.FilterByExt(".java")
1070 var uniqueSrcFiles android.Paths
1071 set := make(map[string]bool)
1072 for _, v := range javaSrcFiles {
1073 if _, found := set[v.String()]; !found {
1074 set[v.String()] = true
1075 uniqueSrcFiles = append(uniqueSrcFiles, v)
1076 }
1077 }
1078
Colin Crossb5db4012022-03-28 17:12:39 -07001079 // We don't currently run annotation processors in turbine, which means we can't use turbine
1080 // generated header jars when an annotation processor that generates API is enabled. One
1081 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1082 // is used to run all of the annotation processors.
1083 disableTurbine := deps.disableTurbine
1084
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 // Collect .java files for AIDEGen
1086 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1087
1088 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001089 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001090
1091 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001092 // When using kotlin sources turbine is used to generate annotation processor sources,
1093 // including for annotation processors that generate API, so we can use turbine for
1094 // java sources too.
1095 disableTurbine = false
1096
Jaewoong Jung26342642021-03-17 15:56:23 -07001097 // user defined kotlin flags.
1098 kotlincFlags := j.properties.Kotlincflags
1099 CheckKotlincFlags(ctx, kotlincFlags)
1100
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001101 // Workaround for KT-46512
1102 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001103
1104 // If there are kotlin files, compile them first but pass all the kotlin and java files
1105 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1106 // won't emit any classes for them.
1107 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1108 if ctx.Device() {
1109 kotlincFlags = append(kotlincFlags, "-no-jdk")
1110 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001111
1112 for _, plugin := range deps.kotlinPlugins {
1113 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1114 }
1115 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1116
Jaewoong Jung26342642021-03-17 15:56:23 -07001117 if len(kotlincFlags) > 0 {
1118 // optimization.
1119 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1120 flags.kotlincFlags += "$kotlincFlags"
1121 }
1122
1123 var kotlinSrcFiles android.Paths
1124 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1125 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1126
1127 // Collect .kt files for AIDEGen
1128 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1129 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1130
1131 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1132 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1133
1134 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1135 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1136
Isaac Chioua23d9942022-04-06 06:14:38 +00001137 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001139 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1140 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1141 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1142 srcJars = append(srcJars, kaptSrcJar)
1143 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 // Disable annotation processing in javac, it's already been handled by kapt
1145 flags.processorPath = nil
1146 flags.processors = nil
1147 }
1148
1149 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001150 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1151 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 if ctx.Failed() {
1153 return
1154 }
1155
Isaac Chioua23d9942022-04-06 06:14:38 +00001156 // Make javac rule depend on the kotlinc rule
1157 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1158
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001160 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1161
Jaewoong Jung26342642021-03-17 15:56:23 -07001162 // Jar kotlin classes into the final jar after javac
1163 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1164 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001165 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001166 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001167 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001168 } else {
1169 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001170 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001171 }
1172 }
1173
1174 jars := append(android.Paths(nil), kotlinJars...)
1175
1176 // Store the list of .java files that was passed to javac
1177 j.compiledJavaSrcs = uniqueSrcFiles
1178 j.compiledSrcJars = srcJars
1179
1180 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001181 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001182 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1184 enableSharding = true
1185 // Formerly, there was a check here that prevented annotation processors
1186 // from being used when sharding was enabled, as some annotation processors
1187 // do not function correctly in sharded environments. It was removed to
1188 // allow for the use of annotation processors that do function correctly
1189 // with sharding enabled. See: b/77284273.
1190 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001191 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001192 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 if ctx.Failed() {
1194 return
1195 }
1196 }
1197 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
Cole Faust2d516df2022-08-24 11:22:52 -07001198 hasErrorproneableFiles := false
1199 for _, ext := range j.sourceExtensions {
1200 if ext != ".proto" && ext != ".aidl" {
1201 // Skip running errorprone on pure proto or pure aidl modules. Some modules take a long time to
1202 // compile, and it's not useful to have warnings on these generated sources.
1203 hasErrorproneableFiles = true
1204 break
1205 }
1206 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001207 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001208 if Bool(j.properties.Errorprone.Enabled) {
1209 // If error-prone is enabled, enable errorprone flags on the regular
1210 // build.
1211 flags = enableErrorproneFlags(flags)
Cole Faust2d516df2022-08-24 11:22:52 -07001212 } else if hasErrorproneableFiles && ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001213 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1214 // a new jar file just for compiling with the errorprone compiler to.
1215 // This is because we don't want to cause the java files to get completely
1216 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1217 // We also don't want to run this if errorprone is enabled by default for
1218 // this module, or else we could have duplicated errorprone messages.
1219 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001221
1222 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1223 "errorprone", "errorprone")
1224
Jaewoong Jung26342642021-03-17 15:56:23 -07001225 extraJarDeps = append(extraJarDeps, errorprone)
1226 }
1227
1228 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001229 if headerJarFileWithoutDepsOrJarjar != nil {
1230 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1231 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001232 shardSize := int(*(j.properties.Javac_shard_size))
1233 var shardSrcs []android.Paths
1234 if len(uniqueSrcFiles) > 0 {
1235 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1236 for idx, shardSrc := range shardSrcs {
1237 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1238 nil, flags, extraJarDeps)
1239 jars = append(jars, classes)
1240 }
1241 }
1242 if len(srcJars) > 0 {
1243 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1244 nil, srcJars, flags, extraJarDeps)
1245 jars = append(jars, classes)
1246 }
1247 } else {
1248 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1249 jars = append(jars, classes)
1250 }
1251 if ctx.Failed() {
1252 return
1253 }
1254 }
1255
1256 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1257
1258 var includeSrcJar android.WritablePath
1259 if Bool(j.properties.Include_srcs) {
1260 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1261 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1262 }
1263
1264 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1265 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1266 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1267 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1268
1269 var resArgs []string
1270 var resDeps android.Paths
1271
1272 resArgs = append(resArgs, dirArgs...)
1273 resDeps = append(resDeps, dirDeps...)
1274
1275 resArgs = append(resArgs, fileArgs...)
1276 resDeps = append(resDeps, fileDeps...)
1277
1278 resArgs = append(resArgs, extraArgs...)
1279 resDeps = append(resDeps, extraDeps...)
1280
1281 if len(resArgs) > 0 {
1282 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1283 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1284 j.resourceJar = resourceJar
1285 if ctx.Failed() {
1286 return
1287 }
1288 }
1289
1290 var resourceJars android.Paths
1291 if j.resourceJar != nil {
1292 resourceJars = append(resourceJars, j.resourceJar)
1293 }
1294 if Bool(j.properties.Include_srcs) {
1295 resourceJars = append(resourceJars, includeSrcJar)
1296 }
1297 resourceJars = append(resourceJars, deps.staticResourceJars...)
1298
1299 if len(resourceJars) > 1 {
1300 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1301 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1302 false, nil, nil)
1303 j.resourceJar = combinedJar
1304 } else if len(resourceJars) == 1 {
1305 j.resourceJar = resourceJars[0]
1306 }
1307
1308 if len(deps.staticJars) > 0 {
1309 jars = append(jars, deps.staticJars...)
1310 }
1311
1312 manifest := j.overrideManifest
1313 if !manifest.Valid() && j.properties.Manifest != nil {
1314 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1315 }
1316
1317 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1318 if len(services) > 0 {
1319 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1320 var zipargs []string
1321 for _, file := range services {
1322 serviceFile := file.String()
1323 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1324 }
1325 rule := zip
1326 args := map[string]string{
1327 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1328 }
1329 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1330 rule = zipRE
1331 args["implicits"] = strings.Join(services.Strings(), ",")
1332 }
1333 ctx.Build(pctx, android.BuildParams{
1334 Rule: rule,
1335 Output: servicesJar,
1336 Implicits: services,
1337 Args: args,
1338 })
1339 jars = append(jars, servicesJar)
1340 }
1341
1342 // Combine the classes built from sources, any manifests, and any static libraries into
1343 // classes.jar. If there is only one input jar this step will be skipped.
1344 var outputFile android.OutputPath
1345
1346 if len(jars) == 1 && !manifest.Valid() {
1347 // Optimization: skip the combine step as there is nothing to do
1348 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1349 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1350 // any if len(jars) == 1.
1351
1352 // Transform the single path to the jar into an OutputPath as that is required by the following
1353 // code.
1354 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1355 // The path contains an embedded OutputPath so reuse that.
1356 outputFile = moduleOutPath.OutputPath
1357 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1358 // The path is an OutputPath so reuse it directly.
1359 outputFile = outputPath
1360 } else {
1361 // The file is not in the out directory so create an OutputPath into which it can be copied
1362 // and which the following code can use to refer to it.
1363 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1364 ctx.Build(pctx, android.BuildParams{
1365 Rule: android.Cp,
1366 Input: jars[0],
1367 Output: combinedJar,
1368 })
1369 outputFile = combinedJar.OutputPath
1370 }
1371 } else {
1372 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1373 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1374 false, nil, nil)
1375 outputFile = combinedJar.OutputPath
1376 }
1377
1378 // jarjar implementation jar if necessary
1379 if j.expandJarjarRules != nil {
1380 // Transform classes.jar into classes-jarjar.jar
1381 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1382 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1383 outputFile = jarjarFile
1384
1385 // jarjar resource jar if necessary
1386 if j.resourceJar != nil {
1387 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1388 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1389 j.resourceJar = resourceJarJarFile
1390 }
1391
1392 if ctx.Failed() {
1393 return
1394 }
1395 }
1396
1397 // Check package restrictions if necessary.
1398 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001399 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001400 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001401
1402 // Create a rule to copy the output jar to another path and add a validate dependency that
1403 // will check that the jar only contains the permitted packages. The new location will become
1404 // the output file of this module.
1405 inputFile := outputFile
1406 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1407 ctx.Build(pctx, android.BuildParams{
1408 Rule: android.Cp,
1409 Input: inputFile,
1410 Output: outputFile,
1411 // Make sure that any dependency on the output file will cause ninja to run the package check
1412 // rule.
1413 Validation: pkgckFile,
1414 })
1415
1416 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001417 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001418
1419 if ctx.Failed() {
1420 return
1421 }
1422 }
1423
1424 j.implementationJarFile = outputFile
1425 if j.headerJarFile == nil {
1426 j.headerJarFile = j.implementationJarFile
1427 }
1428
1429 if j.shouldInstrumentInApex(ctx) {
1430 j.properties.Instrument = true
1431 }
1432
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001433 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1434 specs := j.jacocoModuleToZipCommand(ctx)
1435 if ctx.Failed() {
1436 return
1437 }
1438
Jaewoong Jung26342642021-03-17 15:56:23 -07001439 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001440 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001441 }
1442
1443 // merge implementation jar with resources if necessary
1444 implementationAndResourcesJar := outputFile
1445 if j.resourceJar != nil {
1446 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1447 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1448 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1449 false, nil, nil)
1450 implementationAndResourcesJar = combinedJar
1451 }
1452
1453 j.implementationAndResourcesJar = implementationAndResourcesJar
1454
1455 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001456 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001457 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1458 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001459 if compileDex == nil {
1460 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001461 }
1462 if j.deviceProperties.Hostdex == nil {
1463 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1464 }
1465 }
1466
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001467 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001468 if j.hasCode(ctx) {
1469 if j.shouldInstrumentStatic(ctx) {
1470 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1471 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1472 }
1473 // Dex compilation
1474 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001475 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 if ctx.Failed() {
1477 return
1478 }
1479
Jaewoong Jung26342642021-03-17 15:56:23 -07001480 // merge dex jar with resources if necessary
1481 if j.resourceJar != nil {
1482 jars := android.Paths{dexOutputFile, j.resourceJar}
1483 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1484 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1485 false, nil, nil)
1486 if *j.dexProperties.Uncompress_dex {
1487 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1488 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1489 dexOutputFile = combinedAlignedJar
1490 } else {
1491 dexOutputFile = combinedJar
1492 }
1493 }
1494
Paul Duffin4de94502021-05-16 05:21:16 +01001495 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001496
1497 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001498
1499 // Encode hidden API flags in dex file, if needed.
1500 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1501
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001502 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001503
1504 // Dexpreopting
1505 j.dexpreopt(ctx, dexOutputFile)
1506
1507 outputFile = dexOutputFile
1508 } else {
1509 // There is no code to compile into a dex jar, make sure the resources are propagated
1510 // to the APK if this is an app.
1511 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001512 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 }
1514
1515 if ctx.Failed() {
1516 return
1517 }
1518 } else {
1519 outputFile = implementationAndResourcesJar
1520 }
1521
1522 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001523 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001524 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001525 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001526 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001527 // When running metalava, we pass --version-codename. When that value
1528 // is not REL, metalava will add 1 to the --current-version argument.
1529 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1530 // branch) and the codename is REL, except potentially on the most
1531 // recent non-master branch. On that branch, it goes through two other
1532 // phases before it gets to the phase previously described:
1533 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1534 // is not rel. This happens for most of the internal branch's life
1535 // while the branch has been cut but is still under active development.
1536 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1537 // REL. This happens briefly during the release process. During this
1538 // state the code to add --current-version is commented out, and then
1539 // that commenting out is reverted after the codename is set to REL.
1540 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1541 // prior version and the codename is always non-REL.
1542 //
1543 // We need to add one here to match metalava adding 1. Technically
1544 // this means that in the state described in the second bullet point
1545 // above, this number is 1 higher than it should be.
1546 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001547 }
1548 }
1549
1550 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001551 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1552 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001553 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1554 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001555 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1556 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1557 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001558 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001559 j.linter.javaLanguageLevel = flags.javaVersion.String()
1560 j.linter.kotlinLanguageLevel = "1.3"
1561 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1562 j.linter.buildModuleReportZip = true
1563 }
1564 j.linter.lint(ctx)
1565 }
1566
1567 ctx.CheckbuildFile(outputFile)
1568
1569 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1570 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1571 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1572 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1573 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1574 AidlIncludeDirs: j.exportAidlIncludeDirs,
1575 SrcJarArgs: j.srcJarArgs,
1576 SrcJarDeps: j.srcJarDeps,
1577 ExportedPlugins: j.exportedPluginJars,
1578 ExportedPluginClasses: j.exportedPluginClasses,
1579 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1580 JacocoReportClassesFile: j.jacocoReportClassesFile,
1581 })
1582
1583 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1584 j.outputFile = outputFile.WithoutRel()
1585}
1586
Colin Crossa1ff7c62021-09-17 14:11:52 -07001587func (j *Module) useCompose() bool {
1588 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1589}
1590
Cole Faust75fffb12021-06-13 15:23:16 -07001591// Returns a copy of the supplied flags, but with all the errorprone-related
1592// fields copied to the regular build's fields.
1593func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1594 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1595
1596 if len(flags.errorProneExtraJavacFlags) > 0 {
1597 if len(flags.javacFlags) > 0 {
1598 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1599 } else {
1600 flags.javacFlags = flags.errorProneExtraJavacFlags
1601 }
1602 }
1603 return flags
1604}
1605
Jaewoong Jung26342642021-03-17 15:56:23 -07001606func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1607 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1608
1609 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1610 if idx >= 0 {
1611 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1612 jarName += strconv.Itoa(idx)
1613 }
1614
1615 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1616 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1617
1618 if ctx.Config().EmitXrefRules() {
1619 extractionFile := android.PathForModuleOut(ctx, kzipName)
1620 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1621 j.kytheFiles = append(j.kytheFiles, extractionFile)
1622 }
1623
1624 return classes
1625}
1626
1627// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1628// since some of these flags may be used internally.
1629func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1630 for _, flag := range flags {
1631 flag = strings.TrimSpace(flag)
1632
1633 if !strings.HasPrefix(flag, "-") {
1634 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1635 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1636 ctx.PropertyErrorf("kotlincflags",
1637 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1638 } else if inList(flag, config.KotlincIllegalFlags) {
1639 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1640 } else if flag == "-include-runtime" {
1641 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1642 } else {
1643 args := strings.Split(flag, " ")
1644 if args[0] == "-kotlin-home" {
1645 ctx.PropertyErrorf("kotlincflags",
1646 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1647 }
1648 }
1649 }
1650}
1651
1652func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1653 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001654 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001655
1656 var jars android.Paths
1657 if len(srcFiles) > 0 || len(srcJars) > 0 {
1658 // Compile java sources into turbine.jar.
1659 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1660 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1661 if ctx.Failed() {
1662 return nil, nil
1663 }
1664 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001665 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001666 }
1667
1668 jars = append(jars, extraJars...)
1669
1670 // Combine any static header libraries into classes-header.jar. If there is only
1671 // one input jar this step will be skipped.
1672 jars = append(jars, deps.staticHeaderJars...)
1673
1674 // we cannot skip the combine step for now if there is only one jar
1675 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1676 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1677 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1678 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001679 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001680
1681 if j.expandJarjarRules != nil {
1682 // Transform classes.jar into classes-jarjar.jar
1683 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001684 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1685 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001686 if ctx.Failed() {
1687 return nil, nil
1688 }
1689 }
1690
Colin Cross3d56ed52021-11-18 22:23:12 -08001691 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001692}
1693
1694func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001695 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001696
1697 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1698 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1699
1700 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1701
1702 j.jacocoReportClassesFile = jacocoReportClassesFile
1703
1704 return instrumentedJar
1705}
1706
1707func (j *Module) HeaderJars() android.Paths {
1708 if j.headerJarFile == nil {
1709 return nil
1710 }
1711 return android.Paths{j.headerJarFile}
1712}
1713
1714func (j *Module) ImplementationJars() android.Paths {
1715 if j.implementationJarFile == nil {
1716 return nil
1717 }
1718 return android.Paths{j.implementationJarFile}
1719}
1720
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001721func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001722 return j.dexJarFile
1723}
1724
1725func (j *Module) DexJarInstallPath() android.Path {
1726 return j.installFile
1727}
1728
1729func (j *Module) ImplementationAndResourcesJars() android.Paths {
1730 if j.implementationAndResourcesJar == nil {
1731 return nil
1732 }
1733 return android.Paths{j.implementationAndResourcesJar}
1734}
1735
1736func (j *Module) AidlIncludeDirs() android.Paths {
1737 // exportAidlIncludeDirs is type android.Paths already
1738 return j.exportAidlIncludeDirs
1739}
1740
1741func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1742 return j.classLoaderContexts
1743}
1744
1745// Collect information for opening IDE project files in java/jdeps.go.
1746func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1747 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1748 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1749 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1750 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1751 if j.expandJarjarRules != nil {
1752 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1753 }
1754 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001755 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1756 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001757}
1758
1759func (j *Module) CompilerDeps() []string {
1760 jdeps := []string{}
1761 jdeps = append(jdeps, j.properties.Libs...)
1762 jdeps = append(jdeps, j.properties.Static_libs...)
1763 return jdeps
1764}
1765
1766func (j *Module) hasCode(ctx android.ModuleContext) bool {
1767 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1768 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1769}
1770
1771// Implements android.ApexModule
1772func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1773 return j.depIsInSameApex(ctx, dep)
1774}
1775
1776// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001777func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001778 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001779 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001780 return fmt.Errorf("min_sdk_version is not specified")
1781 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001782 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001783 return nil
1784 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001785 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1786 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001787 }
1788 return nil
1789}
1790
1791func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001792 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001793}
1794
Jaewoong Jung26342642021-03-17 15:56:23 -07001795func (j *Module) JacocoReportClassesFile() android.Path {
1796 return j.jacocoReportClassesFile
1797}
1798
1799func (j *Module) IsInstallable() bool {
1800 return Bool(j.properties.Installable)
1801}
1802
1803type sdkLinkType int
1804
1805const (
1806 // TODO(jiyong) rename these for better readability. Make the allowed
1807 // and disallowed link types explicit
1808 // order is important here. See rank()
1809 javaCore sdkLinkType = iota
1810 javaSdk
1811 javaSystem
1812 javaModule
1813 javaSystemServer
1814 javaPlatform
1815)
1816
1817func (lt sdkLinkType) String() string {
1818 switch lt {
1819 case javaCore:
1820 return "core Java API"
1821 case javaSdk:
1822 return "Android API"
1823 case javaSystem:
1824 return "system API"
1825 case javaModule:
1826 return "module API"
1827 case javaSystemServer:
1828 return "system server API"
1829 case javaPlatform:
1830 return "private API"
1831 default:
1832 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1833 }
1834}
1835
1836// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1837// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1838// can't statically depend on modules that use Platform API.
1839func (lt sdkLinkType) rank() int {
1840 return int(lt)
1841}
1842
1843type moduleWithSdkDep interface {
1844 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001845 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001846}
1847
Jiyong Park92315372021-04-02 08:45:46 +09001848func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001849 switch name {
1850 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1851 "stub-annotations", "private-stub-annotations-jar",
1852 "core-lambda-stubs", "core-generated-annotation-stubs":
1853 return javaCore, true
1854 case "android_stubs_current":
1855 return javaSdk, true
1856 case "android_system_stubs_current":
1857 return javaSystem, true
1858 case "android_module_lib_stubs_current":
1859 return javaModule, true
1860 case "android_system_server_stubs_current":
1861 return javaSystemServer, true
1862 case "android_test_stubs_current":
1863 return javaSystem, true
1864 }
1865
1866 if stub, linkType := moduleStubLinkType(name); stub {
1867 return linkType, true
1868 }
1869
Jiyong Park92315372021-04-02 08:45:46 +09001870 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001871 switch ver.Kind {
1872 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001873 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001874 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001875 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001876 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001877 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001878 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001879 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001880 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001881 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001882 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001883 return javaPlatform, false
1884 }
1885
Jiyong Parkf1691d22021-03-29 20:11:58 +09001886 if !ver.Valid() {
1887 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001888 }
1889 return javaSdk, false
1890}
1891
1892// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1893// this module's. See the comment on rank() for details and an example.
1894func (j *Module) checkSdkLinkType(
1895 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1896 if ctx.Host() {
1897 return
1898 }
1899
Jiyong Park92315372021-04-02 08:45:46 +09001900 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001901 if stubs {
1902 return
1903 }
Jiyong Park92315372021-04-02 08:45:46 +09001904 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001905
1906 if myLinkType.rank() < depLinkType.rank() {
1907 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1908 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1909 "property of the source or target module so that target module is built "+
1910 "with the same or smaller API set when compared to the source.",
1911 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1912 }
1913}
1914
1915func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1916 var deps deps
1917
1918 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001919 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001920 if sdkDep.invalidVersion {
1921 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1922 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1923 } else if sdkDep.useFiles {
1924 // sdkDep.jar is actually equivalent to turbine header.jar.
1925 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001926 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001927 deps.aidlPreprocess = sdkDep.aidl
1928 } else {
1929 deps.aidlPreprocess = sdkDep.aidl
1930 }
1931 }
1932
Jiyong Park92315372021-04-02 08:45:46 +09001933 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001934
1935 ctx.VisitDirectDeps(func(module android.Module) {
1936 otherName := ctx.OtherModuleName(module)
1937 tag := ctx.OtherModuleDependencyTag(module)
1938
1939 if IsJniDepTag(tag) {
1940 // Handled by AndroidApp.collectAppDeps
1941 return
1942 }
1943 if tag == certificateTag {
1944 // Handled by AndroidApp.collectAppDeps
1945 return
1946 }
1947
1948 if dep, ok := module.(SdkLibraryDependency); ok {
1949 switch tag {
1950 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001951 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1952 deps.classpath = append(deps.classpath, depHeaderJars...)
1953 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001954 case staticLibTag:
1955 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1956 }
1957 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1958 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1959 if sdkLinkType != javaPlatform &&
1960 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1961 // dep is a sysprop implementation library, but this module is not linking against
1962 // the platform, so it gets the sysprop public stubs library instead. Replace
1963 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1964 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1965 dep = syspropDep.JavaInfo
1966 }
1967 switch tag {
1968 case bootClasspathTag:
1969 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1970 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001971 if _, ok := module.(*Plugin); ok {
1972 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1973 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001974 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001975 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1977 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1978 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1979 case java9LibTag:
1980 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1981 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001982 if _, ok := module.(*Plugin); ok {
1983 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1984 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001985 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1986 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1987 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1988 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1989 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1990 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1991 // Turbine doesn't run annotation processors, so any module that uses an
1992 // annotation processor that generates API is incompatible with the turbine
1993 // optimization.
1994 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1995 case pluginTag:
1996 if plugin, ok := module.(*Plugin); ok {
1997 if plugin.pluginProperties.Processor_class != nil {
1998 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1999 } else {
2000 addPlugins(&deps, dep.ImplementationAndResourcesJars)
2001 }
2002 // Turbine doesn't run annotation processors, so any module that uses an
2003 // annotation processor that generates API is incompatible with the turbine
2004 // optimization.
2005 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2006 } else {
2007 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2008 }
2009 case errorpronePluginTag:
2010 if _, ok := module.(*Plugin); ok {
2011 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2012 } else {
2013 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2014 }
2015 case exportedPluginTag:
2016 if plugin, ok := module.(*Plugin); ok {
2017 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2018 if plugin.pluginProperties.Processor_class != nil {
2019 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2020 }
2021 // Turbine doesn't run annotation processors, so any module that uses an
2022 // annotation processor that generates API is incompatible with the turbine
2023 // optimization.
2024 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2025 } else {
2026 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2027 }
2028 case kotlinStdlibTag:
2029 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2030 case kotlinAnnotationsTag:
2031 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002032 case kotlinPluginTag:
2033 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002034 case syspropPublicStubDepTag:
2035 // This is a sysprop implementation library, forward the JavaInfoProvider from
2036 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2037 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2038 JavaInfo: dep,
2039 })
2040 }
2041 } else if dep, ok := module.(android.SourceFileProducer); ok {
2042 switch tag {
2043 case libTag:
2044 checkProducesJars(ctx, dep)
2045 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002046 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002047 case staticLibTag:
2048 checkProducesJars(ctx, dep)
2049 deps.classpath = append(deps.classpath, dep.Srcs()...)
2050 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2051 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2052 }
2053 } else {
2054 switch tag {
2055 case bootClasspathTag:
2056 // If a system modules dependency has been added to the bootclasspath
2057 // then add its libs to the bootclasspath.
2058 sm := module.(SystemModulesProvider)
2059 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2060
2061 case systemModulesTag:
2062 if deps.systemModules != nil {
2063 panic("Found two system module dependencies")
2064 }
2065 sm := module.(SystemModulesProvider)
2066 outputDir, outputDeps := sm.OutputDirAndDeps()
2067 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002068
2069 case instrumentationForTag:
2070 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 -07002071 }
2072 }
2073
2074 addCLCFromDep(ctx, module, j.classLoaderContexts)
2075 })
2076
2077 return deps
2078}
2079
2080func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2081 deps.processorPath = append(deps.processorPath, pluginJars...)
2082 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2083}
2084
2085// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2086// this interface.
2087type ProvidesUsesLib interface {
2088 ProvidesUsesLib() *string
2089}
2090
2091func (j *Module) ProvidesUsesLib() *string {
2092 return j.usesLibraryProperties.Provides_uses_lib
2093}
satayev1c564cc2021-05-25 19:50:30 +01002094
2095type ModuleWithStem interface {
2096 Stem() string
2097}
2098
2099var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002100
2101func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2102 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002103 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002104 if lib, ok := ctx.Module().(*Library); ok {
2105 javaLibraryBp2Build(ctx, lib)
2106 }
2107 case "java_binary_host":
2108 if binary, ok := ctx.Module().(*Binary); ok {
2109 javaBinaryHostBp2Build(ctx, binary)
2110 }
2111 }
Wei Libafb6d62021-12-10 03:14:59 -08002112}