blob: e38f0b9c450de808293869432db1ab4522f424df [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,
Sam Delmerico2351eac2022-05-24 17:10:02 +0000823 aidlIncludeDirs android.Paths, aidlSrcs android.Paths) (string, android.Paths) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700824
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
Sam Delmerico2351eac2022-05-24 17:10:02 +0000833 var includeDirs android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700834
835 flags = append(flags, j.deviceProperties.Aidl.Flags...)
836
837 if aidlPreprocess.Valid() {
838 flags = append(flags, "-p"+aidlPreprocess.String())
839 deps = append(deps, aidlPreprocess.Path())
840 } else if len(aidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000841 includeDirs = append(includeDirs, aidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700842 }
843
844 if len(j.exportAidlIncludeDirs) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000845 includeDirs = append(includeDirs, j.exportAidlIncludeDirs...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700846 }
847
848 if len(aidlIncludes) > 0 {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000849 includeDirs = append(includeDirs, aidlIncludes...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700850 }
851
Sam Delmerico2351eac2022-05-24 17:10:02 +0000852 includeDirs = append(includeDirs, android.PathForModuleSrc(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -0700853 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
Sam Delmerico2351eac2022-05-24 17:10:02 +0000854 includeDirs = append(includeDirs, src.Path())
Jaewoong Jung26342642021-03-17 15:56:23 -0700855 }
Sam Delmerico2351eac2022-05-24 17:10:02 +0000856 flags = append(flags, android.JoinWithPrefix(includeDirs.Strings(), "-I"))
857 // add flags for dirs containing AIDL srcs that haven't been specified yet
858 flags = append(flags, genAidlIncludeFlags(ctx, aidlSrcs, includeDirs))
Jaewoong Jung26342642021-03-17 15:56:23 -0700859
860 if Bool(j.deviceProperties.Aidl.Generate_traces) {
861 flags = append(flags, "-t")
862 }
863
864 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
865 flags = append(flags, "--transaction_names")
866 }
867
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100868 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
869 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
870 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
871 }
872
Jooyung Han07f70c02021-11-06 07:08:45 +0900873 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
874 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
875
Jaewoong Jung26342642021-03-17 15:56:23 -0700876 return strings.Join(flags, " "), deps
877}
878
879func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
880
881 var flags javaBuilderFlags
882
883 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900884 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700885
Cole Faust2b1536e2021-06-18 12:25:54 -0700886 epEnabled := j.properties.Errorprone.Enabled
887 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700888 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
889 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
890 }
891
892 errorProneFlags := []string{
893 "-Xplugin:ErrorProne",
894 "${config.ErrorProneChecks}",
895 }
896 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
897
Colin Cross8bf6cad2022-02-28 13:07:03 -0800898 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700899 "'" + strings.Join(errorProneFlags, " ") + "'"
900 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
901 }
902
903 // classpath
904 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
905 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700906 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700907 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
908 flags.processorPath = append(flags.processorPath, deps.processorPath...)
909 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
910
911 flags.processors = append(flags.processors, deps.processorClasses...)
912 flags.processors = android.FirstUniqueStrings(flags.processors)
913
914 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900915 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700916 // Give host-side tools a version of OpenJDK's standard libraries
917 // close to what they're targeting. As of Dec 2017, AOSP is only
918 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
919 //
920 // When building with OpenJDK 8, the following should have no
921 // effect since those jars would be available by default.
922 //
923 // When building with OpenJDK 9 but targeting a version < 1.8,
924 // putting them on the bootclasspath means that:
925 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
926 // b) references to existing APIs are not reinterpreted in an
927 // OpenJDK 9-specific way, eg. calls to subclasses of
928 // java.nio.Buffer as in http://b/70862583
929 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
930 flags.bootClasspath = append(flags.bootClasspath,
931 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
932 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
933 if Bool(j.properties.Use_tools_jar) {
934 flags.bootClasspath = append(flags.bootClasspath,
935 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
936 }
937 }
938
939 // systemModules
940 flags.systemModules = deps.systemModules
941
Jaewoong Jung26342642021-03-17 15:56:23 -0700942 return flags
943}
944
945func (j *Module) collectJavacFlags(
946 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
947 // javac flags.
948 javacFlags := j.properties.Javacflags
949
950 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
951 // For non-host binaries, override the -g flag passed globally to remove
952 // local variable debug info to reduce disk and memory usage.
953 javacFlags = append(javacFlags, "-g:source,lines")
954 }
955 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
956
957 if flags.javaVersion.usesJavaModules() {
958 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
959
960 if j.properties.Patch_module != nil {
961 // Manually specify build directory in case it is not under the repo root.
962 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
963 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200964 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700965
966 // b/150878007
967 //
968 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
969 // execution root for --patch-module. If this javac command line is
970 // invoked within Bazel's execution root working directory, the top
971 // level directories (e.g. libcore/, tools/, frameworks/) are all
972 // symlinks. JDK9 javac does not traverse into symlinks, which causes
973 // --patch-module to fail source file lookups when invoked in the
974 // execution root.
975 //
976 // Short of patching javac or enumerating *all* directories as possible
977 // input dirs, manually add the top level dir of the source files to be
978 // compiled.
979 topLevelDirs := map[string]bool{}
980 for _, srcFilePath := range srcFiles {
981 srcFileParts := strings.Split(srcFilePath.String(), "/")
982 // Ignore source files that are already in the top level directory
983 // as well as generated files in the out directory. The out
984 // directory may be an absolute path, which means srcFileParts[0] is the
985 // empty string, so check that as well. Note that "out" in Bazel's execution
986 // root is *not* a symlink, which doesn't cause problems for --patch-modules
987 // anyway, so it's fine to not apply this workaround for generated
988 // source files.
989 if len(srcFileParts) > 1 &&
990 srcFileParts[0] != "" &&
991 srcFileParts[0] != "out" {
992 topLevelDirs[srcFileParts[0]] = true
993 }
994 }
995 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
996
997 classPath := flags.classpath.FormJavaClassPath("")
998 if classPath != "" {
999 patchPaths = append(patchPaths, classPath)
1000 }
1001 javacFlags = append(
1002 javacFlags,
1003 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1004 }
1005 }
1006
1007 if len(javacFlags) > 0 {
1008 // optimization.
1009 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1010 flags.javacFlags = "$javacFlags"
1011 }
1012
1013 return flags
1014}
1015
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001016func (j *Module) AddJSONData(d *map[string]interface{}) {
1017 (&j.ModuleBase).AddJSONData(d)
1018 (*d)["Java"] = map[string]interface{}{
1019 "SourceExtensions": j.sourceExtensions,
1020 }
1021
1022}
1023
Jaewoong Jung26342642021-03-17 15:56:23 -07001024func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1025 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1026
1027 deps := j.collectDeps(ctx)
1028 flags := j.collectBuilderFlags(ctx, deps)
1029
1030 if flags.javaVersion.usesJavaModules() {
1031 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1032 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001033
Jaewoong Jung26342642021-03-17 15:56:23 -07001034 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001035 j.sourceExtensions = []string{}
1036 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1037 if hasSrcExt(srcFiles.Strings(), ext) {
1038 j.sourceExtensions = append(j.sourceExtensions, ext)
1039 }
1040 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001041 if hasSrcExt(srcFiles.Strings(), ".proto") {
1042 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1043 }
1044
1045 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1046 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1047 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1048 }
1049
Sam Delmerico2351eac2022-05-24 17:10:02 +00001050 aidlSrcs := srcFiles.FilterByExt(".aidl")
1051 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs, aidlSrcs)
1052
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001053 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001054 srcFiles = j.genSources(ctx, srcFiles, flags)
1055
1056 // Collect javac flags only after computing the full set of srcFiles to
1057 // ensure that the --patch-module lookup paths are complete.
1058 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1059
1060 srcJars := srcFiles.FilterByExt(".srcjar")
1061 srcJars = append(srcJars, deps.srcJars...)
1062 if aaptSrcJar != nil {
1063 srcJars = append(srcJars, aaptSrcJar)
1064 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001065 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001066
1067 if j.properties.Jarjar_rules != nil {
1068 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1069 }
1070
1071 jarName := ctx.ModuleName() + ".jar"
1072
1073 javaSrcFiles := srcFiles.FilterByExt(".java")
1074 var uniqueSrcFiles android.Paths
1075 set := make(map[string]bool)
1076 for _, v := range javaSrcFiles {
1077 if _, found := set[v.String()]; !found {
1078 set[v.String()] = true
1079 uniqueSrcFiles = append(uniqueSrcFiles, v)
1080 }
1081 }
1082
Colin Crossb5db4012022-03-28 17:12:39 -07001083 // We don't currently run annotation processors in turbine, which means we can't use turbine
1084 // generated header jars when an annotation processor that generates API is enabled. One
1085 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1086 // is used to run all of the annotation processors.
1087 disableTurbine := deps.disableTurbine
1088
Jaewoong Jung26342642021-03-17 15:56:23 -07001089 // Collect .java files for AIDEGen
1090 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1091
1092 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001093 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001094
1095 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001096 // When using kotlin sources turbine is used to generate annotation processor sources,
1097 // including for annotation processors that generate API, so we can use turbine for
1098 // java sources too.
1099 disableTurbine = false
1100
Jaewoong Jung26342642021-03-17 15:56:23 -07001101 // user defined kotlin flags.
1102 kotlincFlags := j.properties.Kotlincflags
1103 CheckKotlincFlags(ctx, kotlincFlags)
1104
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001105 // Workaround for KT-46512
1106 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001107
1108 // If there are kotlin files, compile them first but pass all the kotlin and java files
1109 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1110 // won't emit any classes for them.
1111 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1112 if ctx.Device() {
1113 kotlincFlags = append(kotlincFlags, "-no-jdk")
1114 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001115
1116 for _, plugin := range deps.kotlinPlugins {
1117 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1118 }
1119 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1120
Jaewoong Jung26342642021-03-17 15:56:23 -07001121 if len(kotlincFlags) > 0 {
1122 // optimization.
1123 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1124 flags.kotlincFlags += "$kotlincFlags"
1125 }
1126
1127 var kotlinSrcFiles android.Paths
1128 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1129 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1130
1131 // Collect .kt files for AIDEGen
1132 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1133 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1134
1135 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1136 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1137
1138 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1139 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1140
Isaac Chioua23d9942022-04-06 06:14:38 +00001141 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001142 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001143 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1144 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1145 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1146 srcJars = append(srcJars, kaptSrcJar)
1147 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001148 // Disable annotation processing in javac, it's already been handled by kapt
1149 flags.processorPath = nil
1150 flags.processors = nil
1151 }
1152
1153 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001154 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1155 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001156 if ctx.Failed() {
1157 return
1158 }
1159
Isaac Chioua23d9942022-04-06 06:14:38 +00001160 // Make javac rule depend on the kotlinc rule
1161 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1162
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001164 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1165
Jaewoong Jung26342642021-03-17 15:56:23 -07001166 // Jar kotlin classes into the final jar after javac
1167 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1168 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001169 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001170 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001171 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001172 } else {
1173 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001174 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001175 }
1176 }
1177
1178 jars := append(android.Paths(nil), kotlinJars...)
1179
1180 // Store the list of .java files that was passed to javac
1181 j.compiledJavaSrcs = uniqueSrcFiles
1182 j.compiledSrcJars = srcJars
1183
1184 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001185 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001186 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001187 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1188 enableSharding = true
1189 // Formerly, there was a check here that prevented annotation processors
1190 // from being used when sharding was enabled, as some annotation processors
1191 // do not function correctly in sharded environments. It was removed to
1192 // allow for the use of annotation processors that do function correctly
1193 // with sharding enabled. See: b/77284273.
1194 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001195 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001196 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001197 if ctx.Failed() {
1198 return
1199 }
1200 }
1201 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1202 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001203 if Bool(j.properties.Errorprone.Enabled) {
1204 // If error-prone is enabled, enable errorprone flags on the regular
1205 // build.
1206 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001207 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001208 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1209 // a new jar file just for compiling with the errorprone compiler to.
1210 // This is because we don't want to cause the java files to get completely
1211 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1212 // We also don't want to run this if errorprone is enabled by default for
1213 // this module, or else we could have duplicated errorprone messages.
1214 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001215 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001216
1217 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1218 "errorprone", "errorprone")
1219
Jaewoong Jung26342642021-03-17 15:56:23 -07001220 extraJarDeps = append(extraJarDeps, errorprone)
1221 }
1222
1223 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001224 if headerJarFileWithoutDepsOrJarjar != nil {
1225 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1226 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001227 shardSize := int(*(j.properties.Javac_shard_size))
1228 var shardSrcs []android.Paths
1229 if len(uniqueSrcFiles) > 0 {
1230 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1231 for idx, shardSrc := range shardSrcs {
1232 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1233 nil, flags, extraJarDeps)
1234 jars = append(jars, classes)
1235 }
1236 }
1237 if len(srcJars) > 0 {
1238 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1239 nil, srcJars, flags, extraJarDeps)
1240 jars = append(jars, classes)
1241 }
1242 } else {
1243 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1244 jars = append(jars, classes)
1245 }
1246 if ctx.Failed() {
1247 return
1248 }
1249 }
1250
1251 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1252
1253 var includeSrcJar android.WritablePath
1254 if Bool(j.properties.Include_srcs) {
1255 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1256 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1257 }
1258
1259 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1260 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1261 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1262 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1263
1264 var resArgs []string
1265 var resDeps android.Paths
1266
1267 resArgs = append(resArgs, dirArgs...)
1268 resDeps = append(resDeps, dirDeps...)
1269
1270 resArgs = append(resArgs, fileArgs...)
1271 resDeps = append(resDeps, fileDeps...)
1272
1273 resArgs = append(resArgs, extraArgs...)
1274 resDeps = append(resDeps, extraDeps...)
1275
1276 if len(resArgs) > 0 {
1277 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1278 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1279 j.resourceJar = resourceJar
1280 if ctx.Failed() {
1281 return
1282 }
1283 }
1284
1285 var resourceJars android.Paths
1286 if j.resourceJar != nil {
1287 resourceJars = append(resourceJars, j.resourceJar)
1288 }
1289 if Bool(j.properties.Include_srcs) {
1290 resourceJars = append(resourceJars, includeSrcJar)
1291 }
1292 resourceJars = append(resourceJars, deps.staticResourceJars...)
1293
1294 if len(resourceJars) > 1 {
1295 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1296 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1297 false, nil, nil)
1298 j.resourceJar = combinedJar
1299 } else if len(resourceJars) == 1 {
1300 j.resourceJar = resourceJars[0]
1301 }
1302
1303 if len(deps.staticJars) > 0 {
1304 jars = append(jars, deps.staticJars...)
1305 }
1306
1307 manifest := j.overrideManifest
1308 if !manifest.Valid() && j.properties.Manifest != nil {
1309 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1310 }
1311
1312 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1313 if len(services) > 0 {
1314 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1315 var zipargs []string
1316 for _, file := range services {
1317 serviceFile := file.String()
1318 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1319 }
1320 rule := zip
1321 args := map[string]string{
1322 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1323 }
1324 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1325 rule = zipRE
1326 args["implicits"] = strings.Join(services.Strings(), ",")
1327 }
1328 ctx.Build(pctx, android.BuildParams{
1329 Rule: rule,
1330 Output: servicesJar,
1331 Implicits: services,
1332 Args: args,
1333 })
1334 jars = append(jars, servicesJar)
1335 }
1336
1337 // Combine the classes built from sources, any manifests, and any static libraries into
1338 // classes.jar. If there is only one input jar this step will be skipped.
1339 var outputFile android.OutputPath
1340
1341 if len(jars) == 1 && !manifest.Valid() {
1342 // Optimization: skip the combine step as there is nothing to do
1343 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1344 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1345 // any if len(jars) == 1.
1346
1347 // Transform the single path to the jar into an OutputPath as that is required by the following
1348 // code.
1349 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1350 // The path contains an embedded OutputPath so reuse that.
1351 outputFile = moduleOutPath.OutputPath
1352 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1353 // The path is an OutputPath so reuse it directly.
1354 outputFile = outputPath
1355 } else {
1356 // The file is not in the out directory so create an OutputPath into which it can be copied
1357 // and which the following code can use to refer to it.
1358 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1359 ctx.Build(pctx, android.BuildParams{
1360 Rule: android.Cp,
1361 Input: jars[0],
1362 Output: combinedJar,
1363 })
1364 outputFile = combinedJar.OutputPath
1365 }
1366 } else {
1367 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1368 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1369 false, nil, nil)
1370 outputFile = combinedJar.OutputPath
1371 }
1372
1373 // jarjar implementation jar if necessary
1374 if j.expandJarjarRules != nil {
1375 // Transform classes.jar into classes-jarjar.jar
1376 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1377 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1378 outputFile = jarjarFile
1379
1380 // jarjar resource jar if necessary
1381 if j.resourceJar != nil {
1382 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1383 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1384 j.resourceJar = resourceJarJarFile
1385 }
1386
1387 if ctx.Failed() {
1388 return
1389 }
1390 }
1391
1392 // Check package restrictions if necessary.
1393 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001394 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001395 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001396
1397 // Create a rule to copy the output jar to another path and add a validate dependency that
1398 // will check that the jar only contains the permitted packages. The new location will become
1399 // the output file of this module.
1400 inputFile := outputFile
1401 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1402 ctx.Build(pctx, android.BuildParams{
1403 Rule: android.Cp,
1404 Input: inputFile,
1405 Output: outputFile,
1406 // Make sure that any dependency on the output file will cause ninja to run the package check
1407 // rule.
1408 Validation: pkgckFile,
1409 })
1410
1411 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001412 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001413
1414 if ctx.Failed() {
1415 return
1416 }
1417 }
1418
1419 j.implementationJarFile = outputFile
1420 if j.headerJarFile == nil {
1421 j.headerJarFile = j.implementationJarFile
1422 }
1423
1424 if j.shouldInstrumentInApex(ctx) {
1425 j.properties.Instrument = true
1426 }
1427
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001428 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1429 specs := j.jacocoModuleToZipCommand(ctx)
1430 if ctx.Failed() {
1431 return
1432 }
1433
Jaewoong Jung26342642021-03-17 15:56:23 -07001434 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001435 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001436 }
1437
1438 // merge implementation jar with resources if necessary
1439 implementationAndResourcesJar := outputFile
1440 if j.resourceJar != nil {
1441 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1442 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1443 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1444 false, nil, nil)
1445 implementationAndResourcesJar = combinedJar
1446 }
1447
1448 j.implementationAndResourcesJar = implementationAndResourcesJar
1449
1450 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001451 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001452 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1453 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001454 if compileDex == nil {
1455 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001456 }
1457 if j.deviceProperties.Hostdex == nil {
1458 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1459 }
1460 }
1461
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001462 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001463 if j.hasCode(ctx) {
1464 if j.shouldInstrumentStatic(ctx) {
1465 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1466 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1467 }
1468 // Dex compilation
1469 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001470 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001471 if ctx.Failed() {
1472 return
1473 }
1474
Jaewoong Jung26342642021-03-17 15:56:23 -07001475 // merge dex jar with resources if necessary
1476 if j.resourceJar != nil {
1477 jars := android.Paths{dexOutputFile, j.resourceJar}
1478 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1479 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1480 false, nil, nil)
1481 if *j.dexProperties.Uncompress_dex {
1482 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1483 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1484 dexOutputFile = combinedAlignedJar
1485 } else {
1486 dexOutputFile = combinedJar
1487 }
1488 }
1489
Paul Duffin4de94502021-05-16 05:21:16 +01001490 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001491
1492 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001493
1494 // Encode hidden API flags in dex file, if needed.
1495 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1496
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001497 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001498
1499 // Dexpreopting
1500 j.dexpreopt(ctx, dexOutputFile)
1501
1502 outputFile = dexOutputFile
1503 } else {
1504 // There is no code to compile into a dex jar, make sure the resources are propagated
1505 // to the APK if this is an app.
1506 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001507 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001508 }
1509
1510 if ctx.Failed() {
1511 return
1512 }
1513 } else {
1514 outputFile = implementationAndResourcesJar
1515 }
1516
1517 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001518 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001519 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001520 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001521 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001522 // When running metalava, we pass --version-codename. When that value
1523 // is not REL, metalava will add 1 to the --current-version argument.
1524 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1525 // branch) and the codename is REL, except potentially on the most
1526 // recent non-master branch. On that branch, it goes through two other
1527 // phases before it gets to the phase previously described:
1528 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1529 // is not rel. This happens for most of the internal branch's life
1530 // while the branch has been cut but is still under active development.
1531 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1532 // REL. This happens briefly during the release process. During this
1533 // state the code to add --current-version is commented out, and then
1534 // that commenting out is reverted after the codename is set to REL.
1535 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1536 // prior version and the codename is always non-REL.
1537 //
1538 // We need to add one here to match metalava adding 1. Technically
1539 // this means that in the state described in the second bullet point
1540 // above, this number is 1 higher than it should be.
1541 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001542 }
1543 }
1544
1545 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001546 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1547 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001548 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1549 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001550 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1551 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1552 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001553 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001554 j.linter.javaLanguageLevel = flags.javaVersion.String()
1555 j.linter.kotlinLanguageLevel = "1.3"
1556 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1557 j.linter.buildModuleReportZip = true
1558 }
1559 j.linter.lint(ctx)
1560 }
1561
1562 ctx.CheckbuildFile(outputFile)
1563
1564 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1565 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1566 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1567 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1568 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1569 AidlIncludeDirs: j.exportAidlIncludeDirs,
1570 SrcJarArgs: j.srcJarArgs,
1571 SrcJarDeps: j.srcJarDeps,
1572 ExportedPlugins: j.exportedPluginJars,
1573 ExportedPluginClasses: j.exportedPluginClasses,
1574 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1575 JacocoReportClassesFile: j.jacocoReportClassesFile,
1576 })
1577
1578 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1579 j.outputFile = outputFile.WithoutRel()
1580}
1581
Colin Crossa1ff7c62021-09-17 14:11:52 -07001582func (j *Module) useCompose() bool {
1583 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1584}
1585
Cole Faust75fffb12021-06-13 15:23:16 -07001586// Returns a copy of the supplied flags, but with all the errorprone-related
1587// fields copied to the regular build's fields.
1588func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1589 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1590
1591 if len(flags.errorProneExtraJavacFlags) > 0 {
1592 if len(flags.javacFlags) > 0 {
1593 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1594 } else {
1595 flags.javacFlags = flags.errorProneExtraJavacFlags
1596 }
1597 }
1598 return flags
1599}
1600
Jaewoong Jung26342642021-03-17 15:56:23 -07001601func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1602 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1603
1604 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1605 if idx >= 0 {
1606 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1607 jarName += strconv.Itoa(idx)
1608 }
1609
1610 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1611 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1612
1613 if ctx.Config().EmitXrefRules() {
1614 extractionFile := android.PathForModuleOut(ctx, kzipName)
1615 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1616 j.kytheFiles = append(j.kytheFiles, extractionFile)
1617 }
1618
1619 return classes
1620}
1621
1622// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1623// since some of these flags may be used internally.
1624func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1625 for _, flag := range flags {
1626 flag = strings.TrimSpace(flag)
1627
1628 if !strings.HasPrefix(flag, "-") {
1629 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1630 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1631 ctx.PropertyErrorf("kotlincflags",
1632 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1633 } else if inList(flag, config.KotlincIllegalFlags) {
1634 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1635 } else if flag == "-include-runtime" {
1636 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1637 } else {
1638 args := strings.Split(flag, " ")
1639 if args[0] == "-kotlin-home" {
1640 ctx.PropertyErrorf("kotlincflags",
1641 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1642 }
1643 }
1644 }
1645}
1646
1647func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1648 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001649 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001650
1651 var jars android.Paths
1652 if len(srcFiles) > 0 || len(srcJars) > 0 {
1653 // Compile java sources into turbine.jar.
1654 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1655 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1656 if ctx.Failed() {
1657 return nil, nil
1658 }
1659 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001660 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001661 }
1662
1663 jars = append(jars, extraJars...)
1664
1665 // Combine any static header libraries into classes-header.jar. If there is only
1666 // one input jar this step will be skipped.
1667 jars = append(jars, deps.staticHeaderJars...)
1668
1669 // we cannot skip the combine step for now if there is only one jar
1670 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1671 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1672 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1673 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001674 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001675
1676 if j.expandJarjarRules != nil {
1677 // Transform classes.jar into classes-jarjar.jar
1678 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001679 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1680 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001681 if ctx.Failed() {
1682 return nil, nil
1683 }
1684 }
1685
Colin Cross3d56ed52021-11-18 22:23:12 -08001686 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001687}
1688
1689func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001690 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001691
1692 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1693 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1694
1695 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1696
1697 j.jacocoReportClassesFile = jacocoReportClassesFile
1698
1699 return instrumentedJar
1700}
1701
1702func (j *Module) HeaderJars() android.Paths {
1703 if j.headerJarFile == nil {
1704 return nil
1705 }
1706 return android.Paths{j.headerJarFile}
1707}
1708
1709func (j *Module) ImplementationJars() android.Paths {
1710 if j.implementationJarFile == nil {
1711 return nil
1712 }
1713 return android.Paths{j.implementationJarFile}
1714}
1715
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001716func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001717 return j.dexJarFile
1718}
1719
1720func (j *Module) DexJarInstallPath() android.Path {
1721 return j.installFile
1722}
1723
1724func (j *Module) ImplementationAndResourcesJars() android.Paths {
1725 if j.implementationAndResourcesJar == nil {
1726 return nil
1727 }
1728 return android.Paths{j.implementationAndResourcesJar}
1729}
1730
1731func (j *Module) AidlIncludeDirs() android.Paths {
1732 // exportAidlIncludeDirs is type android.Paths already
1733 return j.exportAidlIncludeDirs
1734}
1735
1736func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1737 return j.classLoaderContexts
1738}
1739
1740// Collect information for opening IDE project files in java/jdeps.go.
1741func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1742 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1743 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1744 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1745 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1746 if j.expandJarjarRules != nil {
1747 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1748 }
1749 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001750 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1751 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001752}
1753
1754func (j *Module) CompilerDeps() []string {
1755 jdeps := []string{}
1756 jdeps = append(jdeps, j.properties.Libs...)
1757 jdeps = append(jdeps, j.properties.Static_libs...)
1758 return jdeps
1759}
1760
1761func (j *Module) hasCode(ctx android.ModuleContext) bool {
1762 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1763 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1764}
1765
1766// Implements android.ApexModule
1767func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1768 return j.depIsInSameApex(ctx, dep)
1769}
1770
1771// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001772func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001773 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001774 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001775 return fmt.Errorf("min_sdk_version is not specified")
1776 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001777 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001778 return nil
1779 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001780 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1781 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001782 }
1783 return nil
1784}
1785
1786func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001787 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001788}
1789
Jaewoong Jung26342642021-03-17 15:56:23 -07001790func (j *Module) JacocoReportClassesFile() android.Path {
1791 return j.jacocoReportClassesFile
1792}
1793
1794func (j *Module) IsInstallable() bool {
1795 return Bool(j.properties.Installable)
1796}
1797
1798type sdkLinkType int
1799
1800const (
1801 // TODO(jiyong) rename these for better readability. Make the allowed
1802 // and disallowed link types explicit
1803 // order is important here. See rank()
1804 javaCore sdkLinkType = iota
1805 javaSdk
1806 javaSystem
1807 javaModule
1808 javaSystemServer
1809 javaPlatform
1810)
1811
1812func (lt sdkLinkType) String() string {
1813 switch lt {
1814 case javaCore:
1815 return "core Java API"
1816 case javaSdk:
1817 return "Android API"
1818 case javaSystem:
1819 return "system API"
1820 case javaModule:
1821 return "module API"
1822 case javaSystemServer:
1823 return "system server API"
1824 case javaPlatform:
1825 return "private API"
1826 default:
1827 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1828 }
1829}
1830
1831// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1832// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1833// can't statically depend on modules that use Platform API.
1834func (lt sdkLinkType) rank() int {
1835 return int(lt)
1836}
1837
1838type moduleWithSdkDep interface {
1839 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001840 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001841}
1842
Jiyong Park92315372021-04-02 08:45:46 +09001843func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001844 switch name {
1845 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1846 "stub-annotations", "private-stub-annotations-jar",
1847 "core-lambda-stubs", "core-generated-annotation-stubs":
1848 return javaCore, true
1849 case "android_stubs_current":
1850 return javaSdk, true
1851 case "android_system_stubs_current":
1852 return javaSystem, true
1853 case "android_module_lib_stubs_current":
1854 return javaModule, true
1855 case "android_system_server_stubs_current":
1856 return javaSystemServer, true
1857 case "android_test_stubs_current":
1858 return javaSystem, true
1859 }
1860
1861 if stub, linkType := moduleStubLinkType(name); stub {
1862 return linkType, true
1863 }
1864
Jiyong Park92315372021-04-02 08:45:46 +09001865 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001866 switch ver.Kind {
1867 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001868 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001869 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001870 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001871 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001872 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001873 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001874 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001875 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001876 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001877 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001878 return javaPlatform, false
1879 }
1880
Jiyong Parkf1691d22021-03-29 20:11:58 +09001881 if !ver.Valid() {
1882 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001883 }
1884 return javaSdk, false
1885}
1886
1887// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1888// this module's. See the comment on rank() for details and an example.
1889func (j *Module) checkSdkLinkType(
1890 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1891 if ctx.Host() {
1892 return
1893 }
1894
Jiyong Park92315372021-04-02 08:45:46 +09001895 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001896 if stubs {
1897 return
1898 }
Jiyong Park92315372021-04-02 08:45:46 +09001899 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001900
1901 if myLinkType.rank() < depLinkType.rank() {
1902 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1903 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1904 "property of the source or target module so that target module is built "+
1905 "with the same or smaller API set when compared to the source.",
1906 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1907 }
1908}
1909
1910func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1911 var deps deps
1912
1913 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001914 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001915 if sdkDep.invalidVersion {
1916 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1917 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1918 } else if sdkDep.useFiles {
1919 // sdkDep.jar is actually equivalent to turbine header.jar.
1920 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001921 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001922 deps.aidlPreprocess = sdkDep.aidl
1923 } else {
1924 deps.aidlPreprocess = sdkDep.aidl
1925 }
1926 }
1927
Jiyong Park92315372021-04-02 08:45:46 +09001928 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001929
1930 ctx.VisitDirectDeps(func(module android.Module) {
1931 otherName := ctx.OtherModuleName(module)
1932 tag := ctx.OtherModuleDependencyTag(module)
1933
1934 if IsJniDepTag(tag) {
1935 // Handled by AndroidApp.collectAppDeps
1936 return
1937 }
1938 if tag == certificateTag {
1939 // Handled by AndroidApp.collectAppDeps
1940 return
1941 }
1942
1943 if dep, ok := module.(SdkLibraryDependency); ok {
1944 switch tag {
1945 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001946 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1947 deps.classpath = append(deps.classpath, depHeaderJars...)
1948 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001949 case staticLibTag:
1950 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1951 }
1952 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1953 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1954 if sdkLinkType != javaPlatform &&
1955 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1956 // dep is a sysprop implementation library, but this module is not linking against
1957 // the platform, so it gets the sysprop public stubs library instead. Replace
1958 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1959 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1960 dep = syspropDep.JavaInfo
1961 }
1962 switch tag {
1963 case bootClasspathTag:
1964 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1965 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001966 if _, ok := module.(*Plugin); ok {
1967 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1968 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001969 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001970 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001971 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1972 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1973 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1974 case java9LibTag:
1975 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1976 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001977 if _, ok := module.(*Plugin); ok {
1978 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1979 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001980 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1981 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1982 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1983 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1984 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1985 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1986 // Turbine doesn't run annotation processors, so any module that uses an
1987 // annotation processor that generates API is incompatible with the turbine
1988 // optimization.
1989 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1990 case pluginTag:
1991 if plugin, ok := module.(*Plugin); ok {
1992 if plugin.pluginProperties.Processor_class != nil {
1993 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1994 } else {
1995 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1996 }
1997 // Turbine doesn't run annotation processors, so any module that uses an
1998 // annotation processor that generates API is incompatible with the turbine
1999 // optimization.
2000 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
2001 } else {
2002 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2003 }
2004 case errorpronePluginTag:
2005 if _, ok := module.(*Plugin); ok {
2006 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2007 } else {
2008 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2009 }
2010 case exportedPluginTag:
2011 if plugin, ok := module.(*Plugin); ok {
2012 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2013 if plugin.pluginProperties.Processor_class != nil {
2014 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2015 }
2016 // Turbine doesn't run annotation processors, so any module that uses an
2017 // annotation processor that generates API is incompatible with the turbine
2018 // optimization.
2019 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2020 } else {
2021 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2022 }
2023 case kotlinStdlibTag:
2024 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2025 case kotlinAnnotationsTag:
2026 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002027 case kotlinPluginTag:
2028 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002029 case syspropPublicStubDepTag:
2030 // This is a sysprop implementation library, forward the JavaInfoProvider from
2031 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2032 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2033 JavaInfo: dep,
2034 })
2035 }
2036 } else if dep, ok := module.(android.SourceFileProducer); ok {
2037 switch tag {
2038 case libTag:
2039 checkProducesJars(ctx, dep)
2040 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002041 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002042 case staticLibTag:
2043 checkProducesJars(ctx, dep)
2044 deps.classpath = append(deps.classpath, dep.Srcs()...)
2045 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2046 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2047 }
2048 } else {
2049 switch tag {
2050 case bootClasspathTag:
2051 // If a system modules dependency has been added to the bootclasspath
2052 // then add its libs to the bootclasspath.
2053 sm := module.(SystemModulesProvider)
2054 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2055
2056 case systemModulesTag:
2057 if deps.systemModules != nil {
2058 panic("Found two system module dependencies")
2059 }
2060 sm := module.(SystemModulesProvider)
2061 outputDir, outputDeps := sm.OutputDirAndDeps()
2062 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002063
2064 case instrumentationForTag:
2065 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 -07002066 }
2067 }
2068
2069 addCLCFromDep(ctx, module, j.classLoaderContexts)
2070 })
2071
2072 return deps
2073}
2074
2075func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2076 deps.processorPath = append(deps.processorPath, pluginJars...)
2077 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2078}
2079
2080// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2081// this interface.
2082type ProvidesUsesLib interface {
2083 ProvidesUsesLib() *string
2084}
2085
2086func (j *Module) ProvidesUsesLib() *string {
2087 return j.usesLibraryProperties.Provides_uses_lib
2088}
satayev1c564cc2021-05-25 19:50:30 +01002089
2090type ModuleWithStem interface {
2091 Stem() string
2092}
2093
2094var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002095
2096func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2097 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002098 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002099 if lib, ok := ctx.Module().(*Library); ok {
2100 javaLibraryBp2Build(ctx, lib)
2101 }
2102 case "java_binary_host":
2103 if binary, ok := ctx.Module().(*Binary); ok {
2104 javaBinaryHostBp2Build(ctx, binary)
2105 }
2106 }
Wei Libafb6d62021-12-10 03:14:59 -08002107}