blob: ddabbc0c3aa51acd0c7806a33c5b3c678df344f4 [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 Duffin39531532022-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
Jaewoong Jung26342642021-03-17 15:56:23 -0700207 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000208 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700209 Target_sdk_version *string
210
211 // Whether to compile against the platform APIs instead of an SDK.
212 // If true, then sdk_version must be empty. The value of this field
Vinh Trand91939e2022-04-18 19:27:17 +0000213 // is ignored when module's type isn't android_app, android_test, or android_test_helper_app.
Jaewoong Jung26342642021-03-17 15:56:23 -0700214 Platform_apis *bool
215
216 Aidl struct {
217 // Top level directories to pass to aidl tool
218 Include_dirs []string
219
220 // Directories rooted at the Android.bp file to pass to aidl tool
221 Local_include_dirs []string
222
223 // directories that should be added as include directories for any aidl sources of modules
224 // that depend on this module, as well as to aidl for this module.
225 Export_include_dirs []string
226
227 // whether to generate traces (for systrace) for this interface
228 Generate_traces *bool
229
230 // whether to generate Binder#GetTransaction name method.
231 Generate_get_transaction_name *bool
232
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100233 // whether all interfaces should be annotated with required permissions.
234 Enforce_permissions *bool
235
236 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
237 Enforce_permissions_exceptions []string `android:"path"`
238
Jaewoong Jung26342642021-03-17 15:56:23 -0700239 // list of flags that will be passed to the AIDL compiler
240 Flags []string
241 }
242
243 // If true, export a copy of the module as a -hostdex module for host testing.
244 Hostdex *bool
245
246 Target struct {
247 Hostdex struct {
248 // Additional required dependencies to add to -hostdex modules.
249 Required []string
250 }
251 }
252
253 // When targeting 1.9 and above, override the modules to use with --system,
254 // otherwise provides defaults libraries to add to the bootclasspath.
255 System_modules *string
256
Jaewoong Jung26342642021-03-17 15:56:23 -0700257 IsSDKLibrary bool `blueprint:"mutated"`
258
259 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
260 // Defaults to false.
261 V4_signature *bool
262
263 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
264 // public stubs library.
265 SyspropPublicStub string `blueprint:"mutated"`
Paul Duffinb5e3c982022-07-27 16:27:42 +0000266
267 HiddenAPIPackageProperties
268 HiddenAPIFlagFileProperties
Jaewoong Jung26342642021-03-17 15:56:23 -0700269}
270
Jooyung Han01d80d82022-01-08 12:16:32 +0900271// Device properties that can be overridden by overriding module (e.g. override_android_app)
272type OverridableDeviceProperties struct {
273 // set the name of the output. If not set, `name` is used.
274 // To override a module with this property set, overriding module might need to set this as well.
275 // Otherwise, both the overridden and the overriding modules will have the same output name, which
276 // can cause the duplicate output error.
277 Stem *string
278}
279
Jaewoong Jung26342642021-03-17 15:56:23 -0700280// Functionality common to Module and Import
281//
282// It is embedded in Module so its functionality can be used by methods in Module
283// but it is currently only initialized by Import and Library.
284type embeddableInModuleAndImport struct {
285
286 // Functionality related to this being used as a component of a java_sdk_library.
287 EmbeddableSdkLibraryComponent
288}
289
Paul Duffin71b33cc2021-06-23 11:39:47 +0100290func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
291 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700292}
293
294// Module/Import's DepIsInSameApex(...) delegates to this method.
295//
296// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
297// the one provided by ApexModuleBase.
298func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
299 // dependencies other than the static linkage are all considered crossing APEX boundary
300 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
301 return true
302 }
303 return false
304}
305
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100306// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
307// or an invalid path describing the reason it is invalid.
308//
309// It is unset if a dex jar isn't applicable, i.e. no build rule has been
310// requested to create one.
311//
312// If a dex jar has been requested to be built then it is set, and it may be
313// either a valid android.Path, or invalid with a reason message. The latter
314// happens if the source that should produce the dex file isn't able to.
315//
316// E.g. it is invalid with a reason message if there is a prebuilt APEX that
317// could produce the dex jar through a deapexer module, but the APEX isn't
318// installable so doing so wouldn't be safe.
319type OptionalDexJarPath struct {
320 isSet bool
321 path android.OptionalPath
322}
323
324// IsSet returns true if a path has been set, either invalid or valid.
325func (o OptionalDexJarPath) IsSet() bool {
326 return o.isSet
327}
328
329// Valid returns true if there is a path that is valid.
330func (o OptionalDexJarPath) Valid() bool {
331 return o.isSet && o.path.Valid()
332}
333
334// Path returns the valid path, or panics if it's either not set or is invalid.
335func (o OptionalDexJarPath) Path() android.Path {
336 if !o.isSet {
337 panic("path isn't set")
338 }
339 return o.path.Path()
340}
341
342// PathOrNil returns the path if it's set and valid, or else nil.
343func (o OptionalDexJarPath) PathOrNil() android.Path {
344 if o.Valid() {
345 return o.Path()
346 }
347 return nil
348}
349
350// InvalidReason returns the reason for an invalid path, which is never "". It
351// returns "" for an unset or valid path.
352func (o OptionalDexJarPath) InvalidReason() string {
353 if !o.isSet {
354 return ""
355 }
356 return o.path.InvalidReason()
357}
358
359func (o OptionalDexJarPath) String() string {
360 if !o.isSet {
361 return "<unset>"
362 }
363 return o.path.String()
364}
365
366// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
367func makeUnsetDexJarPath() OptionalDexJarPath {
368 return OptionalDexJarPath{isSet: false}
369}
370
371// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
372// the given OptionalPath, which may be valid or invalid.
373func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
374 return OptionalDexJarPath{isSet: true, path: path}
375}
376
377// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
378// valid given path. It returns an unset OptionalDexJarPath if the given path is
379// nil.
380func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
381 if path == nil {
382 return makeUnsetDexJarPath()
383 }
384 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
385}
386
Jaewoong Jung26342642021-03-17 15:56:23 -0700387// Module contains the properties and members used by all java module types
388type Module struct {
389 android.ModuleBase
390 android.DefaultableModuleBase
391 android.ApexModuleBase
392 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800393 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700394
395 // Functionality common to Module and Import.
396 embeddableInModuleAndImport
397
398 properties CommonProperties
399 protoProperties android.ProtoProperties
400 deviceProperties DeviceProperties
401
Jooyung Han01d80d82022-01-08 12:16:32 +0900402 overridableDeviceProperties OverridableDeviceProperties
403
Jaewoong Jung26342642021-03-17 15:56:23 -0700404 // jar file containing header classes including static library dependencies, suitable for
405 // inserting into the bootclasspath/classpath of another compile
406 headerJarFile android.Path
407
408 // jar file containing implementation classes including static library dependencies but no
409 // resources
410 implementationJarFile android.Path
411
412 // jar file containing only resources including from static library dependencies
413 resourceJar android.Path
414
415 // args and dependencies to package source files into a srcjar
416 srcJarArgs []string
417 srcJarDeps android.Paths
418
419 // jar file containing implementation classes and resources including static library
420 // dependencies
421 implementationAndResourcesJar android.Path
422
423 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100424 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700425
426 // output file containing uninstrumented classes that will be instrumented by jacoco
427 jacocoReportClassesFile android.Path
428
429 // output file of the module, which may be a classes jar or a dex jar
430 outputFile android.Path
431 extraOutputFiles android.Paths
432
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100433 exportAidlIncludeDirs android.Paths
434 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700435
436 logtagsSrcs android.Paths
437
438 // installed file for binary dependency
439 installFile android.Path
440
Colin Cross3108ce12021-11-10 14:38:50 -0800441 // installed file for hostdex copy
442 hostdexInstallFile android.InstallPath
443
Jaewoong Jung26342642021-03-17 15:56:23 -0700444 // list of .java files and srcjars that was passed to javac
445 compiledJavaSrcs android.Paths
446 compiledSrcJars android.Paths
447
448 // manifest file to use instead of properties.Manifest
449 overrideManifest android.OptionalPath
450
451 // map of SDK version to class loader context
452 classLoaderContexts dexpreopt.ClassLoaderContextMap
453
454 // list of plugins that this java module is exporting
455 exportedPluginJars android.Paths
456
457 // list of plugins that this java module is exporting
458 exportedPluginClasses []string
459
460 // if true, the exported plugins generate API and require disabling turbine.
461 exportedDisableTurbine bool
462
463 // list of source files, collected from srcFiles with unique java and all kt files,
464 // will be used by android.IDEInfo struct
465 expandIDEInfoCompiledSrcs []string
466
467 // expanded Jarjar_rules
468 expandJarjarRules android.Path
469
Jaewoong Jung26342642021-03-17 15:56:23 -0700470 // Extra files generated by the module type to be added as java resources.
471 extraResources android.Paths
472
473 hiddenAPI
474 dexer
475 dexpreopter
476 usesLibrary
477 linter
478
479 // list of the xref extraction files
480 kytheFiles android.Paths
481
482 // Collect the module directory for IDE info in java/jdeps.go.
483 modulePaths []string
484
485 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900486
487 sdkVersion android.SdkSpec
488 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000489 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400490
491 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700492}
493
Jiyong Park92315372021-04-02 08:45:46 +0900494func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
495 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900496 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700497 return nil
498 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900499 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000500 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700501 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
502 } else {
503 // Treat stable core platform as stable.
504 return nil
505 }
506 } else {
507 return fmt.Errorf("non stable SDK %v", sdkVersion)
508 }
509}
510
511// checkSdkVersions enforces restrictions around SDK dependencies.
512func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
513 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900514 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900515 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700516 ctx.PropertyErrorf("sdk_version",
517 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
518 }
519 }
520 }
521
522 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
523 // See rank() for details.
524 ctx.VisitDirectDeps(func(module android.Module) {
525 tag := ctx.OtherModuleDependencyTag(module)
526 switch module.(type) {
527 // TODO(satayev): cover other types as well, e.g. imports
528 case *Library, *AndroidLibrary:
529 switch tag {
530 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
531 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
532 }
533 }
534 })
535}
536
537func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900538 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700539 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900540 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700541 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000542 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 -0700543 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000544 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 -0700545 }
546
547 }
548}
549
550func (j *Module) addHostProperties() {
551 j.AddProperties(
552 &j.properties,
553 &j.protoProperties,
554 &j.usesLibraryProperties,
555 )
556}
557
558func (j *Module) addHostAndDeviceProperties() {
559 j.addHostProperties()
560 j.AddProperties(
561 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900562 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700563 &j.dexer.dexProperties,
564 &j.dexpreoptProperties,
565 &j.linter.properties,
566 )
567}
568
Paul Duffinb5e3c982022-07-27 16:27:42 +0000569// provideHiddenAPIPropertyInfo populates a HiddenAPIPropertyInfo from hidden API properties and
570// makes it available through the hiddenAPIPropertyInfoProvider.
571func (j *Module) provideHiddenAPIPropertyInfo(ctx android.ModuleContext) {
572 hiddenAPIInfo := newHiddenAPIPropertyInfo()
573
574 // Populate with flag file paths from the properties.
575 hiddenAPIInfo.extractFlagFilesFromProperties(ctx, &j.deviceProperties.HiddenAPIFlagFileProperties)
576
577 // Populate with package rules from the properties.
578 hiddenAPIInfo.extractPackageRulesFromProperties(&j.deviceProperties.HiddenAPIPackageProperties)
579
580 ctx.SetProvider(hiddenAPIPropertyInfoProvider, hiddenAPIInfo)
581}
582
Jaewoong Jung26342642021-03-17 15:56:23 -0700583func (j *Module) OutputFiles(tag string) (android.Paths, error) {
584 switch tag {
585 case "":
586 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
587 case android.DefaultDistTag:
588 return android.Paths{j.outputFile}, nil
589 case ".jar":
590 return android.Paths{j.implementationAndResourcesJar}, nil
591 case ".proguard_map":
592 if j.dexer.proguardDictionary.Valid() {
593 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
594 }
595 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
596 default:
597 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
598 }
599}
600
601var _ android.OutputFileProducer = (*Module)(nil)
602
603func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
604 initJavaModule(module, hod, false)
605}
606
607func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
608 initJavaModule(module, hod, true)
609}
610
611func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
612 multilib := android.MultilibCommon
613 if multiTargets {
614 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
615 } else {
616 android.InitAndroidArchModule(module, hod, multilib)
617 }
618 android.InitDefaultableModule(module)
619}
620
621func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
622 return j.properties.Instrument &&
623 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
624 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
625}
626
627func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
Paul Duffin39531532022-05-03 00:28:40 +0000628 return j.properties.Supports_static_instrumentation &&
629 j.shouldInstrument(ctx) &&
Jaewoong Jung26342642021-03-17 15:56:23 -0700630 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
631 ctx.Config().UnbundledBuild())
632}
633
634func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
635 // Force enable the instrumentation for java code that is built for APEXes ...
636 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
637 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
638 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
639 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
640 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
641 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
642 return true
643 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
644 return true
645 }
646 }
647 return false
648}
649
Jiyong Park92315372021-04-02 08:45:46 +0900650func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
651 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700652}
653
Jiyong Parkf1691d22021-03-29 20:11:58 +0900654func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700655 return proptools.String(j.deviceProperties.System_modules)
656}
657
Jiyong Park92315372021-04-02 08:45:46 +0900658func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700659 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900660 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700661 }
Jiyong Park92315372021-04-02 08:45:46 +0900662 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700663}
664
satayev0a420e72021-11-29 17:25:52 +0000665func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
666 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
667 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
668 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
669 return android.SdkSpecFrom(ctx, maxSdkVersion)
670}
671
Jiyong Parkf1691d22021-03-29 20:11:58 +0900672func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900673 return j.minSdkVersion.Raw
674}
675
676func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
677 if j.deviceProperties.Target_sdk_version != nil {
678 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
679 }
680 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700681}
682
683func (j *Module) AvailableFor(what string) bool {
684 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
685 // Exception: for hostdex: true libraries, the platform variant is created
686 // even if it's not marked as available to platform. In that case, the platform
687 // variant is used only for the hostdex and not installed to the device.
688 return true
689 }
690 return j.ApexModuleBase.AvailableFor(what)
691}
692
693func (j *Module) deps(ctx android.BottomUpMutatorContext) {
694 if ctx.Device() {
695 j.linter.deps(ctx)
696
Jiyong Parkf1691d22021-03-29 20:11:58 +0900697 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700698
699 if j.deviceProperties.SyspropPublicStub != "" {
700 // This is a sysprop implementation library that has a corresponding sysprop public
701 // stubs library, and a dependency on it so that dependencies on the implementation can
702 // be forwarded to the public stubs library when necessary.
703 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
704 }
705 }
706
707 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
708 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
709
710 // Add dependency on libraries that provide additional hidden api annotations.
711 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
712
713 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
714 // Require java_sdk_library at inter-partition java dependency to ensure stable
715 // interface between partitions. If inter-partition java_library dependency is detected,
716 // raise build error because java_library doesn't have a stable interface.
717 //
718 // Inputs:
719 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
720 // if true, enable enforcement
721 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
722 // exception list of java_library names to allow inter-partition dependency
723 for idx := range j.properties.Libs {
724 if libDeps[idx] == nil {
725 continue
726 }
727
728 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
729 // java_sdk_library is always allowed at inter-partition dependency.
730 // So, skip check.
731 if _, ok := javaDep.(*SdkLibrary); ok {
732 continue
733 }
734
735 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
736 }
737 }
738 }
739
740 // For library dependencies that are component libraries (like stubs), add the implementation
741 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
742 for _, dep := range libDeps {
743 if dep != nil {
744 if component, ok := dep.(SdkLibraryComponentDependency); ok {
745 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100746 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100747 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
748 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100749 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700750 }
751 }
752 }
753 }
754
755 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
756 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
757 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
758
759 android.ProtoDeps(ctx, &j.protoProperties)
760 if j.hasSrcExt(".proto") {
761 protoDeps(ctx, &j.protoProperties)
762 }
763
764 if j.hasSrcExt(".kt") {
765 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
766 // Kotlin files
767 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
768 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
769 if len(j.properties.Plugins) > 0 {
770 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
771 }
772 }
773
774 // Framework libraries need special handling in static coverage builds: they should not have
775 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
776 // the same jacoco classes coming from different bootclasspath jars.
777 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
778 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
779 j.properties.Instrument = true
780 }
781 } else if j.shouldInstrumentStatic(ctx) {
782 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
783 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700784
785 if j.useCompose() {
786 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
787 "androidx.compose.compiler_compiler-hosted")
788 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700789}
790
791func hasSrcExt(srcs []string, ext string) bool {
792 for _, src := range srcs {
793 if filepath.Ext(src) == ext {
794 return true
795 }
796 }
797
798 return false
799}
800
801func (j *Module) hasSrcExt(ext string) bool {
802 return hasSrcExt(j.properties.Srcs, ext)
803}
804
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100805func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
806 var flags string
807
808 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
809 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
810 flags = "-Wmissing-permission-annotation -Werror"
811 }
812 }
813 return flags
814}
815
Jaewoong Jung26342642021-03-17 15:56:23 -0700816func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
817 aidlIncludeDirs android.Paths) (string, android.Paths) {
818
819 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
820 aidlIncludes = append(aidlIncludes,
821 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
822 aidlIncludes = append(aidlIncludes,
823 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
824
825 var flags []string
826 var deps android.Paths
827
828 flags = append(flags, j.deviceProperties.Aidl.Flags...)
829
830 if aidlPreprocess.Valid() {
831 flags = append(flags, "-p"+aidlPreprocess.String())
832 deps = append(deps, aidlPreprocess.Path())
833 } else if len(aidlIncludeDirs) > 0 {
834 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
835 }
836
837 if len(j.exportAidlIncludeDirs) > 0 {
838 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
839 }
840
841 if len(aidlIncludes) > 0 {
842 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
843 }
844
845 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
846 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
847 flags = append(flags, "-I"+src.String())
848 }
849
850 if Bool(j.deviceProperties.Aidl.Generate_traces) {
851 flags = append(flags, "-t")
852 }
853
854 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
855 flags = append(flags, "--transaction_names")
856 }
857
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100858 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
859 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
860 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
861 }
862
Jooyung Han07f70c02021-11-06 07:08:45 +0900863 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
864 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
865
Jaewoong Jung26342642021-03-17 15:56:23 -0700866 return strings.Join(flags, " "), deps
867}
868
869func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
870
871 var flags javaBuilderFlags
872
873 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900874 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700875
Cole Faust2b1536e2021-06-18 12:25:54 -0700876 epEnabled := j.properties.Errorprone.Enabled
877 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700878 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
879 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
880 }
881
882 errorProneFlags := []string{
883 "-Xplugin:ErrorProne",
884 "${config.ErrorProneChecks}",
885 }
886 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
887
Colin Cross8bf6cad2022-02-28 13:07:03 -0800888 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700889 "'" + strings.Join(errorProneFlags, " ") + "'"
890 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
891 }
892
893 // classpath
894 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
895 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700896 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700897 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
898 flags.processorPath = append(flags.processorPath, deps.processorPath...)
899 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
900
901 flags.processors = append(flags.processors, deps.processorClasses...)
902 flags.processors = android.FirstUniqueStrings(flags.processors)
903
904 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900905 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700906 // Give host-side tools a version of OpenJDK's standard libraries
907 // close to what they're targeting. As of Dec 2017, AOSP is only
908 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
909 //
910 // When building with OpenJDK 8, the following should have no
911 // effect since those jars would be available by default.
912 //
913 // When building with OpenJDK 9 but targeting a version < 1.8,
914 // putting them on the bootclasspath means that:
915 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
916 // b) references to existing APIs are not reinterpreted in an
917 // OpenJDK 9-specific way, eg. calls to subclasses of
918 // java.nio.Buffer as in http://b/70862583
919 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
920 flags.bootClasspath = append(flags.bootClasspath,
921 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
922 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
923 if Bool(j.properties.Use_tools_jar) {
924 flags.bootClasspath = append(flags.bootClasspath,
925 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
926 }
927 }
928
929 // systemModules
930 flags.systemModules = deps.systemModules
931
932 // aidl flags.
933 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
934
935 return flags
936}
937
938func (j *Module) collectJavacFlags(
939 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
940 // javac flags.
941 javacFlags := j.properties.Javacflags
942
943 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
944 // For non-host binaries, override the -g flag passed globally to remove
945 // local variable debug info to reduce disk and memory usage.
946 javacFlags = append(javacFlags, "-g:source,lines")
947 }
948 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
949
950 if flags.javaVersion.usesJavaModules() {
951 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
952
953 if j.properties.Patch_module != nil {
954 // Manually specify build directory in case it is not under the repo root.
955 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
956 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200957 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700958
959 // b/150878007
960 //
961 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
962 // execution root for --patch-module. If this javac command line is
963 // invoked within Bazel's execution root working directory, the top
964 // level directories (e.g. libcore/, tools/, frameworks/) are all
965 // symlinks. JDK9 javac does not traverse into symlinks, which causes
966 // --patch-module to fail source file lookups when invoked in the
967 // execution root.
968 //
969 // Short of patching javac or enumerating *all* directories as possible
970 // input dirs, manually add the top level dir of the source files to be
971 // compiled.
972 topLevelDirs := map[string]bool{}
973 for _, srcFilePath := range srcFiles {
974 srcFileParts := strings.Split(srcFilePath.String(), "/")
975 // Ignore source files that are already in the top level directory
976 // as well as generated files in the out directory. The out
977 // directory may be an absolute path, which means srcFileParts[0] is the
978 // empty string, so check that as well. Note that "out" in Bazel's execution
979 // root is *not* a symlink, which doesn't cause problems for --patch-modules
980 // anyway, so it's fine to not apply this workaround for generated
981 // source files.
982 if len(srcFileParts) > 1 &&
983 srcFileParts[0] != "" &&
984 srcFileParts[0] != "out" {
985 topLevelDirs[srcFileParts[0]] = true
986 }
987 }
988 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
989
990 classPath := flags.classpath.FormJavaClassPath("")
991 if classPath != "" {
992 patchPaths = append(patchPaths, classPath)
993 }
994 javacFlags = append(
995 javacFlags,
996 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
997 }
998 }
999
1000 if len(javacFlags) > 0 {
1001 // optimization.
1002 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
1003 flags.javacFlags = "$javacFlags"
1004 }
1005
1006 return flags
1007}
1008
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001009func (j *Module) AddJSONData(d *map[string]interface{}) {
1010 (&j.ModuleBase).AddJSONData(d)
1011 (*d)["Java"] = map[string]interface{}{
1012 "SourceExtensions": j.sourceExtensions,
1013 }
1014
1015}
1016
Jaewoong Jung26342642021-03-17 15:56:23 -07001017func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
1018 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
1019
1020 deps := j.collectDeps(ctx)
1021 flags := j.collectBuilderFlags(ctx, deps)
1022
1023 if flags.javaVersion.usesJavaModules() {
1024 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1025 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001026
Jaewoong Jung26342642021-03-17 15:56:23 -07001027 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001028 j.sourceExtensions = []string{}
1029 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1030 if hasSrcExt(srcFiles.Strings(), ext) {
1031 j.sourceExtensions = append(j.sourceExtensions, ext)
1032 }
1033 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001034 if hasSrcExt(srcFiles.Strings(), ".proto") {
1035 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1036 }
1037
1038 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1039 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1040 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1041 }
1042
1043 srcFiles = j.genSources(ctx, srcFiles, flags)
1044
1045 // Collect javac flags only after computing the full set of srcFiles to
1046 // ensure that the --patch-module lookup paths are complete.
1047 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1048
1049 srcJars := srcFiles.FilterByExt(".srcjar")
1050 srcJars = append(srcJars, deps.srcJars...)
1051 if aaptSrcJar != nil {
1052 srcJars = append(srcJars, aaptSrcJar)
1053 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001054 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001055
1056 if j.properties.Jarjar_rules != nil {
1057 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1058 }
1059
1060 jarName := ctx.ModuleName() + ".jar"
1061
1062 javaSrcFiles := srcFiles.FilterByExt(".java")
1063 var uniqueSrcFiles android.Paths
1064 set := make(map[string]bool)
1065 for _, v := range javaSrcFiles {
1066 if _, found := set[v.String()]; !found {
1067 set[v.String()] = true
1068 uniqueSrcFiles = append(uniqueSrcFiles, v)
1069 }
1070 }
1071
Colin Crossb5db4012022-03-28 17:12:39 -07001072 // We don't currently run annotation processors in turbine, which means we can't use turbine
1073 // generated header jars when an annotation processor that generates API is enabled. One
1074 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1075 // is used to run all of the annotation processors.
1076 disableTurbine := deps.disableTurbine
1077
Jaewoong Jung26342642021-03-17 15:56:23 -07001078 // Collect .java files for AIDEGen
1079 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1080
1081 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001082 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001083
1084 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001085 // When using kotlin sources turbine is used to generate annotation processor sources,
1086 // including for annotation processors that generate API, so we can use turbine for
1087 // java sources too.
1088 disableTurbine = false
1089
Jaewoong Jung26342642021-03-17 15:56:23 -07001090 // user defined kotlin flags.
1091 kotlincFlags := j.properties.Kotlincflags
1092 CheckKotlincFlags(ctx, kotlincFlags)
1093
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001094 // Workaround for KT-46512
1095 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001096
1097 // If there are kotlin files, compile them first but pass all the kotlin and java files
1098 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1099 // won't emit any classes for them.
1100 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1101 if ctx.Device() {
1102 kotlincFlags = append(kotlincFlags, "-no-jdk")
1103 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001104
1105 for _, plugin := range deps.kotlinPlugins {
1106 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1107 }
1108 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1109
Jaewoong Jung26342642021-03-17 15:56:23 -07001110 if len(kotlincFlags) > 0 {
1111 // optimization.
1112 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1113 flags.kotlincFlags += "$kotlincFlags"
1114 }
1115
1116 var kotlinSrcFiles android.Paths
1117 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1118 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1119
1120 // Collect .kt files for AIDEGen
1121 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1122 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1123
1124 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1125 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1126
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001127 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
1128
Jaewoong Jung26342642021-03-17 15:56:23 -07001129 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1130 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1131
Isaac Chioua23d9942022-04-06 06:14:38 +00001132 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001133 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001134 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1135 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1136 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1137 srcJars = append(srcJars, kaptSrcJar)
1138 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001139 // Disable annotation processing in javac, it's already been handled by kapt
1140 flags.processorPath = nil
1141 flags.processors = nil
1142 }
1143
1144 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001145 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1146 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001147 if ctx.Failed() {
1148 return
1149 }
1150
Isaac Chioua23d9942022-04-06 06:14:38 +00001151 // Make javac rule depend on the kotlinc rule
1152 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1153
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001155 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1156
Jaewoong Jung26342642021-03-17 15:56:23 -07001157 // Jar kotlin classes into the final jar after javac
1158 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1159 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross220a9a12022-03-28 17:08:01 -07001160 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001161 } else {
1162 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001163 }
1164 }
1165
1166 jars := append(android.Paths(nil), kotlinJars...)
1167
1168 // Store the list of .java files that was passed to javac
1169 j.compiledJavaSrcs = uniqueSrcFiles
1170 j.compiledSrcJars = srcJars
1171
1172 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001173 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001174 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001175 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1176 enableSharding = true
1177 // Formerly, there was a check here that prevented annotation processors
1178 // from being used when sharding was enabled, as some annotation processors
1179 // do not function correctly in sharded environments. It was removed to
1180 // allow for the use of annotation processors that do function correctly
1181 // with sharding enabled. See: b/77284273.
1182 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001183 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001184 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001185 if ctx.Failed() {
1186 return
1187 }
1188 }
1189 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1190 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001191 if Bool(j.properties.Errorprone.Enabled) {
1192 // If error-prone is enabled, enable errorprone flags on the regular
1193 // build.
1194 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001195 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001196 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1197 // a new jar file just for compiling with the errorprone compiler to.
1198 // This is because we don't want to cause the java files to get completely
1199 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1200 // We also don't want to run this if errorprone is enabled by default for
1201 // this module, or else we could have duplicated errorprone messages.
1202 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001203 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001204
1205 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1206 "errorprone", "errorprone")
1207
Jaewoong Jung26342642021-03-17 15:56:23 -07001208 extraJarDeps = append(extraJarDeps, errorprone)
1209 }
1210
1211 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001212 if headerJarFileWithoutDepsOrJarjar != nil {
1213 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1214 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001215 shardSize := int(*(j.properties.Javac_shard_size))
1216 var shardSrcs []android.Paths
1217 if len(uniqueSrcFiles) > 0 {
1218 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1219 for idx, shardSrc := range shardSrcs {
1220 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1221 nil, flags, extraJarDeps)
1222 jars = append(jars, classes)
1223 }
1224 }
1225 if len(srcJars) > 0 {
1226 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1227 nil, srcJars, flags, extraJarDeps)
1228 jars = append(jars, classes)
1229 }
1230 } else {
1231 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1232 jars = append(jars, classes)
1233 }
1234 if ctx.Failed() {
1235 return
1236 }
1237 }
1238
1239 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1240
1241 var includeSrcJar android.WritablePath
1242 if Bool(j.properties.Include_srcs) {
1243 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1244 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1245 }
1246
1247 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1248 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1249 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1250 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1251
1252 var resArgs []string
1253 var resDeps android.Paths
1254
1255 resArgs = append(resArgs, dirArgs...)
1256 resDeps = append(resDeps, dirDeps...)
1257
1258 resArgs = append(resArgs, fileArgs...)
1259 resDeps = append(resDeps, fileDeps...)
1260
1261 resArgs = append(resArgs, extraArgs...)
1262 resDeps = append(resDeps, extraDeps...)
1263
1264 if len(resArgs) > 0 {
1265 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1266 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1267 j.resourceJar = resourceJar
1268 if ctx.Failed() {
1269 return
1270 }
1271 }
1272
1273 var resourceJars android.Paths
1274 if j.resourceJar != nil {
1275 resourceJars = append(resourceJars, j.resourceJar)
1276 }
1277 if Bool(j.properties.Include_srcs) {
1278 resourceJars = append(resourceJars, includeSrcJar)
1279 }
1280 resourceJars = append(resourceJars, deps.staticResourceJars...)
1281
1282 if len(resourceJars) > 1 {
1283 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1284 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1285 false, nil, nil)
1286 j.resourceJar = combinedJar
1287 } else if len(resourceJars) == 1 {
1288 j.resourceJar = resourceJars[0]
1289 }
1290
1291 if len(deps.staticJars) > 0 {
1292 jars = append(jars, deps.staticJars...)
1293 }
1294
1295 manifest := j.overrideManifest
1296 if !manifest.Valid() && j.properties.Manifest != nil {
1297 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1298 }
1299
1300 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1301 if len(services) > 0 {
1302 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1303 var zipargs []string
1304 for _, file := range services {
1305 serviceFile := file.String()
1306 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1307 }
1308 rule := zip
1309 args := map[string]string{
1310 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1311 }
1312 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1313 rule = zipRE
1314 args["implicits"] = strings.Join(services.Strings(), ",")
1315 }
1316 ctx.Build(pctx, android.BuildParams{
1317 Rule: rule,
1318 Output: servicesJar,
1319 Implicits: services,
1320 Args: args,
1321 })
1322 jars = append(jars, servicesJar)
1323 }
1324
1325 // Combine the classes built from sources, any manifests, and any static libraries into
1326 // classes.jar. If there is only one input jar this step will be skipped.
1327 var outputFile android.OutputPath
1328
1329 if len(jars) == 1 && !manifest.Valid() {
1330 // Optimization: skip the combine step as there is nothing to do
1331 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1332 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1333 // any if len(jars) == 1.
1334
1335 // Transform the single path to the jar into an OutputPath as that is required by the following
1336 // code.
1337 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1338 // The path contains an embedded OutputPath so reuse that.
1339 outputFile = moduleOutPath.OutputPath
1340 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1341 // The path is an OutputPath so reuse it directly.
1342 outputFile = outputPath
1343 } else {
1344 // The file is not in the out directory so create an OutputPath into which it can be copied
1345 // and which the following code can use to refer to it.
1346 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1347 ctx.Build(pctx, android.BuildParams{
1348 Rule: android.Cp,
1349 Input: jars[0],
1350 Output: combinedJar,
1351 })
1352 outputFile = combinedJar.OutputPath
1353 }
1354 } else {
1355 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1356 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1357 false, nil, nil)
1358 outputFile = combinedJar.OutputPath
1359 }
1360
1361 // jarjar implementation jar if necessary
1362 if j.expandJarjarRules != nil {
1363 // Transform classes.jar into classes-jarjar.jar
1364 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1365 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1366 outputFile = jarjarFile
1367
1368 // jarjar resource jar if necessary
1369 if j.resourceJar != nil {
1370 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1371 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1372 j.resourceJar = resourceJarJarFile
1373 }
1374
1375 if ctx.Failed() {
1376 return
1377 }
1378 }
1379
1380 // Check package restrictions if necessary.
1381 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001382 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001383 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001384
1385 // Create a rule to copy the output jar to another path and add a validate dependency that
1386 // will check that the jar only contains the permitted packages. The new location will become
1387 // the output file of this module.
1388 inputFile := outputFile
1389 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1390 ctx.Build(pctx, android.BuildParams{
1391 Rule: android.Cp,
1392 Input: inputFile,
1393 Output: outputFile,
1394 // Make sure that any dependency on the output file will cause ninja to run the package check
1395 // rule.
1396 Validation: pkgckFile,
1397 })
1398
1399 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001400 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001401
1402 if ctx.Failed() {
1403 return
1404 }
1405 }
1406
1407 j.implementationJarFile = outputFile
1408 if j.headerJarFile == nil {
1409 j.headerJarFile = j.implementationJarFile
1410 }
1411
1412 if j.shouldInstrumentInApex(ctx) {
1413 j.properties.Instrument = true
1414 }
1415
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001416 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1417 specs := j.jacocoModuleToZipCommand(ctx)
1418 if ctx.Failed() {
1419 return
1420 }
1421
Jaewoong Jung26342642021-03-17 15:56:23 -07001422 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001423 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001424 }
1425
1426 // merge implementation jar with resources if necessary
1427 implementationAndResourcesJar := outputFile
1428 if j.resourceJar != nil {
1429 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1430 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1431 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1432 false, nil, nil)
1433 implementationAndResourcesJar = combinedJar
1434 }
1435
1436 j.implementationAndResourcesJar = implementationAndResourcesJar
1437
1438 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
Paul Duffin029d7202022-06-29 10:15:52 +00001439 compileDex := j.dexProperties.Compile_dex
Jaewoong Jung26342642021-03-17 15:56:23 -07001440 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1441 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
Paul Duffin029d7202022-06-29 10:15:52 +00001442 if compileDex == nil {
1443 compileDex = proptools.BoolPtr(true)
Jaewoong Jung26342642021-03-17 15:56:23 -07001444 }
1445 if j.deviceProperties.Hostdex == nil {
1446 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1447 }
1448 }
1449
Paul Duffin029d7202022-06-29 10:15:52 +00001450 if ctx.Device() && (Bool(j.properties.Installable) || Bool(compileDex)) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001451 if j.hasCode(ctx) {
1452 if j.shouldInstrumentStatic(ctx) {
1453 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1454 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1455 }
1456 // Dex compilation
1457 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001458 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001459 if ctx.Failed() {
1460 return
1461 }
1462
Jaewoong Jung26342642021-03-17 15:56:23 -07001463 // merge dex jar with resources if necessary
1464 if j.resourceJar != nil {
1465 jars := android.Paths{dexOutputFile, j.resourceJar}
1466 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1467 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1468 false, nil, nil)
1469 if *j.dexProperties.Uncompress_dex {
1470 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1471 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1472 dexOutputFile = combinedAlignedJar
1473 } else {
1474 dexOutputFile = combinedJar
1475 }
1476 }
1477
Paul Duffin4de94502021-05-16 05:21:16 +01001478 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001479
1480 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001481
1482 // Encode hidden API flags in dex file, if needed.
1483 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1484
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001485 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001486
1487 // Dexpreopting
1488 j.dexpreopt(ctx, dexOutputFile)
1489
1490 outputFile = dexOutputFile
1491 } else {
1492 // There is no code to compile into a dex jar, make sure the resources are propagated
1493 // to the APK if this is an app.
1494 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001495 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001496 }
1497
1498 if ctx.Failed() {
1499 return
1500 }
1501 } else {
1502 outputFile = implementationAndResourcesJar
1503 }
1504
1505 if ctx.Device() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001506 lintSDKVersion := func(sdkSpec android.SdkSpec) android.ApiLevel {
Jiyong Park54105c42021-03-31 18:17:53 +09001507 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001508 return v
Jaewoong Jung26342642021-03-17 15:56:23 -07001509 } else {
Spandan Dasa3264ef2022-04-22 17:28:25 +00001510 return ctx.Config().DefaultAppTargetSdk(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 }
1512 }
1513
1514 j.linter.name = ctx.ModuleName()
1515 j.linter.srcs = srcFiles
1516 j.linter.srcJars = srcJars
1517 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1518 j.linter.classes = j.implementationJarFile
Spandan Dasa3264ef2022-04-22 17:28:25 +00001519 j.linter.minSdkVersion = lintSDKVersion(j.MinSdkVersion(ctx))
1520 j.linter.targetSdkVersion = lintSDKVersion(j.TargetSdkVersion(ctx))
1521 j.linter.compileSdkVersion = lintSDKVersion(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001522 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001523 j.linter.javaLanguageLevel = flags.javaVersion.String()
1524 j.linter.kotlinLanguageLevel = "1.3"
1525 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1526 j.linter.buildModuleReportZip = true
1527 }
1528 j.linter.lint(ctx)
1529 }
1530
1531 ctx.CheckbuildFile(outputFile)
1532
1533 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1534 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1535 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1536 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1537 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1538 AidlIncludeDirs: j.exportAidlIncludeDirs,
1539 SrcJarArgs: j.srcJarArgs,
1540 SrcJarDeps: j.srcJarDeps,
1541 ExportedPlugins: j.exportedPluginJars,
1542 ExportedPluginClasses: j.exportedPluginClasses,
1543 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1544 JacocoReportClassesFile: j.jacocoReportClassesFile,
1545 })
1546
1547 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1548 j.outputFile = outputFile.WithoutRel()
1549}
1550
Colin Crossa1ff7c62021-09-17 14:11:52 -07001551func (j *Module) useCompose() bool {
1552 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1553}
1554
Cole Faust75fffb12021-06-13 15:23:16 -07001555// Returns a copy of the supplied flags, but with all the errorprone-related
1556// fields copied to the regular build's fields.
1557func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1558 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1559
1560 if len(flags.errorProneExtraJavacFlags) > 0 {
1561 if len(flags.javacFlags) > 0 {
1562 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1563 } else {
1564 flags.javacFlags = flags.errorProneExtraJavacFlags
1565 }
1566 }
1567 return flags
1568}
1569
Jaewoong Jung26342642021-03-17 15:56:23 -07001570func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1571 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1572
1573 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1574 if idx >= 0 {
1575 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1576 jarName += strconv.Itoa(idx)
1577 }
1578
1579 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1580 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1581
1582 if ctx.Config().EmitXrefRules() {
1583 extractionFile := android.PathForModuleOut(ctx, kzipName)
1584 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1585 j.kytheFiles = append(j.kytheFiles, extractionFile)
1586 }
1587
1588 return classes
1589}
1590
1591// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1592// since some of these flags may be used internally.
1593func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1594 for _, flag := range flags {
1595 flag = strings.TrimSpace(flag)
1596
1597 if !strings.HasPrefix(flag, "-") {
1598 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1599 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1600 ctx.PropertyErrorf("kotlincflags",
1601 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1602 } else if inList(flag, config.KotlincIllegalFlags) {
1603 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1604 } else if flag == "-include-runtime" {
1605 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1606 } else {
1607 args := strings.Split(flag, " ")
1608 if args[0] == "-kotlin-home" {
1609 ctx.PropertyErrorf("kotlincflags",
1610 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1611 }
1612 }
1613 }
1614}
1615
1616func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1617 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001618 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001619
1620 var jars android.Paths
1621 if len(srcFiles) > 0 || len(srcJars) > 0 {
1622 // Compile java sources into turbine.jar.
1623 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1624 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1625 if ctx.Failed() {
1626 return nil, nil
1627 }
1628 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001629 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001630 }
1631
1632 jars = append(jars, extraJars...)
1633
1634 // Combine any static header libraries into classes-header.jar. If there is only
1635 // one input jar this step will be skipped.
1636 jars = append(jars, deps.staticHeaderJars...)
1637
1638 // we cannot skip the combine step for now if there is only one jar
1639 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1640 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1641 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1642 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001643 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001644
1645 if j.expandJarjarRules != nil {
1646 // Transform classes.jar into classes-jarjar.jar
1647 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001648 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1649 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001650 if ctx.Failed() {
1651 return nil, nil
1652 }
1653 }
1654
Colin Cross3d56ed52021-11-18 22:23:12 -08001655 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001656}
1657
1658func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001659 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001660
1661 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1662 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1663
1664 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1665
1666 j.jacocoReportClassesFile = jacocoReportClassesFile
1667
1668 return instrumentedJar
1669}
1670
1671func (j *Module) HeaderJars() android.Paths {
1672 if j.headerJarFile == nil {
1673 return nil
1674 }
1675 return android.Paths{j.headerJarFile}
1676}
1677
1678func (j *Module) ImplementationJars() android.Paths {
1679 if j.implementationJarFile == nil {
1680 return nil
1681 }
1682 return android.Paths{j.implementationJarFile}
1683}
1684
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001685func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001686 return j.dexJarFile
1687}
1688
1689func (j *Module) DexJarInstallPath() android.Path {
1690 return j.installFile
1691}
1692
1693func (j *Module) ImplementationAndResourcesJars() android.Paths {
1694 if j.implementationAndResourcesJar == nil {
1695 return nil
1696 }
1697 return android.Paths{j.implementationAndResourcesJar}
1698}
1699
1700func (j *Module) AidlIncludeDirs() android.Paths {
1701 // exportAidlIncludeDirs is type android.Paths already
1702 return j.exportAidlIncludeDirs
1703}
1704
1705func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1706 return j.classLoaderContexts
1707}
1708
1709// Collect information for opening IDE project files in java/jdeps.go.
1710func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1711 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1712 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1713 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1714 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1715 if j.expandJarjarRules != nil {
1716 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1717 }
1718 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001719 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1720 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001721}
1722
1723func (j *Module) CompilerDeps() []string {
1724 jdeps := []string{}
1725 jdeps = append(jdeps, j.properties.Libs...)
1726 jdeps = append(jdeps, j.properties.Static_libs...)
1727 return jdeps
1728}
1729
1730func (j *Module) hasCode(ctx android.ModuleContext) bool {
1731 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1732 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1733}
1734
1735// Implements android.ApexModule
1736func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1737 return j.depIsInSameApex(ctx, dep)
1738}
1739
1740// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001741func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001742 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001743 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001744 return fmt.Errorf("min_sdk_version is not specified")
1745 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001746 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001747 return nil
1748 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001749 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1750 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001751 }
1752 return nil
1753}
1754
1755func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001756 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001757}
1758
Jaewoong Jung26342642021-03-17 15:56:23 -07001759func (j *Module) JacocoReportClassesFile() android.Path {
1760 return j.jacocoReportClassesFile
1761}
1762
1763func (j *Module) IsInstallable() bool {
1764 return Bool(j.properties.Installable)
1765}
1766
1767type sdkLinkType int
1768
1769const (
1770 // TODO(jiyong) rename these for better readability. Make the allowed
1771 // and disallowed link types explicit
1772 // order is important here. See rank()
1773 javaCore sdkLinkType = iota
1774 javaSdk
1775 javaSystem
1776 javaModule
1777 javaSystemServer
1778 javaPlatform
1779)
1780
1781func (lt sdkLinkType) String() string {
1782 switch lt {
1783 case javaCore:
1784 return "core Java API"
1785 case javaSdk:
1786 return "Android API"
1787 case javaSystem:
1788 return "system API"
1789 case javaModule:
1790 return "module API"
1791 case javaSystemServer:
1792 return "system server API"
1793 case javaPlatform:
1794 return "private API"
1795 default:
1796 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1797 }
1798}
1799
1800// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1801// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1802// can't statically depend on modules that use Platform API.
1803func (lt sdkLinkType) rank() int {
1804 return int(lt)
1805}
1806
1807type moduleWithSdkDep interface {
1808 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001809 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001810}
1811
Jiyong Park92315372021-04-02 08:45:46 +09001812func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001813 switch name {
1814 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1815 "stub-annotations", "private-stub-annotations-jar",
1816 "core-lambda-stubs", "core-generated-annotation-stubs":
1817 return javaCore, true
1818 case "android_stubs_current":
1819 return javaSdk, true
1820 case "android_system_stubs_current":
1821 return javaSystem, true
1822 case "android_module_lib_stubs_current":
1823 return javaModule, true
1824 case "android_system_server_stubs_current":
1825 return javaSystemServer, true
1826 case "android_test_stubs_current":
1827 return javaSystem, true
1828 }
1829
1830 if stub, linkType := moduleStubLinkType(name); stub {
1831 return linkType, true
1832 }
1833
Jiyong Park92315372021-04-02 08:45:46 +09001834 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001835 switch ver.Kind {
1836 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001837 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001838 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001839 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001840 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001841 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001842 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001843 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001844 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001845 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001846 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001847 return javaPlatform, false
1848 }
1849
Jiyong Parkf1691d22021-03-29 20:11:58 +09001850 if !ver.Valid() {
1851 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001852 }
1853 return javaSdk, false
1854}
1855
1856// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1857// this module's. See the comment on rank() for details and an example.
1858func (j *Module) checkSdkLinkType(
1859 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1860 if ctx.Host() {
1861 return
1862 }
1863
Jiyong Park92315372021-04-02 08:45:46 +09001864 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001865 if stubs {
1866 return
1867 }
Jiyong Park92315372021-04-02 08:45:46 +09001868 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001869
1870 if myLinkType.rank() < depLinkType.rank() {
1871 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1872 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1873 "property of the source or target module so that target module is built "+
1874 "with the same or smaller API set when compared to the source.",
1875 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1876 }
1877}
1878
1879func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1880 var deps deps
1881
1882 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001883 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001884 if sdkDep.invalidVersion {
1885 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1886 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1887 } else if sdkDep.useFiles {
1888 // sdkDep.jar is actually equivalent to turbine header.jar.
1889 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001890 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001891 deps.aidlPreprocess = sdkDep.aidl
1892 } else {
1893 deps.aidlPreprocess = sdkDep.aidl
1894 }
1895 }
1896
Jiyong Park92315372021-04-02 08:45:46 +09001897 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001898
1899 ctx.VisitDirectDeps(func(module android.Module) {
1900 otherName := ctx.OtherModuleName(module)
1901 tag := ctx.OtherModuleDependencyTag(module)
1902
1903 if IsJniDepTag(tag) {
1904 // Handled by AndroidApp.collectAppDeps
1905 return
1906 }
1907 if tag == certificateTag {
1908 // Handled by AndroidApp.collectAppDeps
1909 return
1910 }
1911
1912 if dep, ok := module.(SdkLibraryDependency); ok {
1913 switch tag {
1914 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001915 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1916 deps.classpath = append(deps.classpath, depHeaderJars...)
1917 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001918 case staticLibTag:
1919 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1920 }
1921 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1922 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1923 if sdkLinkType != javaPlatform &&
1924 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1925 // dep is a sysprop implementation library, but this module is not linking against
1926 // the platform, so it gets the sysprop public stubs library instead. Replace
1927 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1928 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1929 dep = syspropDep.JavaInfo
1930 }
1931 switch tag {
1932 case bootClasspathTag:
1933 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1934 case libTag, instrumentationForTag:
1935 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001936 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001937 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1938 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1939 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1940 case java9LibTag:
1941 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1942 case staticLibTag:
1943 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1944 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1945 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1946 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1947 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1948 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1949 // Turbine doesn't run annotation processors, so any module that uses an
1950 // annotation processor that generates API is incompatible with the turbine
1951 // optimization.
1952 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1953 case pluginTag:
1954 if plugin, ok := module.(*Plugin); ok {
1955 if plugin.pluginProperties.Processor_class != nil {
1956 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1957 } else {
1958 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1959 }
1960 // Turbine doesn't run annotation processors, so any module that uses an
1961 // annotation processor that generates API is incompatible with the turbine
1962 // optimization.
1963 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1964 } else {
1965 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1966 }
1967 case errorpronePluginTag:
1968 if _, ok := module.(*Plugin); ok {
1969 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1970 } else {
1971 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1972 }
1973 case exportedPluginTag:
1974 if plugin, ok := module.(*Plugin); ok {
1975 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1976 if plugin.pluginProperties.Processor_class != nil {
1977 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1978 }
1979 // Turbine doesn't run annotation processors, so any module that uses an
1980 // annotation processor that generates API is incompatible with the turbine
1981 // optimization.
1982 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1983 } else {
1984 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1985 }
1986 case kotlinStdlibTag:
1987 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1988 case kotlinAnnotationsTag:
1989 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001990 case kotlinPluginTag:
1991 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001992 case syspropPublicStubDepTag:
1993 // This is a sysprop implementation library, forward the JavaInfoProvider from
1994 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1995 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1996 JavaInfo: dep,
1997 })
1998 }
1999 } else if dep, ok := module.(android.SourceFileProducer); ok {
2000 switch tag {
2001 case libTag:
2002 checkProducesJars(ctx, dep)
2003 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07002004 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07002005 case staticLibTag:
2006 checkProducesJars(ctx, dep)
2007 deps.classpath = append(deps.classpath, dep.Srcs()...)
2008 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
2009 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
2010 }
2011 } else {
2012 switch tag {
2013 case bootClasspathTag:
2014 // If a system modules dependency has been added to the bootclasspath
2015 // then add its libs to the bootclasspath.
2016 sm := module.(SystemModulesProvider)
2017 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
2018
2019 case systemModulesTag:
2020 if deps.systemModules != nil {
2021 panic("Found two system module dependencies")
2022 }
2023 sm := module.(SystemModulesProvider)
2024 outputDir, outputDeps := sm.OutputDirAndDeps()
2025 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002026
2027 case instrumentationForTag:
2028 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 -07002029 }
2030 }
2031
2032 addCLCFromDep(ctx, module, j.classLoaderContexts)
2033 })
2034
2035 return deps
2036}
2037
2038func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2039 deps.processorPath = append(deps.processorPath, pluginJars...)
2040 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2041}
2042
2043// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2044// this interface.
2045type ProvidesUsesLib interface {
2046 ProvidesUsesLib() *string
2047}
2048
2049func (j *Module) ProvidesUsesLib() *string {
2050 return j.usesLibraryProperties.Provides_uses_lib
2051}
satayev1c564cc2021-05-25 19:50:30 +01002052
2053type ModuleWithStem interface {
2054 Stem() string
2055}
2056
2057var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002058
2059func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2060 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002061 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002062 if lib, ok := ctx.Module().(*Library); ok {
2063 javaLibraryBp2Build(ctx, lib)
2064 }
2065 case "java_binary_host":
2066 if binary, ok := ctx.Module().(*Binary); ok {
2067 javaBinaryHostBp2Build(ctx, binary)
2068 }
2069 }
Wei Libafb6d62021-12-10 03:14:59 -08002070}