blob: c6c560935727b910f9bfac93b89e30bc23dd23b8 [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"`
173
174 // List of files to include in the META-INF/services folder of the resulting jar.
175 Services []string `android:"path,arch_variant"`
176
177 // If true, package the kotlin stdlib into the jar. Defaults to true.
178 Static_kotlin_stdlib *bool `android:"arch_variant"`
179
180 // A list of java_library instances that provide additional hiddenapi annotations for the library.
181 Hiddenapi_additional_annotations []string
182}
183
184// Properties that are specific to device modules. Host module factories should not add these when
185// constructing a new module.
186type DeviceProperties struct {
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000187 // If not blank, set to the version of the sdk to compile against.
Jaewoong Jung26342642021-03-17 15:56:23 -0700188 // Defaults to compiling against the current platform.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000189 // Values are of one of the following forms:
190 // 1) numerical API level or "current"
191 // 2) An SDK kind with an API level: "<sdk kind>_<API level>". See
192 // build/soong/android/sdk_version.go for the complete and up to date list of
193 // SDK kinds. If the SDK kind value is empty, it will be set to public.
Jaewoong Jung26342642021-03-17 15:56:23 -0700194 Sdk_version *string
195
196 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000197 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700198 Min_sdk_version *string
199
satayev0a420e72021-11-29 17:25:52 +0000200 // if not blank, set the maximum version of the sdk that the compiled artifacts will run against.
201 // Defaults to empty string "". See sdk_version for possible values.
202 Max_sdk_version *string
203
Jaewoong Jung26342642021-03-17 15:56:23 -0700204 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
Trevor Radcliffe347e5e42021-11-05 19:30:24 +0000205 // Defaults to sdk_version if not set. See sdk_version for possible values.
Jaewoong Jung26342642021-03-17 15:56:23 -0700206 Target_sdk_version *string
207
208 // Whether to compile against the platform APIs instead of an SDK.
209 // If true, then sdk_version must be empty. The value of this field
210 // is ignored when module's type isn't android_app.
211 Platform_apis *bool
212
213 Aidl struct {
214 // Top level directories to pass to aidl tool
215 Include_dirs []string
216
217 // Directories rooted at the Android.bp file to pass to aidl tool
218 Local_include_dirs []string
219
220 // directories that should be added as include directories for any aidl sources of modules
221 // that depend on this module, as well as to aidl for this module.
222 Export_include_dirs []string
223
224 // whether to generate traces (for systrace) for this interface
225 Generate_traces *bool
226
227 // whether to generate Binder#GetTransaction name method.
228 Generate_get_transaction_name *bool
229
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100230 // whether all interfaces should be annotated with required permissions.
231 Enforce_permissions *bool
232
233 // allowlist for interfaces that (temporarily) do not require annotation for permissions.
234 Enforce_permissions_exceptions []string `android:"path"`
235
Jaewoong Jung26342642021-03-17 15:56:23 -0700236 // list of flags that will be passed to the AIDL compiler
237 Flags []string
238 }
239
240 // If true, export a copy of the module as a -hostdex module for host testing.
241 Hostdex *bool
242
243 Target struct {
244 Hostdex struct {
245 // Additional required dependencies to add to -hostdex modules.
246 Required []string
247 }
248 }
249
250 // When targeting 1.9 and above, override the modules to use with --system,
251 // otherwise provides defaults libraries to add to the bootclasspath.
252 System_modules *string
253
Jaewoong Jung26342642021-03-17 15:56:23 -0700254 IsSDKLibrary bool `blueprint:"mutated"`
255
256 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
257 // Defaults to false.
258 V4_signature *bool
259
260 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
261 // public stubs library.
262 SyspropPublicStub string `blueprint:"mutated"`
263}
264
Jooyung Han01d80d82022-01-08 12:16:32 +0900265// Device properties that can be overridden by overriding module (e.g. override_android_app)
266type OverridableDeviceProperties struct {
267 // set the name of the output. If not set, `name` is used.
268 // To override a module with this property set, overriding module might need to set this as well.
269 // Otherwise, both the overridden and the overriding modules will have the same output name, which
270 // can cause the duplicate output error.
271 Stem *string
272}
273
Jaewoong Jung26342642021-03-17 15:56:23 -0700274// Functionality common to Module and Import
275//
276// It is embedded in Module so its functionality can be used by methods in Module
277// but it is currently only initialized by Import and Library.
278type embeddableInModuleAndImport struct {
279
280 // Functionality related to this being used as a component of a java_sdk_library.
281 EmbeddableSdkLibraryComponent
282}
283
Paul Duffin71b33cc2021-06-23 11:39:47 +0100284func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
285 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700286}
287
288// Module/Import's DepIsInSameApex(...) delegates to this method.
289//
290// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
291// the one provided by ApexModuleBase.
292func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
293 // dependencies other than the static linkage are all considered crossing APEX boundary
294 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
295 return true
296 }
297 return false
298}
299
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100300// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
301// or an invalid path describing the reason it is invalid.
302//
303// It is unset if a dex jar isn't applicable, i.e. no build rule has been
304// requested to create one.
305//
306// If a dex jar has been requested to be built then it is set, and it may be
307// either a valid android.Path, or invalid with a reason message. The latter
308// happens if the source that should produce the dex file isn't able to.
309//
310// E.g. it is invalid with a reason message if there is a prebuilt APEX that
311// could produce the dex jar through a deapexer module, but the APEX isn't
312// installable so doing so wouldn't be safe.
313type OptionalDexJarPath struct {
314 isSet bool
315 path android.OptionalPath
316}
317
318// IsSet returns true if a path has been set, either invalid or valid.
319func (o OptionalDexJarPath) IsSet() bool {
320 return o.isSet
321}
322
323// Valid returns true if there is a path that is valid.
324func (o OptionalDexJarPath) Valid() bool {
325 return o.isSet && o.path.Valid()
326}
327
328// Path returns the valid path, or panics if it's either not set or is invalid.
329func (o OptionalDexJarPath) Path() android.Path {
330 if !o.isSet {
331 panic("path isn't set")
332 }
333 return o.path.Path()
334}
335
336// PathOrNil returns the path if it's set and valid, or else nil.
337func (o OptionalDexJarPath) PathOrNil() android.Path {
338 if o.Valid() {
339 return o.Path()
340 }
341 return nil
342}
343
344// InvalidReason returns the reason for an invalid path, which is never "". It
345// returns "" for an unset or valid path.
346func (o OptionalDexJarPath) InvalidReason() string {
347 if !o.isSet {
348 return ""
349 }
350 return o.path.InvalidReason()
351}
352
353func (o OptionalDexJarPath) String() string {
354 if !o.isSet {
355 return "<unset>"
356 }
357 return o.path.String()
358}
359
360// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
361func makeUnsetDexJarPath() OptionalDexJarPath {
362 return OptionalDexJarPath{isSet: false}
363}
364
365// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
366// the given OptionalPath, which may be valid or invalid.
367func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
368 return OptionalDexJarPath{isSet: true, path: path}
369}
370
371// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
372// valid given path. It returns an unset OptionalDexJarPath if the given path is
373// nil.
374func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
375 if path == nil {
376 return makeUnsetDexJarPath()
377 }
378 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
379}
380
Jaewoong Jung26342642021-03-17 15:56:23 -0700381// Module contains the properties and members used by all java module types
382type Module struct {
383 android.ModuleBase
384 android.DefaultableModuleBase
385 android.ApexModuleBase
386 android.SdkBase
Wei Libafb6d62021-12-10 03:14:59 -0800387 android.BazelModuleBase
Jaewoong Jung26342642021-03-17 15:56:23 -0700388
389 // Functionality common to Module and Import.
390 embeddableInModuleAndImport
391
392 properties CommonProperties
393 protoProperties android.ProtoProperties
394 deviceProperties DeviceProperties
395
Jooyung Han01d80d82022-01-08 12:16:32 +0900396 overridableDeviceProperties OverridableDeviceProperties
397
Jaewoong Jung26342642021-03-17 15:56:23 -0700398 // jar file containing header classes including static library dependencies, suitable for
399 // inserting into the bootclasspath/classpath of another compile
400 headerJarFile android.Path
401
402 // jar file containing implementation classes including static library dependencies but no
403 // resources
404 implementationJarFile android.Path
405
406 // jar file containing only resources including from static library dependencies
407 resourceJar android.Path
408
409 // args and dependencies to package source files into a srcjar
410 srcJarArgs []string
411 srcJarDeps android.Paths
412
413 // jar file containing implementation classes and resources including static library
414 // dependencies
415 implementationAndResourcesJar android.Path
416
417 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100418 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700419
420 // output file containing uninstrumented classes that will be instrumented by jacoco
421 jacocoReportClassesFile android.Path
422
423 // output file of the module, which may be a classes jar or a dex jar
424 outputFile android.Path
425 extraOutputFiles android.Paths
426
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100427 exportAidlIncludeDirs android.Paths
428 ignoredAidlPermissionList android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -0700429
430 logtagsSrcs android.Paths
431
432 // installed file for binary dependency
433 installFile android.Path
434
Colin Cross3108ce12021-11-10 14:38:50 -0800435 // installed file for hostdex copy
436 hostdexInstallFile android.InstallPath
437
Jaewoong Jung26342642021-03-17 15:56:23 -0700438 // list of .java files and srcjars that was passed to javac
439 compiledJavaSrcs android.Paths
440 compiledSrcJars android.Paths
441
442 // manifest file to use instead of properties.Manifest
443 overrideManifest android.OptionalPath
444
445 // map of SDK version to class loader context
446 classLoaderContexts dexpreopt.ClassLoaderContextMap
447
448 // list of plugins that this java module is exporting
449 exportedPluginJars android.Paths
450
451 // list of plugins that this java module is exporting
452 exportedPluginClasses []string
453
454 // if true, the exported plugins generate API and require disabling turbine.
455 exportedDisableTurbine bool
456
457 // list of source files, collected from srcFiles with unique java and all kt files,
458 // will be used by android.IDEInfo struct
459 expandIDEInfoCompiledSrcs []string
460
461 // expanded Jarjar_rules
462 expandJarjarRules android.Path
463
Jaewoong Jung26342642021-03-17 15:56:23 -0700464 // Extra files generated by the module type to be added as java resources.
465 extraResources android.Paths
466
467 hiddenAPI
468 dexer
469 dexpreopter
470 usesLibrary
471 linter
472
473 // list of the xref extraction files
474 kytheFiles android.Paths
475
476 // Collect the module directory for IDE info in java/jdeps.go.
477 modulePaths []string
478
479 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900480
481 sdkVersion android.SdkSpec
482 minSdkVersion android.SdkSpec
satayev0a420e72021-11-29 17:25:52 +0000483 maxSdkVersion android.SdkSpec
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400484
485 sourceExtensions []string
Jaewoong Jung26342642021-03-17 15:56:23 -0700486}
487
Jiyong Park92315372021-04-02 08:45:46 +0900488func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
489 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900490 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700491 return nil
492 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900493 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000494 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700495 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
496 } else {
497 // Treat stable core platform as stable.
498 return nil
499 }
500 } else {
501 return fmt.Errorf("non stable SDK %v", sdkVersion)
502 }
503}
504
505// checkSdkVersions enforces restrictions around SDK dependencies.
506func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
507 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900508 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900509 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700510 ctx.PropertyErrorf("sdk_version",
511 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
512 }
513 }
514 }
515
516 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
517 // See rank() for details.
518 ctx.VisitDirectDeps(func(module android.Module) {
519 tag := ctx.OtherModuleDependencyTag(module)
520 switch module.(type) {
521 // TODO(satayev): cover other types as well, e.g. imports
522 case *Library, *AndroidLibrary:
523 switch tag {
524 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
525 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
526 }
527 }
528 })
529}
530
531func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900532 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700533 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900534 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700535 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000536 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 -0700537 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000538 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 -0700539 }
540
541 }
542}
543
544func (j *Module) addHostProperties() {
545 j.AddProperties(
546 &j.properties,
547 &j.protoProperties,
548 &j.usesLibraryProperties,
549 )
550}
551
552func (j *Module) addHostAndDeviceProperties() {
553 j.addHostProperties()
554 j.AddProperties(
555 &j.deviceProperties,
Jooyung Han01d80d82022-01-08 12:16:32 +0900556 &j.overridableDeviceProperties,
Jaewoong Jung26342642021-03-17 15:56:23 -0700557 &j.dexer.dexProperties,
558 &j.dexpreoptProperties,
559 &j.linter.properties,
560 )
561}
562
563func (j *Module) OutputFiles(tag string) (android.Paths, error) {
564 switch tag {
565 case "":
566 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
567 case android.DefaultDistTag:
568 return android.Paths{j.outputFile}, nil
569 case ".jar":
570 return android.Paths{j.implementationAndResourcesJar}, nil
571 case ".proguard_map":
572 if j.dexer.proguardDictionary.Valid() {
573 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
574 }
575 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
576 default:
577 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
578 }
579}
580
581var _ android.OutputFileProducer = (*Module)(nil)
582
583func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
584 initJavaModule(module, hod, false)
585}
586
587func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
588 initJavaModule(module, hod, true)
589}
590
591func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
592 multilib := android.MultilibCommon
593 if multiTargets {
594 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
595 } else {
596 android.InitAndroidArchModule(module, hod, multilib)
597 }
598 android.InitDefaultableModule(module)
599}
600
601func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
602 return j.properties.Instrument &&
603 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
604 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
605}
606
607func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
608 return j.shouldInstrument(ctx) &&
609 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
610 ctx.Config().UnbundledBuild())
611}
612
613func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
614 // Force enable the instrumentation for java code that is built for APEXes ...
615 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
616 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
617 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
618 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
619 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
620 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
621 return true
622 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
623 return true
624 }
625 }
626 return false
627}
628
Jiyong Park92315372021-04-02 08:45:46 +0900629func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
630 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700631}
632
Jiyong Parkf1691d22021-03-29 20:11:58 +0900633func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700634 return proptools.String(j.deviceProperties.System_modules)
635}
636
Jiyong Park92315372021-04-02 08:45:46 +0900637func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700638 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900639 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700640 }
Jiyong Park92315372021-04-02 08:45:46 +0900641 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700642}
643
satayev0a420e72021-11-29 17:25:52 +0000644func (j *Module) MaxSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
645 maxSdkVersion := proptools.StringDefault(j.deviceProperties.Max_sdk_version, "")
646 // SdkSpecFrom returns SdkSpecPrivate for this, which may be confusing.
647 // TODO(b/208456999): ideally MaxSdkVersion should be an ApiLevel and not SdkSpec.
648 return android.SdkSpecFrom(ctx, maxSdkVersion)
649}
650
Jiyong Parkf1691d22021-03-29 20:11:58 +0900651func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900652 return j.minSdkVersion.Raw
653}
654
655func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
656 if j.deviceProperties.Target_sdk_version != nil {
657 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
658 }
659 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700660}
661
662func (j *Module) AvailableFor(what string) bool {
663 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
664 // Exception: for hostdex: true libraries, the platform variant is created
665 // even if it's not marked as available to platform. In that case, the platform
666 // variant is used only for the hostdex and not installed to the device.
667 return true
668 }
669 return j.ApexModuleBase.AvailableFor(what)
670}
671
672func (j *Module) deps(ctx android.BottomUpMutatorContext) {
673 if ctx.Device() {
674 j.linter.deps(ctx)
675
Jiyong Parkf1691d22021-03-29 20:11:58 +0900676 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700677
678 if j.deviceProperties.SyspropPublicStub != "" {
679 // This is a sysprop implementation library that has a corresponding sysprop public
680 // stubs library, and a dependency on it so that dependencies on the implementation can
681 // be forwarded to the public stubs library when necessary.
682 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
683 }
684 }
685
686 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
687 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
688
689 // Add dependency on libraries that provide additional hidden api annotations.
690 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
691
692 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
693 // Require java_sdk_library at inter-partition java dependency to ensure stable
694 // interface between partitions. If inter-partition java_library dependency is detected,
695 // raise build error because java_library doesn't have a stable interface.
696 //
697 // Inputs:
698 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
699 // if true, enable enforcement
700 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
701 // exception list of java_library names to allow inter-partition dependency
702 for idx := range j.properties.Libs {
703 if libDeps[idx] == nil {
704 continue
705 }
706
707 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
708 // java_sdk_library is always allowed at inter-partition dependency.
709 // So, skip check.
710 if _, ok := javaDep.(*SdkLibrary); ok {
711 continue
712 }
713
714 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
715 }
716 }
717 }
718
719 // For library dependencies that are component libraries (like stubs), add the implementation
720 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
721 for _, dep := range libDeps {
722 if dep != nil {
723 if component, ok := dep.(SdkLibraryComponentDependency); ok {
724 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100725 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100726 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
727 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100728 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700729 }
730 }
731 }
732 }
733
734 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
735 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
736 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
737
738 android.ProtoDeps(ctx, &j.protoProperties)
739 if j.hasSrcExt(".proto") {
740 protoDeps(ctx, &j.protoProperties)
741 }
742
743 if j.hasSrcExt(".kt") {
744 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
745 // Kotlin files
746 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
747 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
748 if len(j.properties.Plugins) > 0 {
749 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
750 }
751 }
752
753 // Framework libraries need special handling in static coverage builds: they should not have
754 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
755 // the same jacoco classes coming from different bootclasspath jars.
756 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
757 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
758 j.properties.Instrument = true
759 }
760 } else if j.shouldInstrumentStatic(ctx) {
761 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
762 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700763
764 if j.useCompose() {
765 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
766 "androidx.compose.compiler_compiler-hosted")
767 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700768}
769
770func hasSrcExt(srcs []string, ext string) bool {
771 for _, src := range srcs {
772 if filepath.Ext(src) == ext {
773 return true
774 }
775 }
776
777 return false
778}
779
780func (j *Module) hasSrcExt(ext string) bool {
781 return hasSrcExt(j.properties.Srcs, ext)
782}
783
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100784func (j *Module) individualAidlFlags(ctx android.ModuleContext, aidlFile android.Path) string {
785 var flags string
786
787 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
788 if !android.InList(aidlFile.String(), j.ignoredAidlPermissionList.Strings()) {
789 flags = "-Wmissing-permission-annotation -Werror"
790 }
791 }
792 return flags
793}
794
Jaewoong Jung26342642021-03-17 15:56:23 -0700795func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
796 aidlIncludeDirs android.Paths) (string, android.Paths) {
797
798 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
799 aidlIncludes = append(aidlIncludes,
800 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
801 aidlIncludes = append(aidlIncludes,
802 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
803
804 var flags []string
805 var deps android.Paths
806
807 flags = append(flags, j.deviceProperties.Aidl.Flags...)
808
809 if aidlPreprocess.Valid() {
810 flags = append(flags, "-p"+aidlPreprocess.String())
811 deps = append(deps, aidlPreprocess.Path())
812 } else if len(aidlIncludeDirs) > 0 {
813 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
814 }
815
816 if len(j.exportAidlIncludeDirs) > 0 {
817 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
818 }
819
820 if len(aidlIncludes) > 0 {
821 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
822 }
823
824 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
825 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
826 flags = append(flags, "-I"+src.String())
827 }
828
829 if Bool(j.deviceProperties.Aidl.Generate_traces) {
830 flags = append(flags, "-t")
831 }
832
833 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
834 flags = append(flags, "--transaction_names")
835 }
836
Thiébaud Weksteende8417c2022-02-10 15:41:46 +1100837 if Bool(j.deviceProperties.Aidl.Enforce_permissions) {
838 exceptions := j.deviceProperties.Aidl.Enforce_permissions_exceptions
839 j.ignoredAidlPermissionList = android.PathsForModuleSrcExcludes(ctx, exceptions, nil)
840 }
841
Jooyung Han07f70c02021-11-06 07:08:45 +0900842 aidlMinSdkVersion := j.MinSdkVersion(ctx).ApiLevel.String()
843 flags = append(flags, "--min_sdk_version="+aidlMinSdkVersion)
844
Jaewoong Jung26342642021-03-17 15:56:23 -0700845 return strings.Join(flags, " "), deps
846}
847
848func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
849
850 var flags javaBuilderFlags
851
852 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900853 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700854
Cole Faust2b1536e2021-06-18 12:25:54 -0700855 epEnabled := j.properties.Errorprone.Enabled
856 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700857 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
858 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
859 }
860
861 errorProneFlags := []string{
862 "-Xplugin:ErrorProne",
863 "${config.ErrorProneChecks}",
864 }
865 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
866
Colin Cross8bf6cad2022-02-28 13:07:03 -0800867 flags.errorProneExtraJavacFlags = "${config.ErrorProneHeapFlags} ${config.ErrorProneFlags} " +
Jaewoong Jung26342642021-03-17 15:56:23 -0700868 "'" + strings.Join(errorProneFlags, " ") + "'"
869 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
870 }
871
872 // classpath
873 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
874 flags.classpath = append(flags.classpath, deps.classpath...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700875 flags.dexClasspath = append(flags.dexClasspath, deps.dexClasspath...)
Jaewoong Jung26342642021-03-17 15:56:23 -0700876 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
877 flags.processorPath = append(flags.processorPath, deps.processorPath...)
878 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
879
880 flags.processors = append(flags.processors, deps.processorClasses...)
881 flags.processors = android.FirstUniqueStrings(flags.processors)
882
883 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900884 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700885 // Give host-side tools a version of OpenJDK's standard libraries
886 // close to what they're targeting. As of Dec 2017, AOSP is only
887 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
888 //
889 // When building with OpenJDK 8, the following should have no
890 // effect since those jars would be available by default.
891 //
892 // When building with OpenJDK 9 but targeting a version < 1.8,
893 // putting them on the bootclasspath means that:
894 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
895 // b) references to existing APIs are not reinterpreted in an
896 // OpenJDK 9-specific way, eg. calls to subclasses of
897 // java.nio.Buffer as in http://b/70862583
898 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
899 flags.bootClasspath = append(flags.bootClasspath,
900 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
901 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
902 if Bool(j.properties.Use_tools_jar) {
903 flags.bootClasspath = append(flags.bootClasspath,
904 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
905 }
906 }
907
908 // systemModules
909 flags.systemModules = deps.systemModules
910
911 // aidl flags.
912 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
913
914 return flags
915}
916
917func (j *Module) collectJavacFlags(
918 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
919 // javac flags.
920 javacFlags := j.properties.Javacflags
921
922 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
923 // For non-host binaries, override the -g flag passed globally to remove
924 // local variable debug info to reduce disk and memory usage.
925 javacFlags = append(javacFlags, "-g:source,lines")
926 }
927 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
928
929 if flags.javaVersion.usesJavaModules() {
930 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
931
932 if j.properties.Patch_module != nil {
933 // Manually specify build directory in case it is not under the repo root.
934 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
935 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200936 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700937
938 // b/150878007
939 //
940 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
941 // execution root for --patch-module. If this javac command line is
942 // invoked within Bazel's execution root working directory, the top
943 // level directories (e.g. libcore/, tools/, frameworks/) are all
944 // symlinks. JDK9 javac does not traverse into symlinks, which causes
945 // --patch-module to fail source file lookups when invoked in the
946 // execution root.
947 //
948 // Short of patching javac or enumerating *all* directories as possible
949 // input dirs, manually add the top level dir of the source files to be
950 // compiled.
951 topLevelDirs := map[string]bool{}
952 for _, srcFilePath := range srcFiles {
953 srcFileParts := strings.Split(srcFilePath.String(), "/")
954 // Ignore source files that are already in the top level directory
955 // as well as generated files in the out directory. The out
956 // directory may be an absolute path, which means srcFileParts[0] is the
957 // empty string, so check that as well. Note that "out" in Bazel's execution
958 // root is *not* a symlink, which doesn't cause problems for --patch-modules
959 // anyway, so it's fine to not apply this workaround for generated
960 // source files.
961 if len(srcFileParts) > 1 &&
962 srcFileParts[0] != "" &&
963 srcFileParts[0] != "out" {
964 topLevelDirs[srcFileParts[0]] = true
965 }
966 }
967 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
968
969 classPath := flags.classpath.FormJavaClassPath("")
970 if classPath != "" {
971 patchPaths = append(patchPaths, classPath)
972 }
973 javacFlags = append(
974 javacFlags,
975 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
976 }
977 }
978
979 if len(javacFlags) > 0 {
980 // optimization.
981 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
982 flags.javacFlags = "$javacFlags"
983 }
984
985 return flags
986}
987
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -0400988func (j *Module) AddJSONData(d *map[string]interface{}) {
989 (&j.ModuleBase).AddJSONData(d)
990 (*d)["Java"] = map[string]interface{}{
991 "SourceExtensions": j.sourceExtensions,
992 }
993
994}
995
Jaewoong Jung26342642021-03-17 15:56:23 -0700996func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
997 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
998
999 deps := j.collectDeps(ctx)
1000 flags := j.collectBuilderFlags(ctx, deps)
1001
1002 if flags.javaVersion.usesJavaModules() {
1003 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
1004 }
Sorin Basca9347ae32021-12-20 11:51:24 +00001005
Jaewoong Jung26342642021-03-17 15:56:23 -07001006 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
Romain Jobredeaux3ec36ad42021-10-29 13:08:48 -04001007 j.sourceExtensions = []string{}
1008 for _, ext := range []string{".kt", ".proto", ".aidl", ".java", ".logtags"} {
1009 if hasSrcExt(srcFiles.Strings(), ext) {
1010 j.sourceExtensions = append(j.sourceExtensions, ext)
1011 }
1012 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001013 if hasSrcExt(srcFiles.Strings(), ".proto") {
1014 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
1015 }
1016
1017 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
1018 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
1019 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
1020 }
1021
1022 srcFiles = j.genSources(ctx, srcFiles, flags)
1023
1024 // Collect javac flags only after computing the full set of srcFiles to
1025 // ensure that the --patch-module lookup paths are complete.
1026 flags = j.collectJavacFlags(ctx, flags, srcFiles)
1027
1028 srcJars := srcFiles.FilterByExt(".srcjar")
1029 srcJars = append(srcJars, deps.srcJars...)
1030 if aaptSrcJar != nil {
1031 srcJars = append(srcJars, aaptSrcJar)
1032 }
Colin Crossb0ef30a2021-06-29 10:42:00 -07001033 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -07001034
1035 if j.properties.Jarjar_rules != nil {
1036 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
1037 }
1038
1039 jarName := ctx.ModuleName() + ".jar"
1040
1041 javaSrcFiles := srcFiles.FilterByExt(".java")
1042 var uniqueSrcFiles android.Paths
1043 set := make(map[string]bool)
1044 for _, v := range javaSrcFiles {
1045 if _, found := set[v.String()]; !found {
1046 set[v.String()] = true
1047 uniqueSrcFiles = append(uniqueSrcFiles, v)
1048 }
1049 }
1050
Colin Crossb5db4012022-03-28 17:12:39 -07001051 // We don't currently run annotation processors in turbine, which means we can't use turbine
1052 // generated header jars when an annotation processor that generates API is enabled. One
1053 // exception (handled further below) is when kotlin sources are enabled, in which case turbine
1054 // is used to run all of the annotation processors.
1055 disableTurbine := deps.disableTurbine
1056
Jaewoong Jung26342642021-03-17 15:56:23 -07001057 // Collect .java files for AIDEGen
1058 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
1059
1060 var kotlinJars android.Paths
Colin Cross220a9a12022-03-28 17:08:01 -07001061 var kotlinHeaderJars android.Paths
Jaewoong Jung26342642021-03-17 15:56:23 -07001062
1063 if srcFiles.HasExt(".kt") {
Colin Crossb5db4012022-03-28 17:12:39 -07001064 // When using kotlin sources turbine is used to generate annotation processor sources,
1065 // including for annotation processors that generate API, so we can use turbine for
1066 // java sources too.
1067 disableTurbine = false
1068
Jaewoong Jung26342642021-03-17 15:56:23 -07001069 // user defined kotlin flags.
1070 kotlincFlags := j.properties.Kotlincflags
1071 CheckKotlincFlags(ctx, kotlincFlags)
1072
Aurimas Liutikas24a987f2021-05-17 17:47:10 +00001073 // Workaround for KT-46512
1074 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -07001075
1076 // If there are kotlin files, compile them first but pass all the kotlin and java files
1077 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
1078 // won't emit any classes for them.
1079 kotlincFlags = append(kotlincFlags, "-no-stdlib")
1080 if ctx.Device() {
1081 kotlincFlags = append(kotlincFlags, "-no-jdk")
1082 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001083
1084 for _, plugin := range deps.kotlinPlugins {
1085 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1086 }
1087 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1088
Jaewoong Jung26342642021-03-17 15:56:23 -07001089 if len(kotlincFlags) > 0 {
1090 // optimization.
1091 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1092 flags.kotlincFlags += "$kotlincFlags"
1093 }
1094
1095 var kotlinSrcFiles android.Paths
1096 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1097 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1098
1099 // Collect .kt files for AIDEGen
1100 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1101 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1102
1103 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1104 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1105
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001106 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinAnnotations...)
1107
Jaewoong Jung26342642021-03-17 15:56:23 -07001108 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1109 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1110
Isaac Chioua23d9942022-04-06 06:14:38 +00001111 if len(flags.processorPath) > 0 {
Jaewoong Jung26342642021-03-17 15:56:23 -07001112 // Use kapt for annotation processing
Isaac Chioua23d9942022-04-06 06:14:38 +00001113 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1114 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1115 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1116 srcJars = append(srcJars, kaptSrcJar)
1117 kotlinJars = append(kotlinJars, kaptResJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001118 // Disable annotation processing in javac, it's already been handled by kapt
1119 flags.processorPath = nil
1120 flags.processors = nil
1121 }
1122
1123 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
Colin Cross220a9a12022-03-28 17:08:01 -07001124 kotlinHeaderJar := android.PathForModuleOut(ctx, "kotlin_headers", jarName)
1125 kotlinCompile(ctx, kotlinJar, kotlinHeaderJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001126 if ctx.Failed() {
1127 return
1128 }
1129
Isaac Chioua23d9942022-04-06 06:14:38 +00001130 // Make javac rule depend on the kotlinc rule
1131 flags.classpath = append(classpath{kotlinHeaderJar}, flags.classpath...)
1132
Jaewoong Jung26342642021-03-17 15:56:23 -07001133 kotlinJars = append(kotlinJars, kotlinJar)
Colin Cross220a9a12022-03-28 17:08:01 -07001134 kotlinHeaderJars = append(kotlinHeaderJars, kotlinHeaderJar)
1135
Jaewoong Jung26342642021-03-17 15:56:23 -07001136 // Jar kotlin classes into the final jar after javac
1137 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1138 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
Colin Cross220a9a12022-03-28 17:08:01 -07001139 kotlinHeaderJars = append(kotlinHeaderJars, deps.kotlinStdlib...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001140 } else {
1141 flags.dexClasspath = append(flags.dexClasspath, deps.kotlinStdlib...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001142 }
1143 }
1144
1145 jars := append(android.Paths(nil), kotlinJars...)
1146
1147 // Store the list of .java files that was passed to javac
1148 j.compiledJavaSrcs = uniqueSrcFiles
1149 j.compiledSrcJars = srcJars
1150
1151 enableSharding := false
Colin Cross3d56ed52021-11-18 22:23:12 -08001152 var headerJarFileWithoutDepsOrJarjar android.Path
Colin Crossb5db4012022-03-28 17:12:39 -07001153 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !disableTurbine {
Jaewoong Jung26342642021-03-17 15:56:23 -07001154 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1155 enableSharding = true
1156 // Formerly, there was a check here that prevented annotation processors
1157 // from being used when sharding was enabled, as some annotation processors
1158 // do not function correctly in sharded environments. It was removed to
1159 // allow for the use of annotation processors that do function correctly
1160 // with sharding enabled. See: b/77284273.
1161 }
Colin Cross3d56ed52021-11-18 22:23:12 -08001162 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Colin Cross220a9a12022-03-28 17:08:01 -07001163 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinHeaderJars)
Jaewoong Jung26342642021-03-17 15:56:23 -07001164 if ctx.Failed() {
1165 return
1166 }
1167 }
1168 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1169 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001170 if Bool(j.properties.Errorprone.Enabled) {
1171 // If error-prone is enabled, enable errorprone flags on the regular
1172 // build.
1173 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001174 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001175 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1176 // a new jar file just for compiling with the errorprone compiler to.
1177 // This is because we don't want to cause the java files to get completely
1178 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1179 // We also don't want to run this if errorprone is enabled by default for
1180 // this module, or else we could have duplicated errorprone messages.
1181 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001182 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001183
1184 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1185 "errorprone", "errorprone")
1186
Jaewoong Jung26342642021-03-17 15:56:23 -07001187 extraJarDeps = append(extraJarDeps, errorprone)
1188 }
1189
1190 if enableSharding {
Colin Cross3d56ed52021-11-18 22:23:12 -08001191 if headerJarFileWithoutDepsOrJarjar != nil {
1192 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
1193 }
Jaewoong Jung26342642021-03-17 15:56:23 -07001194 shardSize := int(*(j.properties.Javac_shard_size))
1195 var shardSrcs []android.Paths
1196 if len(uniqueSrcFiles) > 0 {
1197 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1198 for idx, shardSrc := range shardSrcs {
1199 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1200 nil, flags, extraJarDeps)
1201 jars = append(jars, classes)
1202 }
1203 }
1204 if len(srcJars) > 0 {
1205 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1206 nil, srcJars, flags, extraJarDeps)
1207 jars = append(jars, classes)
1208 }
1209 } else {
1210 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1211 jars = append(jars, classes)
1212 }
1213 if ctx.Failed() {
1214 return
1215 }
1216 }
1217
1218 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1219
1220 var includeSrcJar android.WritablePath
1221 if Bool(j.properties.Include_srcs) {
1222 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1223 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1224 }
1225
1226 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1227 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1228 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1229 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1230
1231 var resArgs []string
1232 var resDeps android.Paths
1233
1234 resArgs = append(resArgs, dirArgs...)
1235 resDeps = append(resDeps, dirDeps...)
1236
1237 resArgs = append(resArgs, fileArgs...)
1238 resDeps = append(resDeps, fileDeps...)
1239
1240 resArgs = append(resArgs, extraArgs...)
1241 resDeps = append(resDeps, extraDeps...)
1242
1243 if len(resArgs) > 0 {
1244 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1245 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1246 j.resourceJar = resourceJar
1247 if ctx.Failed() {
1248 return
1249 }
1250 }
1251
1252 var resourceJars android.Paths
1253 if j.resourceJar != nil {
1254 resourceJars = append(resourceJars, j.resourceJar)
1255 }
1256 if Bool(j.properties.Include_srcs) {
1257 resourceJars = append(resourceJars, includeSrcJar)
1258 }
1259 resourceJars = append(resourceJars, deps.staticResourceJars...)
1260
1261 if len(resourceJars) > 1 {
1262 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1263 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1264 false, nil, nil)
1265 j.resourceJar = combinedJar
1266 } else if len(resourceJars) == 1 {
1267 j.resourceJar = resourceJars[0]
1268 }
1269
1270 if len(deps.staticJars) > 0 {
1271 jars = append(jars, deps.staticJars...)
1272 }
1273
1274 manifest := j.overrideManifest
1275 if !manifest.Valid() && j.properties.Manifest != nil {
1276 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1277 }
1278
1279 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1280 if len(services) > 0 {
1281 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1282 var zipargs []string
1283 for _, file := range services {
1284 serviceFile := file.String()
1285 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1286 }
1287 rule := zip
1288 args := map[string]string{
1289 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1290 }
1291 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1292 rule = zipRE
1293 args["implicits"] = strings.Join(services.Strings(), ",")
1294 }
1295 ctx.Build(pctx, android.BuildParams{
1296 Rule: rule,
1297 Output: servicesJar,
1298 Implicits: services,
1299 Args: args,
1300 })
1301 jars = append(jars, servicesJar)
1302 }
1303
1304 // Combine the classes built from sources, any manifests, and any static libraries into
1305 // classes.jar. If there is only one input jar this step will be skipped.
1306 var outputFile android.OutputPath
1307
1308 if len(jars) == 1 && !manifest.Valid() {
1309 // Optimization: skip the combine step as there is nothing to do
1310 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1311 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1312 // any if len(jars) == 1.
1313
1314 // Transform the single path to the jar into an OutputPath as that is required by the following
1315 // code.
1316 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1317 // The path contains an embedded OutputPath so reuse that.
1318 outputFile = moduleOutPath.OutputPath
1319 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1320 // The path is an OutputPath so reuse it directly.
1321 outputFile = outputPath
1322 } else {
1323 // The file is not in the out directory so create an OutputPath into which it can be copied
1324 // and which the following code can use to refer to it.
1325 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1326 ctx.Build(pctx, android.BuildParams{
1327 Rule: android.Cp,
1328 Input: jars[0],
1329 Output: combinedJar,
1330 })
1331 outputFile = combinedJar.OutputPath
1332 }
1333 } else {
1334 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1335 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1336 false, nil, nil)
1337 outputFile = combinedJar.OutputPath
1338 }
1339
1340 // jarjar implementation jar if necessary
1341 if j.expandJarjarRules != nil {
1342 // Transform classes.jar into classes-jarjar.jar
1343 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1344 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1345 outputFile = jarjarFile
1346
1347 // jarjar resource jar if necessary
1348 if j.resourceJar != nil {
1349 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1350 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1351 j.resourceJar = resourceJarJarFile
1352 }
1353
1354 if ctx.Failed() {
1355 return
1356 }
1357 }
1358
1359 // Check package restrictions if necessary.
1360 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001361 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001362 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001363
1364 // Create a rule to copy the output jar to another path and add a validate dependency that
1365 // will check that the jar only contains the permitted packages. The new location will become
1366 // the output file of this module.
1367 inputFile := outputFile
1368 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1369 ctx.Build(pctx, android.BuildParams{
1370 Rule: android.Cp,
1371 Input: inputFile,
1372 Output: outputFile,
1373 // Make sure that any dependency on the output file will cause ninja to run the package check
1374 // rule.
1375 Validation: pkgckFile,
1376 })
1377
1378 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001379 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001380
1381 if ctx.Failed() {
1382 return
1383 }
1384 }
1385
1386 j.implementationJarFile = outputFile
1387 if j.headerJarFile == nil {
1388 j.headerJarFile = j.implementationJarFile
1389 }
1390
1391 if j.shouldInstrumentInApex(ctx) {
1392 j.properties.Instrument = true
1393 }
1394
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001395 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1396 specs := j.jacocoModuleToZipCommand(ctx)
1397 if ctx.Failed() {
1398 return
1399 }
1400
Jaewoong Jung26342642021-03-17 15:56:23 -07001401 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001402 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001403 }
1404
1405 // merge implementation jar with resources if necessary
1406 implementationAndResourcesJar := outputFile
1407 if j.resourceJar != nil {
1408 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1409 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1410 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1411 false, nil, nil)
1412 implementationAndResourcesJar = combinedJar
1413 }
1414
1415 j.implementationAndResourcesJar = implementationAndResourcesJar
1416
1417 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1418 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1419 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1420 if j.dexProperties.Compile_dex == nil {
1421 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1422 }
1423 if j.deviceProperties.Hostdex == nil {
1424 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1425 }
1426 }
1427
1428 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1429 if j.hasCode(ctx) {
1430 if j.shouldInstrumentStatic(ctx) {
1431 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1432 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1433 }
1434 // Dex compilation
1435 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001436 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001437 if ctx.Failed() {
1438 return
1439 }
1440
Jaewoong Jung26342642021-03-17 15:56:23 -07001441 // merge dex jar with resources if necessary
1442 if j.resourceJar != nil {
1443 jars := android.Paths{dexOutputFile, j.resourceJar}
1444 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1445 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1446 false, nil, nil)
1447 if *j.dexProperties.Uncompress_dex {
1448 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1449 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1450 dexOutputFile = combinedAlignedJar
1451 } else {
1452 dexOutputFile = combinedJar
1453 }
1454 }
1455
Paul Duffin4de94502021-05-16 05:21:16 +01001456 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001457
1458 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001459
1460 // Encode hidden API flags in dex file, if needed.
1461 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1462
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001463 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001464
1465 // Dexpreopting
1466 j.dexpreopt(ctx, dexOutputFile)
1467
1468 outputFile = dexOutputFile
1469 } else {
1470 // There is no code to compile into a dex jar, make sure the resources are propagated
1471 // to the APK if this is an app.
1472 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001473 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001474 }
1475
1476 if ctx.Failed() {
1477 return
1478 }
1479 } else {
1480 outputFile = implementationAndResourcesJar
1481 }
1482
1483 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001484 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001485 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001486 return v.String()
1487 } else {
1488 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1489 }
1490 }
1491
1492 j.linter.name = ctx.ModuleName()
1493 j.linter.srcs = srcFiles
1494 j.linter.srcJars = srcJars
1495 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1496 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001497 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1498 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1499 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001500 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001501 j.linter.javaLanguageLevel = flags.javaVersion.String()
1502 j.linter.kotlinLanguageLevel = "1.3"
1503 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1504 j.linter.buildModuleReportZip = true
1505 }
1506 j.linter.lint(ctx)
1507 }
1508
1509 ctx.CheckbuildFile(outputFile)
1510
1511 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1512 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1513 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1514 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1515 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1516 AidlIncludeDirs: j.exportAidlIncludeDirs,
1517 SrcJarArgs: j.srcJarArgs,
1518 SrcJarDeps: j.srcJarDeps,
1519 ExportedPlugins: j.exportedPluginJars,
1520 ExportedPluginClasses: j.exportedPluginClasses,
1521 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1522 JacocoReportClassesFile: j.jacocoReportClassesFile,
1523 })
1524
1525 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1526 j.outputFile = outputFile.WithoutRel()
1527}
1528
Colin Crossa1ff7c62021-09-17 14:11:52 -07001529func (j *Module) useCompose() bool {
1530 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1531}
1532
Cole Faust75fffb12021-06-13 15:23:16 -07001533// Returns a copy of the supplied flags, but with all the errorprone-related
1534// fields copied to the regular build's fields.
1535func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1536 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1537
1538 if len(flags.errorProneExtraJavacFlags) > 0 {
1539 if len(flags.javacFlags) > 0 {
1540 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1541 } else {
1542 flags.javacFlags = flags.errorProneExtraJavacFlags
1543 }
1544 }
1545 return flags
1546}
1547
Jaewoong Jung26342642021-03-17 15:56:23 -07001548func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1549 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1550
1551 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1552 if idx >= 0 {
1553 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1554 jarName += strconv.Itoa(idx)
1555 }
1556
1557 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1558 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1559
1560 if ctx.Config().EmitXrefRules() {
1561 extractionFile := android.PathForModuleOut(ctx, kzipName)
1562 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1563 j.kytheFiles = append(j.kytheFiles, extractionFile)
1564 }
1565
1566 return classes
1567}
1568
1569// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1570// since some of these flags may be used internally.
1571func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1572 for _, flag := range flags {
1573 flag = strings.TrimSpace(flag)
1574
1575 if !strings.HasPrefix(flag, "-") {
1576 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1577 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1578 ctx.PropertyErrorf("kotlincflags",
1579 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1580 } else if inList(flag, config.KotlincIllegalFlags) {
1581 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1582 } else if flag == "-include-runtime" {
1583 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1584 } else {
1585 args := strings.Split(flag, " ")
1586 if args[0] == "-kotlin-home" {
1587 ctx.PropertyErrorf("kotlincflags",
1588 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1589 }
1590 }
1591 }
1592}
1593
1594func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1595 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross3d56ed52021-11-18 22:23:12 -08001596 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001597
1598 var jars android.Paths
1599 if len(srcFiles) > 0 || len(srcJars) > 0 {
1600 // Compile java sources into turbine.jar.
1601 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1602 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1603 if ctx.Failed() {
1604 return nil, nil
1605 }
1606 jars = append(jars, turbineJar)
Colin Cross3d56ed52021-11-18 22:23:12 -08001607 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001608 }
1609
1610 jars = append(jars, extraJars...)
1611
1612 // Combine any static header libraries into classes-header.jar. If there is only
1613 // one input jar this step will be skipped.
1614 jars = append(jars, deps.staticHeaderJars...)
1615
1616 // we cannot skip the combine step for now if there is only one jar
1617 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1618 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1619 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1620 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross3d56ed52021-11-18 22:23:12 -08001621 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001622
1623 if j.expandJarjarRules != nil {
1624 // Transform classes.jar into classes-jarjar.jar
1625 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross3d56ed52021-11-18 22:23:12 -08001626 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1627 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001628 if ctx.Failed() {
1629 return nil, nil
1630 }
1631 }
1632
Colin Cross3d56ed52021-11-18 22:23:12 -08001633 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001634}
1635
1636func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001637 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001638
1639 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1640 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1641
1642 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1643
1644 j.jacocoReportClassesFile = jacocoReportClassesFile
1645
1646 return instrumentedJar
1647}
1648
1649func (j *Module) HeaderJars() android.Paths {
1650 if j.headerJarFile == nil {
1651 return nil
1652 }
1653 return android.Paths{j.headerJarFile}
1654}
1655
1656func (j *Module) ImplementationJars() android.Paths {
1657 if j.implementationJarFile == nil {
1658 return nil
1659 }
1660 return android.Paths{j.implementationJarFile}
1661}
1662
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001663func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001664 return j.dexJarFile
1665}
1666
1667func (j *Module) DexJarInstallPath() android.Path {
1668 return j.installFile
1669}
1670
1671func (j *Module) ImplementationAndResourcesJars() android.Paths {
1672 if j.implementationAndResourcesJar == nil {
1673 return nil
1674 }
1675 return android.Paths{j.implementationAndResourcesJar}
1676}
1677
1678func (j *Module) AidlIncludeDirs() android.Paths {
1679 // exportAidlIncludeDirs is type android.Paths already
1680 return j.exportAidlIncludeDirs
1681}
1682
1683func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1684 return j.classLoaderContexts
1685}
1686
1687// Collect information for opening IDE project files in java/jdeps.go.
1688func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1689 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1690 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1691 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1692 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1693 if j.expandJarjarRules != nil {
1694 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1695 }
1696 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
Yikef6282022022-04-13 20:41:01 +08001697 dpInfo.Static_libs = append(dpInfo.Static_libs, j.properties.Static_libs...)
1698 dpInfo.Libs = append(dpInfo.Libs, j.properties.Libs...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001699}
1700
1701func (j *Module) CompilerDeps() []string {
1702 jdeps := []string{}
1703 jdeps = append(jdeps, j.properties.Libs...)
1704 jdeps = append(jdeps, j.properties.Static_libs...)
1705 return jdeps
1706}
1707
1708func (j *Module) hasCode(ctx android.ModuleContext) bool {
1709 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1710 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1711}
1712
1713// Implements android.ApexModule
1714func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1715 return j.depIsInSameApex(ctx, dep)
1716}
1717
1718// Implements android.ApexModule
satayev758968a2021-12-06 11:42:40 +00001719func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001720 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001721 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001722 return fmt.Errorf("min_sdk_version is not specified")
1723 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001724 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001725 return nil
1726 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001727 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1728 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001729 }
1730 return nil
1731}
1732
1733func (j *Module) Stem() string {
Jooyung Han01d80d82022-01-08 12:16:32 +09001734 return proptools.StringDefault(j.overridableDeviceProperties.Stem, j.Name())
Jaewoong Jung26342642021-03-17 15:56:23 -07001735}
1736
Jaewoong Jung26342642021-03-17 15:56:23 -07001737func (j *Module) JacocoReportClassesFile() android.Path {
1738 return j.jacocoReportClassesFile
1739}
1740
1741func (j *Module) IsInstallable() bool {
1742 return Bool(j.properties.Installable)
1743}
1744
1745type sdkLinkType int
1746
1747const (
1748 // TODO(jiyong) rename these for better readability. Make the allowed
1749 // and disallowed link types explicit
1750 // order is important here. See rank()
1751 javaCore sdkLinkType = iota
1752 javaSdk
1753 javaSystem
1754 javaModule
1755 javaSystemServer
1756 javaPlatform
1757)
1758
1759func (lt sdkLinkType) String() string {
1760 switch lt {
1761 case javaCore:
1762 return "core Java API"
1763 case javaSdk:
1764 return "Android API"
1765 case javaSystem:
1766 return "system API"
1767 case javaModule:
1768 return "module API"
1769 case javaSystemServer:
1770 return "system server API"
1771 case javaPlatform:
1772 return "private API"
1773 default:
1774 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1775 }
1776}
1777
1778// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1779// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1780// can't statically depend on modules that use Platform API.
1781func (lt sdkLinkType) rank() int {
1782 return int(lt)
1783}
1784
1785type moduleWithSdkDep interface {
1786 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001787 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001788}
1789
Jiyong Park92315372021-04-02 08:45:46 +09001790func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001791 switch name {
1792 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1793 "stub-annotations", "private-stub-annotations-jar",
1794 "core-lambda-stubs", "core-generated-annotation-stubs":
1795 return javaCore, true
1796 case "android_stubs_current":
1797 return javaSdk, true
1798 case "android_system_stubs_current":
1799 return javaSystem, true
1800 case "android_module_lib_stubs_current":
1801 return javaModule, true
1802 case "android_system_server_stubs_current":
1803 return javaSystemServer, true
1804 case "android_test_stubs_current":
1805 return javaSystem, true
1806 }
1807
1808 if stub, linkType := moduleStubLinkType(name); stub {
1809 return linkType, true
1810 }
1811
Jiyong Park92315372021-04-02 08:45:46 +09001812 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001813 switch ver.Kind {
1814 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001815 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001816 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001817 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001818 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001819 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001820 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001821 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001822 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001823 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001824 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001825 return javaPlatform, false
1826 }
1827
Jiyong Parkf1691d22021-03-29 20:11:58 +09001828 if !ver.Valid() {
1829 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001830 }
1831 return javaSdk, false
1832}
1833
1834// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1835// this module's. See the comment on rank() for details and an example.
1836func (j *Module) checkSdkLinkType(
1837 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1838 if ctx.Host() {
1839 return
1840 }
1841
Jiyong Park92315372021-04-02 08:45:46 +09001842 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001843 if stubs {
1844 return
1845 }
Jiyong Park92315372021-04-02 08:45:46 +09001846 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001847
1848 if myLinkType.rank() < depLinkType.rank() {
1849 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1850 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1851 "property of the source or target module so that target module is built "+
1852 "with the same or smaller API set when compared to the source.",
1853 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1854 }
1855}
1856
1857func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1858 var deps deps
1859
1860 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001861 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001862 if sdkDep.invalidVersion {
1863 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1864 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1865 } else if sdkDep.useFiles {
1866 // sdkDep.jar is actually equivalent to turbine header.jar.
1867 deps.classpath = append(deps.classpath, sdkDep.jars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001868 deps.dexClasspath = append(deps.dexClasspath, sdkDep.jars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001869 deps.aidlPreprocess = sdkDep.aidl
1870 } else {
1871 deps.aidlPreprocess = sdkDep.aidl
1872 }
1873 }
1874
Jiyong Park92315372021-04-02 08:45:46 +09001875 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001876
1877 ctx.VisitDirectDeps(func(module android.Module) {
1878 otherName := ctx.OtherModuleName(module)
1879 tag := ctx.OtherModuleDependencyTag(module)
1880
1881 if IsJniDepTag(tag) {
1882 // Handled by AndroidApp.collectAppDeps
1883 return
1884 }
1885 if tag == certificateTag {
1886 // Handled by AndroidApp.collectAppDeps
1887 return
1888 }
1889
1890 if dep, ok := module.(SdkLibraryDependency); ok {
1891 switch tag {
1892 case libTag:
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001893 depHeaderJars := dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))
1894 deps.classpath = append(deps.classpath, depHeaderJars...)
1895 deps.dexClasspath = append(deps.dexClasspath, depHeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001896 case staticLibTag:
1897 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1898 }
1899 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1900 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1901 if sdkLinkType != javaPlatform &&
1902 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1903 // dep is a sysprop implementation library, but this module is not linking against
1904 // the platform, so it gets the sysprop public stubs library instead. Replace
1905 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1906 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1907 dep = syspropDep.JavaInfo
1908 }
1909 switch tag {
1910 case bootClasspathTag:
1911 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1912 case libTag, instrumentationForTag:
1913 deps.classpath = append(deps.classpath, dep.HeaderJars...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001914 deps.dexClasspath = append(deps.dexClasspath, dep.HeaderJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001915 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1916 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1917 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1918 case java9LibTag:
1919 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1920 case staticLibTag:
1921 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1922 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1923 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1924 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1925 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1926 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1927 // Turbine doesn't run annotation processors, so any module that uses an
1928 // annotation processor that generates API is incompatible with the turbine
1929 // optimization.
1930 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1931 case pluginTag:
1932 if plugin, ok := module.(*Plugin); ok {
1933 if plugin.pluginProperties.Processor_class != nil {
1934 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1935 } else {
1936 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1937 }
1938 // Turbine doesn't run annotation processors, so any module that uses an
1939 // annotation processor that generates API is incompatible with the turbine
1940 // optimization.
1941 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1942 } else {
1943 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1944 }
1945 case errorpronePluginTag:
1946 if _, ok := module.(*Plugin); ok {
1947 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1948 } else {
1949 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1950 }
1951 case exportedPluginTag:
1952 if plugin, ok := module.(*Plugin); ok {
1953 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1954 if plugin.pluginProperties.Processor_class != nil {
1955 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1956 }
1957 // Turbine doesn't run annotation processors, so any module that uses an
1958 // annotation processor that generates API is incompatible with the turbine
1959 // optimization.
1960 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1961 } else {
1962 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1963 }
1964 case kotlinStdlibTag:
1965 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1966 case kotlinAnnotationsTag:
1967 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001968 case kotlinPluginTag:
1969 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001970 case syspropPublicStubDepTag:
1971 // This is a sysprop implementation library, forward the JavaInfoProvider from
1972 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1973 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1974 JavaInfo: dep,
1975 })
1976 }
1977 } else if dep, ok := module.(android.SourceFileProducer); ok {
1978 switch tag {
1979 case libTag:
1980 checkProducesJars(ctx, dep)
1981 deps.classpath = append(deps.classpath, dep.Srcs()...)
Colin Cross9bb9bfb2022-03-17 11:12:32 -07001982 deps.dexClasspath = append(deps.classpath, dep.Srcs()...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001983 case staticLibTag:
1984 checkProducesJars(ctx, dep)
1985 deps.classpath = append(deps.classpath, dep.Srcs()...)
1986 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1987 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1988 }
1989 } else {
1990 switch tag {
1991 case bootClasspathTag:
1992 // If a system modules dependency has been added to the bootclasspath
1993 // then add its libs to the bootclasspath.
1994 sm := module.(SystemModulesProvider)
1995 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1996
1997 case systemModulesTag:
1998 if deps.systemModules != nil {
1999 panic("Found two system module dependencies")
2000 }
2001 sm := module.(SystemModulesProvider)
2002 outputDir, outputDeps := sm.OutputDirAndDeps()
2003 deps.systemModules = &systemModules{outputDir, outputDeps}
Paul Duffin53a70a42022-01-11 14:35:55 +00002004
2005 case instrumentationForTag:
2006 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 -07002007 }
2008 }
2009
2010 addCLCFromDep(ctx, module, j.classLoaderContexts)
2011 })
2012
2013 return deps
2014}
2015
2016func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
2017 deps.processorPath = append(deps.processorPath, pluginJars...)
2018 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
2019}
2020
2021// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
2022// this interface.
2023type ProvidesUsesLib interface {
2024 ProvidesUsesLib() *string
2025}
2026
2027func (j *Module) ProvidesUsesLib() *string {
2028 return j.usesLibraryProperties.Provides_uses_lib
2029}
satayev1c564cc2021-05-25 19:50:30 +01002030
2031type ModuleWithStem interface {
2032 Stem() string
2033}
2034
2035var _ ModuleWithStem = (*Module)(nil)
Wei Libafb6d62021-12-10 03:14:59 -08002036
2037func (j *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
2038 switch ctx.ModuleType() {
Sam Delmericofde9fb52022-01-28 20:53:38 +00002039 case "java_library", "java_library_host", "java_library_static":
Wei Libafb6d62021-12-10 03:14:59 -08002040 if lib, ok := ctx.Module().(*Library); ok {
2041 javaLibraryBp2Build(ctx, lib)
2042 }
2043 case "java_binary_host":
2044 if binary, ok := ctx.Module().(*Binary); ok {
2045 javaBinaryHostBp2Build(ctx, binary)
2046 }
2047 }
Wei Libafb6d62021-12-10 03:14:59 -08002048}