blob: fe92b47544f1252f9d7b99194d2c310918e1742c [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
Cole Faust2b1536e2021-06-18 12:25:54 -0700159 // This property can be in 3 states. When set to true, errorprone will
160 // be run during the regular build. When set to false, errorprone will
161 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
162 // environment variable is true. Setting this to false will improve build
163 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700164 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700165 }
166
167 Proto struct {
168 // List of extra options that will be passed to the proto generator.
169 Output_params []string
170 }
171
172 Instrument bool `blueprint:"mutated"`
Paul Duffin0038a8d2022-05-03 00:28:40 +0000173 // If true, then the module supports statically including the jacocoagent
174 // into the library.
175 Supports_static_instrumentation bool `blueprint:"mutated"`
Jaewoong Jung26342642021-03-17 15:56:23 -0700176
177 // List of files to include in the META-INF/services folder of the resulting jar.
178 Services []string `android:"path,arch_variant"`
179
180 // If true, package the kotlin stdlib into the jar. Defaults to true.
181 Static_kotlin_stdlib *bool `android:"arch_variant"`
182
183 // A list of java_library instances that provide additional hiddenapi annotations for the library.
184 Hiddenapi_additional_annotations []string
185}
186
187// Properties that are specific to device modules. Host module factories should not add these when
188// constructing a new module.
189type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000190 // If not blank, set to the version of the sdk to compile against.
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000191 // Defaults to private.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000192 // Values are of one of the following forms:
Vinh Trana9c8f7d2022-04-14 20:18:47 +0000193 // 1) numerical API level, "current", "none", or "core_platform"
194 // 2) An SDK kind with an API level: "<sdk kind>_<API level>"
195 // See build/soong/android/sdk_version.go for the complete and up to date list of SDK kinds.
196 // If the SDK kind is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700197 Sdk_version *string
198
199 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000200 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700201 Min_sdk_version *string
202
satayev0a420e72021-11-29 17:25:52 +0000203 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
204 // Defaults to empty string "". See sdk_version for possible values.
205 Max_sdk_version *string
206
William Loh5a082f92022-05-17 20:21:50 +0000207 // if not blank, set the maxSdkVersion properties of permission and uses-permission tags.
208 // Defaults to empty string "". See sdk_version for possible values.
209 Replace_max_sdk_version_placeholder *string
210
Jaewoong Jung26342642021-03-17 15:56:23 -0700211 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000212 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700213 Target_sdk_version *string
214
215 // Whether to compile against the platform APIs instead of an SDK.
216 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000217 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700218 Platform_apis *bool
219
220 Aidl struct {
221 // Top level directories to pass to aidl tool
222 Include_dirs []string
223
224 // Directories rooted at the Android.bp file to pass to aidl tool
225 Local_include_dirs []string
226
227 // directories that should be added as include directories for any aidl sources of modules
228 // that depend on this module, as well as to aidl for this module.
229 Export_include_dirs []string
230
231 // whether to generate traces (for systrace) for this interface
232 Generate_traces *bool
233
234 // whether to generate Binder#GetTransaction name method.
235 Generate_get_transaction_name *bool
236
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100237 // whether all interfaces should be annotated with required permissions.
238 Enforce_permissions *bool
239
240 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
241 Enforce_permissions_exceptions []string `android:"path"`
242
Jaewoong Jung26342642021-03-17 15:56:23 -0700243 // list of flags that will be passed to the AIDL compiler
244 Flags []string
245 }
246
247 // If true, export a copy of the module as a -hostdex module for host testing.
248 Hostdex *bool
249
250 Target struct {
251 Hostdex struct {
252 // Additional required dependencies to add to -hostdex modules.
253 Required []string
254 }
255 }
256
257 // When targeting 1.9 and above, override the modules to use with --system,
258 // otherwise provides defaults libraries to add to the bootclasspath.
259 System_modules *string
260
Jaewoong Jung26342642021-03-17 15:56:23 -0700261 IsSDKLibrary bool `blueprint:"mutated"`
262
263 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
264 // Defaults to false.
265 V4_signature *bool
266
267 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
268 // public stubs library.
269 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000270
271 HiddenAPIPackageProperties
272 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700273}
274
Jooyung Han01d80d82022-01-08 12:16:32 +0900275// Device properties that can be overridden by overriding module (e.g. override_android_app)
276type OverridableDeviceProperties struct {
277 // set the name of the output. If not set, `name` is used.
278 // To override a module with this property set, overriding module might need to set this as well.
279 // Otherwise, both the overridden and the overriding modules will have the same output name, which
280 // can cause the duplicate output error.
281 Stem *string
282}
283
Jaewoong Jung26342642021-03-17 15:56:23 -0700284// Functionality common to Module and Import
285//
286// It is embedded in Module so its functionality can be used by methods in Module
287// but it is currently only initialized by Import and Library.
288type embeddableInModuleAndImport struct {
289
290 // Functionality related to this being used as a component of a java_sdk_library.
291 EmbeddableSdkLibraryComponent
292}
293
Paul Duffin71b33cc2021-06-23 11:39:47 +0100294func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
295 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700296}
297
298// Module/Import's DepIsInSameApex(...) delegates to this method.
299//
300// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
301// the one provided by ApexModuleBase.
302func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
303 // dependencies other than the static linkage are all considered crossing APEX boundary
304 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
305 return true
306 }
307 return false
308}
309
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100310// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
311// or an invalid path describing the reason it is invalid.
312//
313// It is unset if a dex jar isn't applicable, i.e. no build rule has been
314// requested to create one.
315//
316// If a dex jar has been requested to be built then it is set, and it may be
317// either a valid android.Path, or invalid with a reason message. The latter
318// happens if the source that should produce the dex file isn't able to.
319//
320// E.g. it is invalid with a reason message if there is a prebuilt APEX that
321// could produce the dex jar through a deapexer module, but the APEX isn't
322// installable so doing so wouldn't be safe.
323type OptionalDexJarPath struct {
324 isSet bool
325 path android.OptionalPath
326}
327
328// IsSet returns true if a path has been set, either invalid or valid.
329func (o OptionalDexJarPath) IsSet() bool {
330 return o.isSet
331}
332
333// Valid returns true if there is a path that is valid.
334func (o OptionalDexJarPath) Valid() bool {
335 return o.isSet && o.path.Valid()
336}
337
338// Path returns the valid path, or panics if it's either not set or is invalid.
339func (o OptionalDexJarPath) Path() android.Path {
340 if !o.isSet {
341 panic("path isn't set")
342 }
343 return o.path.Path()
344}
345
346// PathOrNil returns the path if it's set and valid, or else nil.
347func (o OptionalDexJarPath) PathOrNil() android.Path {
348 if o.Valid() {
349 return o.Path()
350 }
351 return nil
352}
353
354// InvalidReason returns the reason for an invalid path, which is never "". It
355// returns "" for an unset or valid path.
356func (o OptionalDexJarPath) InvalidReason() string {
357 if !o.isSet {
358 return ""
359 }
360 return o.path.InvalidReason()
361}
362
363func (o OptionalDexJarPath) String() string {
364 if !o.isSet {
365 return "<unset>"
366 }
367 return o.path.String()
368}
369
370// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
371func makeUnsetDexJarPath() OptionalDexJarPath {
372 return OptionalDexJarPath{isSet: false}
373}
374
375// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
376// the given OptionalPath, which may be valid or invalid.
377func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
378 return OptionalDexJarPath{isSet: true, path: path}
379}
380
381// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
382// valid given path. It returns an unset OptionalDexJarPath if the given path is
383// nil.
384func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
385 if path == nil {
386 return makeUnsetDexJarPath()
387 }
388 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
389}
390
Jaewoong Jung26342642021-03-17 15:56:23 -0700391// Module contains the properties and members used by all java module types
392type Module struct {
393 android.ModuleBase
394 android.DefaultableModuleBase
395 android.ApexModuleBase
396 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800397 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700398
399 // Functionality common to Module and Import.
400 embeddableInModuleAndImport
401
402 properties CommonProperties
403 protoProperties android.ProtoProperties
404 deviceProperties DeviceProperties
405
Jooyung Han01d80d82022-01-08 12:16:32 +0900406 overridableDeviceProperties OverridableDeviceProperties
407
Jaewoong Jung26342642021-03-17 15:56:23 -0700408 // jar file containing header classes including static library dependencies, suitable for
409 // inserting into the bootclasspath/classpath of another compile
410 headerJarFile android.Path
411
412 // jar file containing implementation classes including static library dependencies but no
413 // resources
414 implementationJarFile android.Path
415
416 // jar file containing only resources including from static library dependencies
417 resourceJar android.Path
418
419 // args and dependencies to package source files into a srcjar
420 srcJarArgs []string
421 srcJarDeps android.Paths
422
423 // jar file containing implementation classes and resources including static library
424 // dependencies
425 implementationAndResourcesJar android.Path
426
427 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100428 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700429
430 // output file containing uninstrumented classes that will be instrumented by jacoco
431 jacocoReportClassesFile android.Path
432
433 // output file of the module, which may be a classes jar or a dex jar
434 outputFile android.Path
435 extraOutputFiles android.Paths
436
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100437 exportAidlIncludeDirs android.Paths
438 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700439
440 logtagsSrcs android.Paths
441
442 // installed file for binary dependency
443 installFile android.Path
444
Colin Cross3108ce12021-11-10 14:38:50 -0800445 // installed file for hostdex copy
446 hostdexInstallFile android.InstallPath
447
Jaewoong Jung26342642021-03-17 15:56:23 -0700448 // list of .java files and srcjars that was passed to javac
449 compiledJavaSrcs android.Paths
450 compiledSrcJars android.Paths
451
452 // manifest file to use instead of properties.Manifest
453 overrideManifest android.OptionalPath
454
Jaewoong Jung26342642021-03-17 15:56:23 -0700455 // list of plugins that this java module is exporting
456 exportedPluginJars android.Paths
457
458 // list of plugins that this java module is exporting
459 exportedPluginClasses []string
460
461 // if true, the exported plugins generate API and require disabling turbine.
462 exportedDisableTurbine bool
463
464 // list of source files, collected from srcFiles with unique java and all kt files,
465 // will be used by android.IDEInfo struct
466 expandIDEInfoCompiledSrcs []string
467
468 // expanded Jarjar_rules
469 expandJarjarRules android.Path
470
Jaewoong Jung26342642021-03-17 15:56:23 -0700471 // Extra files generated by the module type to be added as java resources.
472 extraResources android.Paths
473
474 hiddenAPI
475 dexer
476 dexpreopter
477 usesLibrary
478 linter
479
480 // list of the xref extraction files
481 kytheFiles android.Paths
482
483 // Collect the module directory for IDE info in java/jdeps.go.
484 modulePaths []string
485
486 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900487
488 sdkVersion android.SdkSpec
489 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000490 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400491
492 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700493}
494
Jiyong Park92315372021-04-02 08:45:46 +0900495func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
496 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900497 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700498 return nil
499 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900500 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000501 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700502 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
503 } else {
504 // Treat stable core platform as stable.
505 return nil
506 }
507 } else {
508 return fmt.Errorf("non stable SDK %v", sdkVersion)
509 }
510}
511
512// checkSdkVersions enforces restrictions around SDK dependencies.
513func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
514 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900515 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900516 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700517 ctx.PropertyErrorf("sdk_version",
518 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
519 }
520 }
521 }
522
523 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
524 // See rank() for details.
525 ctx.VisitDirectDeps(func(module android.Module) {
526 tag := ctx.OtherModuleDependencyTag(module)
527 switch module.(type) {
528 // TODO(satayev): cover other types as well, e.g. imports
529 case *Library, *AndroidLibrary:
530 switch tag {
531 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
532 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
533 }
534 }
535 })
536}
537
538func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900539 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700540 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900541 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700542 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000543 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
Jaewoong Jung26342642021-03-17 15:56:23 -0700544 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000545 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
Jaewoong Jung26342642021-03-17 15:56:23 -0700546 }
547
548 }
549}
550
551func (j *Module) addHostProperties() {
552 j.AddProperties(
553 &j.properties,
554 &j.protoProperties,
555 &j.usesLibraryProperties,
556 )
557}
558
559func (j *Module) addHostAndDeviceProperties() {
560 j.addHostProperties()
561 j.AddProperties(
562 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900563 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700564 &j.dexer.dexProperties,
565 &j.dexpreoptProperties,
566 &j.linter.properties,
567 )
568}
569
Paul Duffin3f1ae0b2022-07-27 16:27:42 +0000570// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
571// makes it available through the hiddenAPIPropertyInfoProvider.
572func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
573 hiddenAPIInfo := newHiddenAPIPropertyInfo()
574
575 // Populate with flag file paths from the properties.
576 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
577
578 // Populate with package rules from the properties.
579 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
580
581 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
582}
583
Jaewoong Jung26342642021-03-17 15:56:23 -0700584func (j *Module) OutputFiles(tag string) (android.Paths, error) {
585 switch tag {
586 case "":
587 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
588 case android.DefaultDistTag:
589 return android.Paths{j.outputFile}, nil
590 case ".jar":
591 return android.Paths{j.implementationAndResourcesJar}, nil
592 case ".proguard_map":
593 if j.dexer.proguardDictionary.Valid() {
594 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
595 }
596 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
597 default:
598 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
599 }
600}
601
602var _ android.OutputFileProducer = (*Module)(nil)
603
604func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
605 initJavaModule(module, hod, false)
606}
607
608func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
609 initJavaModule(module, hod, true)
610}
611
612func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
613 multilib := android.MultilibCommon
614 if multiTargets {
615 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
616 } else {
617 android.InitAndroidArchModule(module, hod, multilib)
618 }
619 android.InitDefaultableModule(module)
620}
621
622func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
623 return j.properties.Instrument &&
624 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
625 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
626}
627
628func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin0038a8d2022-05-03 00:28:40 +0000629 return j.properties.Supports_static_instrumentation &&
630 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700631 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
632 ctx.Config().UnbundledBuild())
633}
634
635func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
636 // Force enable the instrumentation for java code that is built for APEXes ...
637 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
638 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
639 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
640 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
641 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
642 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
643 return true
644 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
645 return true
646 }
647 }
648 return false
649}
650
Jiyong Park92315372021-04-02 08:45:46 +0900651func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
652 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700653}
654
Jiyong Parkf1691d22021-03-29 20:11:58 +0900655func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700656 return proptools.String(j.deviceProperties.System_modules)
657}
658
Jiyong Park92315372021-04-02 08:45:46 +0900659func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700660 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900661 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700662 }
Jiyong Park92315372021-04-02 08:45:46 +0900663 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700664}
665
satayev0a420e72021-11-29 17:25:52 +0000666func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
667 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
668 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
669 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
670 return android.SdkSpecFrom(ctx, maxSdkVersion)
671}
672
William Loh5a082f92022-05-17 20:21:50 +0000673func (j *Module) ReplaceMaxSdkVersionPlaceholder(ctx android.EarlyModuleContext) android.SdkSpec {
674 replaceMaxSdkVersionPlaceholder := proptools.StringDefault(j.deviceProperties.Replace_max_sdk_version_placeholder, "")
675 return android.SdkSpecFrom(ctx, replaceMaxSdkVersionPlaceholder)
676}
677
Jiyong Parkf1691d22021-03-29 20:11:58 +0900678func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900679 return j.minSdkVersion.Raw
680}
681
682func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
683 if j.deviceProperties.Target_sdk_version != nil {
684 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
685 }
686 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700687}
688
689func (j *Module) AvailableFor(what string) bool {
690 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
691 // Exception: for hostdex: true libraries, the platform variant is created
692 // even if it's not marked as available to platform. In that case, the platform
693 // variant is used only for the hostdex and not installed to the device.
694 return true
695 }
696 return j.ApexModuleBase.AvailableFor(what)
697}
698
699func (j *Module) deps(ctx android.BottomUpMutatorContext) {
700 if ctx.Device() {
701 j.linter.deps(ctx)
702
Jiyong Parkf1691d22021-03-29 20:11:58 +0900703 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700704
705 if j.deviceProperties.SyspropPublicStub != "" {
706 // This is a sysprop implementation library that has a corresponding sysprop public
707 // stubs library, and a dependency on it so that dependencies on the implementation can
708 // be forwarded to the public stubs library when necessary.
709 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
710 }
711 }
712
713 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
714 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
715
716 // Add dependency on libraries that provide additional hidden api annotations.
717 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
718
719 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
720 // Require java_sdk_library at inter-partition java dependency to ensure stable
721 // interface between partitions. If inter-partition java_library dependency is detected,
722 // raise build error because java_library doesn't have a stable interface.
723 //
724 // Inputs:
725 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
726 // if true, enable enforcement
727 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
728 // exception list of java_library names to allow inter-partition dependency
729 for idx := range j.properties.Libs {
730 if libDeps[idx] == nil {
731 continue
732 }
733
734 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
735 // java_sdk_library is always allowed at inter-partition dependency.
736 // So, skip check.
737 if _, ok := javaDep.(*SdkLibrary); ok {
738 continue
739 }
740
741 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
742 }
743 }
744 }
745
746 // For library dependencies that are component libraries (like stubs), add the implementation
747 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
748 for _, dep := range libDeps {
749 if dep != nil {
750 if component, ok := dep.(SdkLibraryComponentDependency); ok {
751 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100752 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovichf5d91bb2022-05-04 12:00:02 +0100753 tag := usesLibReqTag
754 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
755 tag = usesLibOptTag
756 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100757 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700758 }
759 }
760 }
761 }
762
763 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
764 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
765 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
766
767 android.ProtoDeps(ctx, &j.protoProperties)
768 if j.hasSrcExt(".proto") {
769 protoDeps(ctx, &j.protoProperties)
770 }
771
772 if j.hasSrcExt(".kt") {
773 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
774 // Kotlin files
775 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
776 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
Colin Cross06354472022-05-03 14:20:24 -0700777 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
Jaewoong Jung26342642021-03-17 15:56:23 -0700778 }
779
780 // Framework libraries need special handling in static coverage builds: they should not have
781 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
782 // the same jacoco classes coming from different bootclasspath jars.
783 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
784 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
785 j.properties.Instrument = true
786 }
787 } else if j.shouldInstrumentStatic(ctx) {
788 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
789 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700790
791 if j.useCompose() {
792 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
793 "androidx.compose.compiler_compiler-hosted")
794 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700795}
796
797func hasSrcExt(srcs []string, ext string) bool {
798 for _, src := range srcs {
799 if filepath.Ext(src) == ext {
800 return true
801 }
802 }
803
804 return false
805}
806
807func (j *Module) hasSrcExt(ext string) bool {
808 return hasSrcExt(j.properties.Srcs, ext)
809}
810
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100811func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
812 var flags string
813
814 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
815 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
816 flags = "-Wmissing-permission-annotation -Werror"
817 }
818 }
819 return flags
820}
821
Jaewoong Jung26342642021-03-17 15:56:23 -0700822func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
823 aidlIncludeDirs android.Paths) (string, android.Paths) {
824
825 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
826 aidlIncludes = append(aidlIncludes,
827 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
828 aidlIncludes = append(aidlIncludes,
829 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
830
831 var flags []string
832 var deps android.Paths
833
834 flags = append(flags, j.deviceProperties.Aidl.Flags...)
835
836 if aidlPreprocess.Valid() {
837 flags = append(flags, "-p"+aidlPreprocess.String())
838 deps = append(deps, aidlPreprocess.Path())
839 } else if len(aidlIncludeDirs) > 0 {
840 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
841 }
842
843 if len(j.exportAidlIncludeDirs) > 0 {
844 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
845 }
846
847 if len(aidlIncludes) > 0 {
848 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
849 }
850
851 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
852 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
853 flags = append(flags, "-I"+src.String())
854 }
855
856 if Bool(j.deviceProperties.Aidl.Generate_traces) {
857 flags = append(flags, "-t")
858 }
859
860 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
861 flags = append(flags, "--transaction_names")
862 }
863
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100864 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
865 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
866 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
867 }
868
Jooyung Han07f70c02021-11-06 07:08:45 +0900869 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
870 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
871
Jaewoong Jung26342642021-03-17 15:56:23 -0700872 return strings.Join(flags, " "), deps
873}
874
875func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
876
877 var flags javaBuilderFlags
878
879 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900880 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
Cole Faust2b1536e2021-06-18 12:25:54 -0700882 epEnabled := j.properties.Errorprone.Enabled
883 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700884 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
885 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
886 }
887
888 errorProneFlags := []string{
889 "-Xplugin:ErrorProne",
890 "${config.ErrorProneChecks}",
891 }
892 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
893
Colin Cross8bf6cad2022-02-28 13:07:03 -0800894 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700895 "'" + strings.Join(errorProneFlags, " ") + "'"
896 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
897 }
898
899 // classpath
900 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
901 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700902 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700903 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
904 flags.processorPath = append(flags.processorPath, deps.processorPath...)
905 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
906
907 flags.processors = append(flags.processors, deps.processorClasses...)
908 flags.processors = android.FirstUniqueStrings(flags.processors)
909
910 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900911 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700912 // Give host-side tools a version of OpenJDK's standard libraries
913 // close to what they're targeting. As of Dec 2017, AOSP is only
914 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
915 //
916 // When building with OpenJDK 8, the following should have no
917 // effect since those jars would be available by default.
918 //
919 // When building with OpenJDK 9 but targeting a version < 1.8,
920 // putting them on the bootclasspath means that:
921 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
922 // b) references to existing APIs are not reinterpreted in an
923 // OpenJDK 9-specific way, eg. calls to subclasses of
924 // java.nio.Buffer as in http://b/70862583
925 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
926 flags.bootClasspath = append(flags.bootClasspath,
927 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
928 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
929 if Bool(j.properties.Use_tools_jar) {
930 flags.bootClasspath = append(flags.bootClasspath,
931 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
932 }
933 }
934
935 // systemModules
936 flags.systemModules = deps.systemModules
937
938 // aidl flags.
939 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
940
941 return flags
942}
943
944func (j *Module) collectJavacFlags(
945 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
946 // javac flags.
947 javacFlags := j.properties.Javacflags
948
949 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
950 // For non-host binaries, override the -g flag passed globally to remove
951 // local variable debug info to reduce disk and memory usage.
952 javacFlags = append(javacFlags, "-g:source,lines")
953 }
954 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
955
956 if flags.javaVersion.usesJavaModules() {
957 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
958
959 if j.properties.Patch_module != nil {
960 // Manually specify build directory in case it is not under the repo root.
961 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
962 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200963 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700964
965 // b/150878007
966 //
967 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
968 // execution root for --patch-module. If this javac command line is
969 // invoked within Bazel's execution root working directory, the top
970 // level directories (e.g. libcore/, tools/, frameworks/) are all
971 // symlinks. JDK9 javac does not traverse into symlinks, which causes
972 // --patch-module to fail source file lookups when invoked in the
973 // execution root.
974 //
975 // Short of patching javac or enumerating *all* directories as possible
976 // input dirs, manually add the top level dir of the source files to be
977 // compiled.
978 topLevelDirs := map[string]bool{}
979 for _, srcFilePath := range srcFiles {
980 srcFileParts := strings.Split(srcFilePath.String(), "/")
981 // Ignore source files that are already in the top level directory
982 // as well as generated files in the out directory. The out
983 // directory may be an absolute path, which means srcFileParts[0] is the
984 // empty string, so check that as well. Note that "out" in Bazel's execution
985 // root is *not* a symlink, which doesn't cause problems for --patch-modules
986 // anyway, so it's fine to not apply this workaround for generated
987 // source files.
988 if len(srcFileParts) > 1 &&
989 srcFileParts[0] != "" &&
990 srcFileParts[0] != "out" {
991 topLevelDirs[srcFileParts[0]] = true
992 }
993 }
994 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
995
996 classPath := flags.classpath.FormJavaClassPath("")
997 if classPath != "" {
998 patchPaths = append(patchPaths, classPath)
999 }
1000 javacFlags = append(
1001 javacFlags,
1002 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
1003 }
1004 }
1005
1006 if len(javacFlags) > 0 {
1007 // optimization.
1008 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1009 flags.javacFlags = "$javacFlags"
1010 }
1011
1012 return flags
1013}
1014
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001015func (j *Module) AddJSONData(d *map[string]interface{}) {
1016 (&j.ModuleBase).AddJSONData(d)
1017 (*d)["Java"] = map[string]interface{}{
1018 "SourceExtensions": j.sourceExtensions,
1019 }
1020
1021}
1022
Jaewoong Jung26342642021-03-17 15:56:23 -07001023func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1024 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1025
1026 deps := j.collectDeps(ctx)
1027 flags := j.collectBuilderFlags(ctx, deps)
1028
1029 if flags.javaVersion.usesJavaModules() {
1030 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1031 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001032
Jaewoong Jung26342642021-03-17 15:56:23 -07001033 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001034 j.sourceExtensions = []string{}
1035 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1036 if hasSrcExt(srcFiles.Strings(), ext) {
1037 j.sourceExtensions = append(j.sourceExtensions, ext)
1038 }
1039 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001040 if hasSrcExt(srcFiles.Strings(), ".proto") {
1041 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1042 }
1043
1044 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1045 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1046 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1047 }
1048
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001049 nonGeneratedSrcJars := srcFiles.FilterByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001050 srcFiles = j.genSources(ctx, srcFiles, flags)
1051
1052 // Collect javac flags only after computing the full set of srcFiles to
1053 // ensure that the --patch-module lookup paths are complete.
1054 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1055
1056 srcJars := srcFiles.FilterByExt(".srcjar")
1057 srcJars = append(srcJars, deps.srcJars...)
1058 if aaptSrcJar != nil {
1059 srcJars = append(srcJars, aaptSrcJar)
1060 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001061 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001062
1063 if j.properties.Jarjar_rules != nil {
1064 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1065 }
1066
1067 jarName := ctx.ModuleName() + ".jar"
1068
1069 javaSrcFiles := srcFiles.FilterByExt(".java")
1070 var uniqueSrcFiles android.Paths
1071 set := make(map[string]bool)
1072 for _, v := range javaSrcFiles {
1073 if _, found := set[v.String()]; !found {
1074 set[v.String()] = true
1075 uniqueSrcFiles = append(uniqueSrcFiles, v)
1076 }
1077 }
1078
Colin Crossb5db4012022-03-28 17:12:39 -07001079 // We don't currently run annotation processors in turbine, which means we can't use turbine
1080 // generated header jars when an annotation processor that generates API is enabled. One
1081 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1082 // is used to run all of the annotation processors.
1083 disableTurbine := deps.disableTurbine
1084
Jaewoong Jung26342642021-03-17 15:56:23 -07001085 // Collect .java files for AIDEGen
1086 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1087
1088 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001089 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001090
1091 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001092 // When using kotlin sources turbine is used to generate annotation processor sources,
1093 // including for annotation processors that generate API, so we can use turbine for
1094 // java sources too.
1095 disableTurbine = false
1096
Jaewoong Jung26342642021-03-17 15:56:23 -07001097 // user defined kotlin flags.
1098 kotlincFlags := j.properties.Kotlincflags
1099 CheckKotlincFlags(ctx, kotlincFlags)
1100
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001101 // Workaround for KT-46512
1102 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001103
1104 // If there are kotlin files, compile them first but pass all the kotlin and java files
1105 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1106 // won't emit any classes for them.
1107 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1108 if ctx.Device() {
1109 kotlincFlags = append(kotlincFlags, "-no-jdk")
1110 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001111
1112 for _, plugin := range deps.kotlinPlugins {
1113 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1114 }
1115 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1116
Jaewoong Jung26342642021-03-17 15:56:23 -07001117 if len(kotlincFlags) > 0 {
1118 // optimization.
1119 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1120 flags.kotlincFlags += "$kotlincFlags"
1121 }
1122
1123 var kotlinSrcFiles android.Paths
1124 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1125 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1126
1127 // Collect .kt files for AIDEGen
1128 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1129 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1130
1131 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1132 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1133
1134 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1135 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1136
Isaac Chioua23d9942022-04-06 06:14:38 +00001137 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001138 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001139 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1140 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1141 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1142 srcJars = append(srcJars, kaptSrcJar)
1143 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001144 // Disable annotation processing in javac, it's already been handled by kapt
1145 flags.processorPath = nil
1146 flags.processors = nil
1147 }
1148
1149 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001150 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1151 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001152 if ctx.Failed() {
1153 return
1154 }
1155
Isaac Chioua23d9942022-04-06 06:14:38 +00001156 // Make javac rule depend on the kotlinc rule
1157 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1158
Jaewoong Jung26342642021-03-17 15:56:23 -07001159 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001160 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1161
Jaewoong Jung26342642021-03-17 15:56:23 -07001162 // Jar kotlin classes into the final jar after javac
1163 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1164 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001165 kotlinJars = append(kotlinJars, deps.kotlinAnnotations...)
Colin Cross220a9a12022-03-28 17:08:01 -07001166 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001167 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinAnnotations...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001168 } else {
1169 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Colin Cross06354472022-05-03 14:20:24 -07001170 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001171 }
1172 }
1173
1174 jars := append(android.Paths(nil), kotlinJars...)
1175
1176 // Store the list of .java files that was passed to javac
1177 j.compiledJavaSrcs = uniqueSrcFiles
1178 j.compiledSrcJars = srcJars
1179
1180 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001181 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001182 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001183 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1184 enableSharding = true
1185 // Formerly, there was a check here that prevented annotation processors
1186 // from being used when sharding was enabled, as some annotation processors
1187 // do not function correctly in sharded environments. It was removed to
1188 // allow for the use of annotation processors that do function correctly
1189 // with sharding enabled. See: b/77284273.
1190 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001191 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001192 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001193 if ctx.Failed() {
1194 return
1195 }
1196 }
1197 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1198 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001199 if Bool(j.properties.Errorprone.Enabled) {
1200 // If error-prone is enabled, enable errorprone flags on the regular
1201 // build.
1202 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001203 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001204 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1205 // a new jar file just for compiling with the errorprone compiler to.
1206 // This is because we don't want to cause the java files to get completely
1207 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1208 // We also don't want to run this if errorprone is enabled by default for
1209 // this module, or else we could have duplicated errorprone messages.
1210 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001211 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001212
1213 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1214 "errorprone", "errorprone")
1215
Jaewoong Jung26342642021-03-17 15:56:23 -07001216 extraJarDeps = append(extraJarDeps, errorprone)
1217 }
1218
1219 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001220 if headerJarFileWithoutDepsOrJarjar != nil {
1221 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1222 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001223 shardSize := int(*(j.properties.Javac_shard_size))
1224 var shardSrcs []android.Paths
1225 if len(uniqueSrcFiles) > 0 {
1226 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1227 for idx, shardSrc := range shardSrcs {
1228 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1229 nil, flags, extraJarDeps)
1230 jars = append(jars, classes)
1231 }
1232 }
1233 if len(srcJars) > 0 {
1234 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1235 nil, srcJars, flags, extraJarDeps)
1236 jars = append(jars, classes)
1237 }
1238 } else {
1239 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1240 jars = append(jars, classes)
1241 }
1242 if ctx.Failed() {
1243 return
1244 }
1245 }
1246
1247 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1248
1249 var includeSrcJar android.WritablePath
1250 if Bool(j.properties.Include_srcs) {
1251 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1252 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1253 }
1254
1255 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1256 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1257 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1258 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1259
1260 var resArgs []string
1261 var resDeps android.Paths
1262
1263 resArgs = append(resArgs, dirArgs...)
1264 resDeps = append(resDeps, dirDeps...)
1265
1266 resArgs = append(resArgs, fileArgs...)
1267 resDeps = append(resDeps, fileDeps...)
1268
1269 resArgs = append(resArgs, extraArgs...)
1270 resDeps = append(resDeps, extraDeps...)
1271
1272 if len(resArgs) > 0 {
1273 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1274 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1275 j.resourceJar = resourceJar
1276 if ctx.Failed() {
1277 return
1278 }
1279 }
1280
1281 var resourceJars android.Paths
1282 if j.resourceJar != nil {
1283 resourceJars = append(resourceJars, j.resourceJar)
1284 }
1285 if Bool(j.properties.Include_srcs) {
1286 resourceJars = append(resourceJars, includeSrcJar)
1287 }
1288 resourceJars = append(resourceJars, deps.staticResourceJars...)
1289
1290 if len(resourceJars) > 1 {
1291 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1292 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1293 false, nil, nil)
1294 j.resourceJar = combinedJar
1295 } else if len(resourceJars) == 1 {
1296 j.resourceJar = resourceJars[0]
1297 }
1298
1299 if len(deps.staticJars) > 0 {
1300 jars = append(jars, deps.staticJars...)
1301 }
1302
1303 manifest := j.overrideManifest
1304 if !manifest.Valid() && j.properties.Manifest != nil {
1305 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1306 }
1307
1308 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1309 if len(services) > 0 {
1310 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1311 var zipargs []string
1312 for _, file := range services {
1313 serviceFile := file.String()
1314 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1315 }
1316 rule := zip
1317 args := map[string]string{
1318 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1319 }
1320 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1321 rule = zipRE
1322 args["implicits"] = strings.Join(services.Strings(), ",")
1323 }
1324 ctx.Build(pctx, android.BuildParams{
1325 Rule: rule,
1326 Output: servicesJar,
1327 Implicits: services,
1328 Args: args,
1329 })
1330 jars = append(jars, servicesJar)
1331 }
1332
1333 // Combine the classes built from sources, any manifests, and any static libraries into
1334 // classes.jar. If there is only one input jar this step will be skipped.
1335 var outputFile android.OutputPath
1336
1337 if len(jars) == 1 && !manifest.Valid() {
1338 // Optimization: skip the combine step as there is nothing to do
1339 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1340 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1341 // any if len(jars) == 1.
1342
1343 // Transform the single path to the jar into an OutputPath as that is required by the following
1344 // code.
1345 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1346 // The path contains an embedded OutputPath so reuse that.
1347 outputFile = moduleOutPath.OutputPath
1348 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1349 // The path is an OutputPath so reuse it directly.
1350 outputFile = outputPath
1351 } else {
1352 // The file is not in the out directory so create an OutputPath into which it can be copied
1353 // and which the following code can use to refer to it.
1354 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1355 ctx.Build(pctx, android.BuildParams{
1356 Rule: android.Cp,
1357 Input: jars[0],
1358 Output: combinedJar,
1359 })
1360 outputFile = combinedJar.OutputPath
1361 }
1362 } else {
1363 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1364 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1365 false, nil, nil)
1366 outputFile = combinedJar.OutputPath
1367 }
1368
1369 // jarjar implementation jar if necessary
1370 if j.expandJarjarRules != nil {
1371 // Transform classes.jar into classes-jarjar.jar
1372 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1373 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1374 outputFile = jarjarFile
1375
1376 // jarjar resource jar if necessary
1377 if j.resourceJar != nil {
1378 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1379 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1380 j.resourceJar = resourceJarJarFile
1381 }
1382
1383 if ctx.Failed() {
1384 return
1385 }
1386 }
1387
1388 // Check package restrictions if necessary.
1389 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001390 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001391 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001392
1393 // Create a rule to copy the output jar to another path and add a validate dependency that
1394 // will check that the jar only contains the permitted packages. The new location will become
1395 // the output file of this module.
1396 inputFile := outputFile
1397 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1398 ctx.Build(pctx, android.BuildParams{
1399 Rule: android.Cp,
1400 Input: inputFile,
1401 Output: outputFile,
1402 // Make sure that any dependency on the output file will cause ninja to run the package check
1403 // rule.
1404 Validation: pkgckFile,
1405 })
1406
1407 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001408 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001409
1410 if ctx.Failed() {
1411 return
1412 }
1413 }
1414
1415 j.implementationJarFile = outputFile
1416 if j.headerJarFile == nil {
1417 j.headerJarFile = j.implementationJarFile
1418 }
1419
1420 if j.shouldInstrumentInApex(ctx) {
1421 j.properties.Instrument = true
1422 }
1423
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001424 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1425 specs := j.jacocoModuleToZipCommand(ctx)
1426 if ctx.Failed() {
1427 return
1428 }
1429
Jaewoong Jung26342642021-03-17 15:56:23 -07001430 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001431 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001432 }
1433
1434 // merge implementation jar with resources if necessary
1435 implementationAndResourcesJar := outputFile
1436 if j.resourceJar != nil {
1437 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1438 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1439 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1440 false, nil, nil)
1441 implementationAndResourcesJar = combinedJar
1442 }
1443
1444 j.implementationAndResourcesJar = implementationAndResourcesJar
1445
1446 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001447 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001448 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1449 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001450 if compileDex == nil {
1451 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001452 }
1453 if j.deviceProperties.Hostdex == nil {
1454 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1455 }
1456 }
1457
Paul Duffine7b1f5b2022-06-29 10:15:52 +00001458 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001459 if j.hasCode(ctx) {
1460 if j.shouldInstrumentStatic(ctx) {
1461 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1462 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1463 }
1464 // Dex compilation
1465 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001466 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001467 if ctx.Failed() {
1468 return
1469 }
1470
Jaewoong Jung26342642021-03-17 15:56:23 -07001471 // merge dex jar with resources if necessary
1472 if j.resourceJar != nil {
1473 jars := android.Paths{dexOutputFile, j.resourceJar}
1474 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1475 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1476 false, nil, nil)
1477 if *j.dexProperties.Uncompress_dex {
1478 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1479 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1480 dexOutputFile = combinedAlignedJar
1481 } else {
1482 dexOutputFile = combinedJar
1483 }
1484 }
1485
Paul Duffin4de94502021-05-16 05:21:16 +01001486 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001487
1488 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001489
1490 // Encode hidden API flags in dex file, if needed.
1491 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1492
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001493 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001494
1495 // Dexpreopting
1496 j.dexpreopt(ctx, dexOutputFile)
1497
1498 outputFile = dexOutputFile
1499 } else {
1500 // There is no code to compile into a dex jar, make sure the resources are propagated
1501 // to the APK if this is an app.
1502 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001503 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001504 }
1505
1506 if ctx.Failed() {
1507 return
1508 }
1509 } else {
1510 outputFile = implementationAndResourcesJar
1511 }
1512
1513 if ctx.Device() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001514 lintSDKVersion := func(sdkSpec android.SdkSpec) int {
Jiyong Park54105c42021-03-31 18:17:53 +09001515 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001516 return v.FinalInt()
Jaewoong Jung26342642021-03-17 15:56:23 -07001517 } else {
Cole Fauste5bf3fb2022-07-01 19:39:14 +00001518 // When running metalava, we pass --version-codename. When that value
1519 // is not REL, metalava will add 1 to the --current-version argument.
1520 // On old branches, PLATFORM_SDK_VERSION is the latest version (for that
1521 // branch) and the codename is REL, except potentially on the most
1522 // recent non-master branch. On that branch, it goes through two other
1523 // phases before it gets to the phase previously described:
1524 // - PLATFORM_SDK_VERSION has not been updated yet, and the codename
1525 // is not rel. This happens for most of the internal branch's life
1526 // while the branch has been cut but is still under active development.
1527 // - PLATFORM_SDK_VERSION has been set, but the codename is still not
1528 // REL. This happens briefly during the release process. During this
1529 // state the code to add --current-version is commented out, and then
1530 // that commenting out is reverted after the codename is set to REL.
1531 // On the master branch, the PLATFORM_SDK_VERSION always represents a
1532 // prior version and the codename is always non-REL.
1533 //
1534 // We need to add one here to match metalava adding 1. Technically
1535 // this means that in the state described in the second bullet point
1536 // above, this number is 1 higher than it should be.
1537 return ctx.Config().PlatformSdkVersion().FinalInt() + 1
Jaewoong Jung26342642021-03-17 15:56:23 -07001538 }
1539 }
1540
1541 j.linter.name = ctx.ModuleName()
Thiébaud Weksteen5c26f812022-05-05 14:49:02 +10001542 j.linter.srcs = append(srcFiles, nonGeneratedSrcJars...)
1543 j.linter.srcJars, _ = android.FilterPathList(srcJars, nonGeneratedSrcJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001544 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1545 j.linter.classes = j.implementationJarFile
Spandan Dasba7e5322022-04-22 17:28:25 +00001546 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1547 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1548 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001549 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001550 j.linter.javaLanguageLevel = flags.javaVersion.String()
1551 j.linter.kotlinLanguageLevel = "1.3"
1552 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1553 j.linter.buildModuleReportZip = true
1554 }
1555 j.linter.lint(ctx)
1556 }
1557
1558 ctx.CheckbuildFile(outputFile)
1559
1560 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1561 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1562 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1563 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1564 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1565 AidlIncludeDirs: j.exportAidlIncludeDirs,
1566 SrcJarArgs: j.srcJarArgs,
1567 SrcJarDeps: j.srcJarDeps,
1568 ExportedPlugins: j.exportedPluginJars,
1569 ExportedPluginClasses: j.exportedPluginClasses,
1570 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1571 JacocoReportClassesFile: j.jacocoReportClassesFile,
1572 })
1573
1574 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1575 j.outputFile = outputFile.WithoutRel()
1576}
1577
Colin Crossa1ff7c62021-09-17 14:11:52 -07001578func (j *Module) useCompose() bool {
1579 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1580}
1581
Cole Faust75fffb12021-06-13 15:23:16 -07001582// Returns a copy of the supplied flags, but with all the errorprone-related
1583// fields copied to the regular build's fields.
1584func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1585 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1586
1587 if len(flags.errorProneExtraJavacFlags) > 0 {
1588 if len(flags.javacFlags) > 0 {
1589 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1590 } else {
1591 flags.javacFlags = flags.errorProneExtraJavacFlags
1592 }
1593 }
1594 return flags
1595}
1596
Jaewoong Jung26342642021-03-17 15:56:23 -07001597func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1598 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1599
1600 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1601 if idx >= 0 {
1602 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1603 jarName += strconv.Itoa(idx)
1604 }
1605
1606 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1607 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1608
1609 if ctx.Config().EmitXrefRules() {
1610 extractionFile := android.PathForModuleOut(ctx, kzipName)
1611 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1612 j.kytheFiles = append(j.kytheFiles, extractionFile)
1613 }
1614
1615 return classes
1616}
1617
1618// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1619// since some of these flags may be used internally.
1620func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1621 for _, flag := range flags {
1622 flag = strings.TrimSpace(flag)
1623
1624 if !strings.HasPrefix(flag, "-") {
1625 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1626 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1627 ctx.PropertyErrorf("kotlincflags",
1628 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1629 } else if inList(flag, config.KotlincIllegalFlags) {
1630 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1631 } else if flag == "-include-runtime" {
1632 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1633 } else {
1634 args := strings.Split(flag, " ")
1635 if args[0] == "-kotlin-home" {
1636 ctx.PropertyErrorf("kotlincflags",
1637 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1638 }
1639 }
1640 }
1641}
1642
1643func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1644 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001645 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001646
1647 var jars android.Paths
1648 if len(srcFiles) > 0 || len(srcJars) > 0 {
1649 // Compile java sources into turbine.jar.
1650 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1651 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1652 if ctx.Failed() {
1653 return nil, nil
1654 }
1655 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001656 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001657 }
1658
1659 jars = append(jars, extraJars...)
1660
1661 // Combine any static header libraries into classes-header.jar. If there is only
1662 // one input jar this step will be skipped.
1663 jars = append(jars, deps.staticHeaderJars...)
1664
1665 // we cannot skip the combine step for now if there is only one jar
1666 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1667 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1668 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1669 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001670 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001671
1672 if j.expandJarjarRules != nil {
1673 // Transform classes.jar into classes-jarjar.jar
1674 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001675 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1676 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001677 if ctx.Failed() {
1678 return nil, nil
1679 }
1680 }
1681
Colin Cross3d56ed52021-11-18 22:23:12 -08001682 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001683}
1684
1685func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001686 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001687
1688 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1689 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1690
1691 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1692
1693 j.jacocoReportClassesFile = jacocoReportClassesFile
1694
1695 return instrumentedJar
1696}
1697
1698func (j *Module) HeaderJars() android.Paths {
1699 if j.headerJarFile == nil {
1700 return nil
1701 }
1702 return android.Paths{j.headerJarFile}
1703}
1704
1705func (j *Module) ImplementationJars() android.Paths {
1706 if j.implementationJarFile == nil {
1707 return nil
1708 }
1709 return android.Paths{j.implementationJarFile}
1710}
1711
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001712func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001713 return j.dexJarFile
1714}
1715
1716func (j *Module) DexJarInstallPath() android.Path {
1717 return j.installFile
1718}
1719
1720func (j *Module) ImplementationAndResourcesJars() android.Paths {
1721 if j.implementationAndResourcesJar == nil {
1722 return nil
1723 }
1724 return android.Paths{j.implementationAndResourcesJar}
1725}
1726
1727func (j *Module) AidlIncludeDirs() android.Paths {
1728 // exportAidlIncludeDirs is type android.Paths already
1729 return j.exportAidlIncludeDirs
1730}
1731
1732func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1733 return j.classLoaderContexts
1734}
1735
1736// Collect information for opening IDE project files in java/jdeps.go.
1737func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1738 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1739 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1740 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1741 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1742 if j.expandJarjarRules != nil {
1743 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1744 }
1745 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001746 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1747 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001748}
1749
1750func (j *Module) CompilerDeps() []string {
1751 jdeps := []string{}
1752 jdeps = append(jdeps, j.properties.Libs...)
1753 jdeps = append(jdeps, j.properties.Static_libs...)
1754 return jdeps
1755}
1756
1757func (j *Module) hasCode(ctx android.ModuleContext) bool {
1758 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1759 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1760}
1761
1762// Implements android.ApexModule
1763func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1764 return j.depIsInSameApex(ctx, dep)
1765}
1766
1767// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001768func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001769 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001770 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001771 return fmt.Errorf("min_sdk_version is not specified")
1772 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001773 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001774 return nil
1775 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001776 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1777 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001778 }
1779 return nil
1780}
1781
1782func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001783 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001784}
1785
Jaewoong Jung26342642021-03-17 15:56:23 -07001786func (j *Module) JacocoReportClassesFile() android.Path {
1787 return j.jacocoReportClassesFile
1788}
1789
1790func (j *Module) IsInstallable() bool {
1791 return Bool(j.properties.Installable)
1792}
1793
1794type sdkLinkType int
1795
1796const (
1797 // TODO(jiyong) rename these for better readability. Make the allowed
1798 // and disallowed link types explicit
1799 // order is important here. See rank()
1800 javaCore sdkLinkType = iota
1801 javaSdk
1802 javaSystem
1803 javaModule
1804 javaSystemServer
1805 javaPlatform
1806)
1807
1808func (lt sdkLinkType) String() string {
1809 switch lt {
1810 case javaCore:
1811 return "core Java API"
1812 case javaSdk:
1813 return "Android API"
1814 case javaSystem:
1815 return "system API"
1816 case javaModule:
1817 return "module API"
1818 case javaSystemServer:
1819 return "system server API"
1820 case javaPlatform:
1821 return "private API"
1822 default:
1823 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1824 }
1825}
1826
1827// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1828// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1829// can't statically depend on modules that use Platform API.
1830func (lt sdkLinkType) rank() int {
1831 return int(lt)
1832}
1833
1834type moduleWithSdkDep interface {
1835 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001836 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001837}
1838
Jiyong Park92315372021-04-02 08:45:46 +09001839func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001840 switch name {
1841 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1842 "stub-annotations", "private-stub-annotations-jar",
1843 "core-lambda-stubs", "core-generated-annotation-stubs":
1844 return javaCore, true
1845 case "android_stubs_current":
1846 return javaSdk, true
1847 case "android_system_stubs_current":
1848 return javaSystem, true
1849 case "android_module_lib_stubs_current":
1850 return javaModule, true
1851 case "android_system_server_stubs_current":
1852 return javaSystemServer, true
1853 case "android_test_stubs_current":
1854 return javaSystem, true
1855 }
1856
1857 if stub, linkType := moduleStubLinkType(name); stub {
1858 return linkType, true
1859 }
1860
Jiyong Park92315372021-04-02 08:45:46 +09001861 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001862 switch ver.Kind {
1863 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001864 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001865 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001866 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001867 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001868 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001869 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001870 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001871 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001872 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001873 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001874 return javaPlatform, false
1875 }
1876
Jiyong Parkf1691d22021-03-29 20:11:58 +09001877 if !ver.Valid() {
1878 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001879 }
1880 return javaSdk, false
1881}
1882
1883// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1884// this module's. See the comment on rank() for details and an example.
1885func (j *Module) checkSdkLinkType(
1886 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1887 if ctx.Host() {
1888 return
1889 }
1890
Jiyong Park92315372021-04-02 08:45:46 +09001891 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001892 if stubs {
1893 return
1894 }
Jiyong Park92315372021-04-02 08:45:46 +09001895 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001896
1897 if myLinkType.rank() < depLinkType.rank() {
1898 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1899 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1900 "property of the source or target module so that target module is built "+
1901 "with the same or smaller API set when compared to the source.",
1902 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1903 }
1904}
1905
1906func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1907 var deps deps
1908
1909 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001910 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001911 if sdkDep.invalidVersion {
1912 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1913 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1914 } else if sdkDep.useFiles {
1915 // sdkDep.jar is actually equivalent to turbine header.jar.
1916 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001917 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001918 deps.aidlPreprocess = sdkDep.aidl
1919 } else {
1920 deps.aidlPreprocess = sdkDep.aidl
1921 }
1922 }
1923
Jiyong Park92315372021-04-02 08:45:46 +09001924 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001925
1926 ctx.VisitDirectDeps(func(module android.Module) {
1927 otherName := ctx.OtherModuleName(module)
1928 tag := ctx.OtherModuleDependencyTag(module)
1929
1930 if IsJniDepTag(tag) {
1931 // Handled by AndroidApp.collectAppDeps
1932 return
1933 }
1934 if tag == certificateTag {
1935 // Handled by AndroidApp.collectAppDeps
1936 return
1937 }
1938
1939 if dep, ok := module.(SdkLibraryDependency); ok {
1940 switch tag {
1941 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001942 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1943 deps.classpath = append(deps.classpath, depHeaderJars...)
1944 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001945 case staticLibTag:
1946 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1947 }
1948 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1949 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1950 if sdkLinkType != javaPlatform &&
1951 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1952 // dep is a sysprop implementation library, but this module is not linking against
1953 // the platform, so it gets the sysprop public stubs library instead. Replace
1954 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1955 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1956 dep = syspropDep.JavaInfo
1957 }
1958 switch tag {
1959 case bootClasspathTag:
1960 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1961 case libTag, instrumentationForTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001962 if _, ok := module.(*Plugin); ok {
1963 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a libs dependency", otherName)
1964 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001965 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001966 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001967 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1968 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1969 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1970 case java9LibTag:
1971 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1972 case staticLibTag:
Sam Delmerico0d1c4a02022-04-26 18:34:55 +00001973 if _, ok := module.(*Plugin); ok {
1974 ctx.ModuleErrorf("a java_plugin (%s) cannot be used as a static_libs dependency", otherName)
1975 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001976 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1977 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1978 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1979 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1980 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1981 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1982 // Turbine doesn't run annotation processors, so any module that uses an
1983 // annotation processor that generates API is incompatible with the turbine
1984 // optimization.
1985 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1986 case pluginTag:
1987 if plugin, ok := module.(*Plugin); ok {
1988 if plugin.pluginProperties.Processor_class != nil {
1989 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1990 } else {
1991 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1992 }
1993 // Turbine doesn't run annotation processors, so any module that uses an
1994 // annotation processor that generates API is incompatible with the turbine
1995 // optimization.
1996 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1997 } else {
1998 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1999 }
2000 case errorpronePluginTag:
2001 if _, ok := module.(*Plugin); ok {
2002 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
2003 } else {
2004 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
2005 }
2006 case exportedPluginTag:
2007 if plugin, ok := module.(*Plugin); ok {
2008 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
2009 if plugin.pluginProperties.Processor_class != nil {
2010 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
2011 }
2012 // Turbine doesn't run annotation processors, so any module that uses an
2013 // annotation processor that generates API is incompatible with the turbine
2014 // optimization.
2015 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
2016 } else {
2017 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
2018 }
2019 case kotlinStdlibTag:
2020 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
2021 case kotlinAnnotationsTag:
2022 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07002023 case kotlinPluginTag:
2024 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002025 case syspropPublicStubDepTag:
2026 // This is a sysprop implementation library, forward the JavaInfoProvider from
2027 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
2028 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
2029 JavaInfo: dep,
2030 })
2031 }
2032 } else if dep, ok := module.(android.SourceFileProducer); ok {
2033 switch tag {
2034 case libTag:
2035 checkProducesJars(ctx, dep)
2036 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002037 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002038 case staticLibTag:
2039 checkProducesJars(ctx, dep)
2040 deps.classpath = append(deps.classpath, dep.Srcs()...)
2041 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2042 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2043 }
2044 } else {
2045 switch tag {
2046 case bootClasspathTag:
2047 // If a system modules dependency has been added to the bootclasspath
2048 // then add its libs to the bootclasspath.
2049 sm := module.(SystemModulesProvider)
2050 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2051
2052 case systemModulesTag:
2053 if deps.systemModules != nil {
2054 panic("Found two system module dependencies")
2055 }
2056 sm := module.(SystemModulesProvider)
2057 outputDir, outputDeps := sm.OutputDirAndDeps()
2058 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002059
2060 case instrumentationForTag:
2061 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 -07002062 }
2063 }
2064
2065 addCLCFromDep(ctx, module, j.classLoaderContexts)
2066 })
2067
2068 return deps
2069}
2070
2071func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2072 deps.processorPath = append(deps.processorPath, pluginJars...)
2073 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2074}
2075
2076// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2077// this interface.
2078type ProvidesUsesLib interface {
2079 ProvidesUsesLib() *string
2080}
2081
2082func (j *Module) ProvidesUsesLib() *string {
2083 return j.usesLibraryProperties.Provides_uses_lib
2084}
satayev1c564cc2021-05-25 19:50:30 +01002085
2086type ModuleWithStem interface {
2087 Stem() string
2088}
2089
2090var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002091
2092func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2093 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002094 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002095 if lib, ok := ctx.Module().(*Library); ok {
2096 javaLibraryBp2Build(ctx, lib)
2097 }
2098 case "java_binary_host":
2099 if binary, ok := ctx.Module().(*Binary); ok {
2100 javaBinaryHostBp2Build(ctx, binary)
2101 }
2102 }
Wei Libafb6d62021-12-10 03:14:59 -08002103}