blob: 73e5352f0a604d00693d8bf7cdc5a7e6ecb335c4 [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
158 }
159
160 Proto struct {
161 // List of extra options that will be passed to the proto generator.
162 Output_params []string
163 }
164
165 Instrument bool `blueprint:"mutated"`
166
167 // List of files to include in the META-INF/services folder of the resulting jar.
168 Services []string `android:"path,arch_variant"`
169
170 // If true, package the kotlin stdlib into the jar. Defaults to true.
171 Static_kotlin_stdlib *bool `android:"arch_variant"`
172
173 // A list of java_library instances that provide additional hiddenapi annotations for the library.
174 Hiddenapi_additional_annotations []string
175}
176
177// Properties that are specific to device modules. Host module factories should not add these when
178// constructing a new module.
179type DeviceProperties struct {
180 // if not blank, set to the version of the sdk to compile against.
181 // Defaults to compiling against the current platform.
182 Sdk_version *string
183
184 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
185 // Defaults to sdk_version if not set.
186 Min_sdk_version *string
187
188 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
189 // Defaults to sdk_version if not set.
190 Target_sdk_version *string
191
192 // Whether to compile against the platform APIs instead of an SDK.
193 // If true, then sdk_version must be empty. The value of this field
194 // is ignored when module's type isn't android_app.
195 Platform_apis *bool
196
197 Aidl struct {
198 // Top level directories to pass to aidl tool
199 Include_dirs []string
200
201 // Directories rooted at the Android.bp file to pass to aidl tool
202 Local_include_dirs []string
203
204 // directories that should be added as include directories for any aidl sources of modules
205 // that depend on this module, as well as to aidl for this module.
206 Export_include_dirs []string
207
208 // whether to generate traces (for systrace) for this interface
209 Generate_traces *bool
210
211 // whether to generate Binder#GetTransaction name method.
212 Generate_get_transaction_name *bool
213
214 // list of flags that will be passed to the AIDL compiler
215 Flags []string
216 }
217
218 // If true, export a copy of the module as a -hostdex module for host testing.
219 Hostdex *bool
220
221 Target struct {
222 Hostdex struct {
223 // Additional required dependencies to add to -hostdex modules.
224 Required []string
225 }
226 }
227
228 // When targeting 1.9 and above, override the modules to use with --system,
229 // otherwise provides defaults libraries to add to the bootclasspath.
230 System_modules *string
231
232 // The name of the module as used in build configuration.
233 //
234 // Allows a library to separate its actual name from the name used in
235 // build configuration, e.g.ctx.Config().BootJars().
236 ConfigurationName *string `blueprint:"mutated"`
237
238 // set the name of the output
239 Stem *string
240
241 IsSDKLibrary bool `blueprint:"mutated"`
242
243 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
244 // Defaults to false.
245 V4_signature *bool
246
247 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
248 // public stubs library.
249 SyspropPublicStub string `blueprint:"mutated"`
250}
251
252// Functionality common to Module and Import
253//
254// It is embedded in Module so its functionality can be used by methods in Module
255// but it is currently only initialized by Import and Library.
256type embeddableInModuleAndImport struct {
257
258 // Functionality related to this being used as a component of a java_sdk_library.
259 EmbeddableSdkLibraryComponent
260}
261
262func (e *embeddableInModuleAndImport) initModuleAndImport(moduleBase *android.ModuleBase) {
263 e.initSdkLibraryComponent(moduleBase)
264}
265
266// Module/Import's DepIsInSameApex(...) delegates to this method.
267//
268// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
269// the one provided by ApexModuleBase.
270func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
271 // dependencies other than the static linkage are all considered crossing APEX boundary
272 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
273 return true
274 }
275 return false
276}
277
278// Module contains the properties and members used by all java module types
279type Module struct {
280 android.ModuleBase
281 android.DefaultableModuleBase
282 android.ApexModuleBase
283 android.SdkBase
284
285 // Functionality common to Module and Import.
286 embeddableInModuleAndImport
287
288 properties CommonProperties
289 protoProperties android.ProtoProperties
290 deviceProperties DeviceProperties
291
292 // jar file containing header classes including static library dependencies, suitable for
293 // inserting into the bootclasspath/classpath of another compile
294 headerJarFile android.Path
295
296 // jar file containing implementation classes including static library dependencies but no
297 // resources
298 implementationJarFile android.Path
299
300 // jar file containing only resources including from static library dependencies
301 resourceJar android.Path
302
303 // args and dependencies to package source files into a srcjar
304 srcJarArgs []string
305 srcJarDeps android.Paths
306
307 // jar file containing implementation classes and resources including static library
308 // dependencies
309 implementationAndResourcesJar android.Path
310
311 // output file containing classes.dex and resources
312 dexJarFile android.Path
313
314 // output file containing uninstrumented classes that will be instrumented by jacoco
315 jacocoReportClassesFile android.Path
316
317 // output file of the module, which may be a classes jar or a dex jar
318 outputFile android.Path
319 extraOutputFiles android.Paths
320
321 exportAidlIncludeDirs android.Paths
322
323 logtagsSrcs android.Paths
324
325 // installed file for binary dependency
326 installFile android.Path
327
328 // list of .java files and srcjars that was passed to javac
329 compiledJavaSrcs android.Paths
330 compiledSrcJars android.Paths
331
332 // manifest file to use instead of properties.Manifest
333 overrideManifest android.OptionalPath
334
335 // map of SDK version to class loader context
336 classLoaderContexts dexpreopt.ClassLoaderContextMap
337
338 // list of plugins that this java module is exporting
339 exportedPluginJars android.Paths
340
341 // list of plugins that this java module is exporting
342 exportedPluginClasses []string
343
344 // if true, the exported plugins generate API and require disabling turbine.
345 exportedDisableTurbine bool
346
347 // list of source files, collected from srcFiles with unique java and all kt files,
348 // will be used by android.IDEInfo struct
349 expandIDEInfoCompiledSrcs []string
350
351 // expanded Jarjar_rules
352 expandJarjarRules android.Path
353
354 // list of additional targets for checkbuild
355 additionalCheckedModules android.Paths
356
357 // Extra files generated by the module type to be added as java resources.
358 extraResources android.Paths
359
360 hiddenAPI
361 dexer
362 dexpreopter
363 usesLibrary
364 linter
365
366 // list of the xref extraction files
367 kytheFiles android.Paths
368
369 // Collect the module directory for IDE info in java/jdeps.go.
370 modulePaths []string
371
372 hideApexVariantFromMake bool
373}
374
375func (j *Module) CheckStableSdkVersion() error {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900376 sdkVersion := j.SdkVersion()
377 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700378 return nil
379 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900380 if sdkVersion.Kind == android.SdkCorePlatform {
Jaewoong Jung26342642021-03-17 15:56:23 -0700381 if useLegacyCorePlatformApiByName(j.BaseModuleName()) {
382 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
383 } else {
384 // Treat stable core platform as stable.
385 return nil
386 }
387 } else {
388 return fmt.Errorf("non stable SDK %v", sdkVersion)
389 }
390}
391
392// checkSdkVersions enforces restrictions around SDK dependencies.
393func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
394 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900395 if sc, ok := ctx.Module().(android.SdkContext); ok {
396 if !sc.SdkVersion().Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700397 ctx.PropertyErrorf("sdk_version",
398 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
399 }
400 }
401 }
402
403 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
404 // See rank() for details.
405 ctx.VisitDirectDeps(func(module android.Module) {
406 tag := ctx.OtherModuleDependencyTag(module)
407 switch module.(type) {
408 // TODO(satayev): cover other types as well, e.g. imports
409 case *Library, *AndroidLibrary:
410 switch tag {
411 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
412 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
413 }
414 }
415 })
416}
417
418func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900419 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700420 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900421 sdkVersionSpecified := sc.SdkVersion().Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700422 if usePlatformAPI && sdkVersionSpecified {
423 ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
424 } else if !usePlatformAPI && !sdkVersionSpecified {
425 ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
426 }
427
428 }
429}
430
431func (j *Module) addHostProperties() {
432 j.AddProperties(
433 &j.properties,
434 &j.protoProperties,
435 &j.usesLibraryProperties,
436 )
437}
438
439func (j *Module) addHostAndDeviceProperties() {
440 j.addHostProperties()
441 j.AddProperties(
442 &j.deviceProperties,
443 &j.dexer.dexProperties,
444 &j.dexpreoptProperties,
445 &j.linter.properties,
446 )
447}
448
449func (j *Module) OutputFiles(tag string) (android.Paths, error) {
450 switch tag {
451 case "":
452 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
453 case android.DefaultDistTag:
454 return android.Paths{j.outputFile}, nil
455 case ".jar":
456 return android.Paths{j.implementationAndResourcesJar}, nil
457 case ".proguard_map":
458 if j.dexer.proguardDictionary.Valid() {
459 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
460 }
461 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
462 default:
463 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
464 }
465}
466
467var _ android.OutputFileProducer = (*Module)(nil)
468
469func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
470 initJavaModule(module, hod, false)
471}
472
473func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
474 initJavaModule(module, hod, true)
475}
476
477func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
478 multilib := android.MultilibCommon
479 if multiTargets {
480 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
481 } else {
482 android.InitAndroidArchModule(module, hod, multilib)
483 }
484 android.InitDefaultableModule(module)
485}
486
487func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
488 return j.properties.Instrument &&
489 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
490 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
491}
492
493func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
494 return j.shouldInstrument(ctx) &&
495 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
496 ctx.Config().UnbundledBuild())
497}
498
499func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
500 // Force enable the instrumentation for java code that is built for APEXes ...
501 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
502 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
503 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
504 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
505 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
506 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
507 return true
508 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
509 return true
510 }
511 }
512 return false
513}
514
Jiyong Parkf1691d22021-03-29 20:11:58 +0900515func (j *Module) SdkVersion() android.SdkSpec {
516 return android.SdkSpecFrom(String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700517}
518
Jiyong Parkf1691d22021-03-29 20:11:58 +0900519func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700520 return proptools.String(j.deviceProperties.System_modules)
521}
522
Jiyong Parkf1691d22021-03-29 20:11:58 +0900523func (j *Module) MinSdkVersion() android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700524 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900525 return android.SdkSpecFrom(*j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700526 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900527 return j.SdkVersion()
Jaewoong Jung26342642021-03-17 15:56:23 -0700528}
529
Jiyong Parkf1691d22021-03-29 20:11:58 +0900530func (j *Module) TargetSdkVersion() android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700531 if j.deviceProperties.Target_sdk_version != nil {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900532 return android.SdkSpecFrom(*j.deviceProperties.Target_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700533 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900534 return j.SdkVersion()
Jaewoong Jung26342642021-03-17 15:56:23 -0700535}
536
Jiyong Parkf1691d22021-03-29 20:11:58 +0900537func (j *Module) MinSdkVersionString() string {
538 return j.MinSdkVersion().Version.String()
Jaewoong Jung26342642021-03-17 15:56:23 -0700539}
540
541func (j *Module) AvailableFor(what string) bool {
542 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
543 // Exception: for hostdex: true libraries, the platform variant is created
544 // even if it's not marked as available to platform. In that case, the platform
545 // variant is used only for the hostdex and not installed to the device.
546 return true
547 }
548 return j.ApexModuleBase.AvailableFor(what)
549}
550
551func (j *Module) deps(ctx android.BottomUpMutatorContext) {
552 if ctx.Device() {
553 j.linter.deps(ctx)
554
Jiyong Parkf1691d22021-03-29 20:11:58 +0900555 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700556
557 if j.deviceProperties.SyspropPublicStub != "" {
558 // This is a sysprop implementation library that has a corresponding sysprop public
559 // stubs library, and a dependency on it so that dependencies on the implementation can
560 // be forwarded to the public stubs library when necessary.
561 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
562 }
563 }
564
565 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
566 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
567
568 // Add dependency on libraries that provide additional hidden api annotations.
569 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
570
571 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
572 // Require java_sdk_library at inter-partition java dependency to ensure stable
573 // interface between partitions. If inter-partition java_library dependency is detected,
574 // raise build error because java_library doesn't have a stable interface.
575 //
576 // Inputs:
577 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
578 // if true, enable enforcement
579 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
580 // exception list of java_library names to allow inter-partition dependency
581 for idx := range j.properties.Libs {
582 if libDeps[idx] == nil {
583 continue
584 }
585
586 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
587 // java_sdk_library is always allowed at inter-partition dependency.
588 // So, skip check.
589 if _, ok := javaDep.(*SdkLibrary); ok {
590 continue
591 }
592
593 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
594 }
595 }
596 }
597
598 // For library dependencies that are component libraries (like stubs), add the implementation
599 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
600 for _, dep := range libDeps {
601 if dep != nil {
602 if component, ok := dep.(SdkLibraryComponentDependency); ok {
603 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
604 ctx.AddVariationDependencies(nil, usesLibTag, *lib)
605 }
606 }
607 }
608 }
609
610 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
611 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
612 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
613
614 android.ProtoDeps(ctx, &j.protoProperties)
615 if j.hasSrcExt(".proto") {
616 protoDeps(ctx, &j.protoProperties)
617 }
618
619 if j.hasSrcExt(".kt") {
620 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
621 // Kotlin files
622 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
623 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
624 if len(j.properties.Plugins) > 0 {
625 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
626 }
627 }
628
629 // Framework libraries need special handling in static coverage builds: they should not have
630 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
631 // the same jacoco classes coming from different bootclasspath jars.
632 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
633 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
634 j.properties.Instrument = true
635 }
636 } else if j.shouldInstrumentStatic(ctx) {
637 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
638 }
639}
640
641func hasSrcExt(srcs []string, ext string) bool {
642 for _, src := range srcs {
643 if filepath.Ext(src) == ext {
644 return true
645 }
646 }
647
648 return false
649}
650
651func (j *Module) hasSrcExt(ext string) bool {
652 return hasSrcExt(j.properties.Srcs, ext)
653}
654
655func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
656 aidlIncludeDirs android.Paths) (string, android.Paths) {
657
658 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
659 aidlIncludes = append(aidlIncludes,
660 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
661 aidlIncludes = append(aidlIncludes,
662 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
663
664 var flags []string
665 var deps android.Paths
666
667 flags = append(flags, j.deviceProperties.Aidl.Flags...)
668
669 if aidlPreprocess.Valid() {
670 flags = append(flags, "-p"+aidlPreprocess.String())
671 deps = append(deps, aidlPreprocess.Path())
672 } else if len(aidlIncludeDirs) > 0 {
673 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
674 }
675
676 if len(j.exportAidlIncludeDirs) > 0 {
677 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
678 }
679
680 if len(aidlIncludes) > 0 {
681 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
682 }
683
684 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
685 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
686 flags = append(flags, "-I"+src.String())
687 }
688
689 if Bool(j.deviceProperties.Aidl.Generate_traces) {
690 flags = append(flags, "-t")
691 }
692
693 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
694 flags = append(flags, "--transaction_names")
695 }
696
697 return strings.Join(flags, " "), deps
698}
699
700func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
701
702 var flags javaBuilderFlags
703
704 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900705 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700706
707 if ctx.Config().RunErrorProne() {
708 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
709 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
710 }
711
712 errorProneFlags := []string{
713 "-Xplugin:ErrorProne",
714 "${config.ErrorProneChecks}",
715 }
716 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
717
718 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
719 "'" + strings.Join(errorProneFlags, " ") + "'"
720 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
721 }
722
723 // classpath
724 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
725 flags.classpath = append(flags.classpath, deps.classpath...)
726 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
727 flags.processorPath = append(flags.processorPath, deps.processorPath...)
728 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
729
730 flags.processors = append(flags.processors, deps.processorClasses...)
731 flags.processors = android.FirstUniqueStrings(flags.processors)
732
733 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900734 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700735 // Give host-side tools a version of OpenJDK's standard libraries
736 // close to what they're targeting. As of Dec 2017, AOSP is only
737 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
738 //
739 // When building with OpenJDK 8, the following should have no
740 // effect since those jars would be available by default.
741 //
742 // When building with OpenJDK 9 but targeting a version < 1.8,
743 // putting them on the bootclasspath means that:
744 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
745 // b) references to existing APIs are not reinterpreted in an
746 // OpenJDK 9-specific way, eg. calls to subclasses of
747 // java.nio.Buffer as in http://b/70862583
748 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
749 flags.bootClasspath = append(flags.bootClasspath,
750 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
751 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
752 if Bool(j.properties.Use_tools_jar) {
753 flags.bootClasspath = append(flags.bootClasspath,
754 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
755 }
756 }
757
758 // systemModules
759 flags.systemModules = deps.systemModules
760
761 // aidl flags.
762 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
763
764 return flags
765}
766
767func (j *Module) collectJavacFlags(
768 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
769 // javac flags.
770 javacFlags := j.properties.Javacflags
771
772 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
773 // For non-host binaries, override the -g flag passed globally to remove
774 // local variable debug info to reduce disk and memory usage.
775 javacFlags = append(javacFlags, "-g:source,lines")
776 }
777 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
778
779 if flags.javaVersion.usesJavaModules() {
780 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
781
782 if j.properties.Patch_module != nil {
783 // Manually specify build directory in case it is not under the repo root.
784 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
785 // just adding a symlink under the root doesn't help.)
786 patchPaths := []string{".", ctx.Config().BuildDir()}
787
788 // b/150878007
789 //
790 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
791 // execution root for --patch-module. If this javac command line is
792 // invoked within Bazel's execution root working directory, the top
793 // level directories (e.g. libcore/, tools/, frameworks/) are all
794 // symlinks. JDK9 javac does not traverse into symlinks, which causes
795 // --patch-module to fail source file lookups when invoked in the
796 // execution root.
797 //
798 // Short of patching javac or enumerating *all* directories as possible
799 // input dirs, manually add the top level dir of the source files to be
800 // compiled.
801 topLevelDirs := map[string]bool{}
802 for _, srcFilePath := range srcFiles {
803 srcFileParts := strings.Split(srcFilePath.String(), "/")
804 // Ignore source files that are already in the top level directory
805 // as well as generated files in the out directory. The out
806 // directory may be an absolute path, which means srcFileParts[0] is the
807 // empty string, so check that as well. Note that "out" in Bazel's execution
808 // root is *not* a symlink, which doesn't cause problems for --patch-modules
809 // anyway, so it's fine to not apply this workaround for generated
810 // source files.
811 if len(srcFileParts) > 1 &&
812 srcFileParts[0] != "" &&
813 srcFileParts[0] != "out" {
814 topLevelDirs[srcFileParts[0]] = true
815 }
816 }
817 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
818
819 classPath := flags.classpath.FormJavaClassPath("")
820 if classPath != "" {
821 patchPaths = append(patchPaths, classPath)
822 }
823 javacFlags = append(
824 javacFlags,
825 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
826 }
827 }
828
829 if len(javacFlags) > 0 {
830 // optimization.
831 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
832 flags.javacFlags = "$javacFlags"
833 }
834
835 return flags
836}
837
838func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
839 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
840
841 deps := j.collectDeps(ctx)
842 flags := j.collectBuilderFlags(ctx, deps)
843
844 if flags.javaVersion.usesJavaModules() {
845 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
846 }
847 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
848 if hasSrcExt(srcFiles.Strings(), ".proto") {
849 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
850 }
851
852 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
853 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
854 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
855 }
856
857 srcFiles = j.genSources(ctx, srcFiles, flags)
858
859 // Collect javac flags only after computing the full set of srcFiles to
860 // ensure that the --patch-module lookup paths are complete.
861 flags = j.collectJavacFlags(ctx, flags, srcFiles)
862
863 srcJars := srcFiles.FilterByExt(".srcjar")
864 srcJars = append(srcJars, deps.srcJars...)
865 if aaptSrcJar != nil {
866 srcJars = append(srcJars, aaptSrcJar)
867 }
868
869 if j.properties.Jarjar_rules != nil {
870 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
871 }
872
873 jarName := ctx.ModuleName() + ".jar"
874
875 javaSrcFiles := srcFiles.FilterByExt(".java")
876 var uniqueSrcFiles android.Paths
877 set := make(map[string]bool)
878 for _, v := range javaSrcFiles {
879 if _, found := set[v.String()]; !found {
880 set[v.String()] = true
881 uniqueSrcFiles = append(uniqueSrcFiles, v)
882 }
883 }
884
885 // Collect .java files for AIDEGen
886 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
887
888 var kotlinJars android.Paths
889
890 if srcFiles.HasExt(".kt") {
891 // user defined kotlin flags.
892 kotlincFlags := j.properties.Kotlincflags
893 CheckKotlincFlags(ctx, kotlincFlags)
894
895 // Dogfood the JVM_IR backend.
896 kotlincFlags = append(kotlincFlags, "-Xuse-ir")
897
898 // If there are kotlin files, compile them first but pass all the kotlin and java files
899 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
900 // won't emit any classes for them.
901 kotlincFlags = append(kotlincFlags, "-no-stdlib")
902 if ctx.Device() {
903 kotlincFlags = append(kotlincFlags, "-no-jdk")
904 }
905 if len(kotlincFlags) > 0 {
906 // optimization.
907 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
908 flags.kotlincFlags += "$kotlincFlags"
909 }
910
911 var kotlinSrcFiles android.Paths
912 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
913 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
914
915 // Collect .kt files for AIDEGen
916 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
917 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
918
919 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
920 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
921
922 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
923 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
924
925 if len(flags.processorPath) > 0 {
926 // Use kapt for annotation processing
927 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
928 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
929 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
930 srcJars = append(srcJars, kaptSrcJar)
931 kotlinJars = append(kotlinJars, kaptResJar)
932 // Disable annotation processing in javac, it's already been handled by kapt
933 flags.processorPath = nil
934 flags.processors = nil
935 }
936
937 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
938 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
939 if ctx.Failed() {
940 return
941 }
942
943 // Make javac rule depend on the kotlinc rule
944 flags.classpath = append(flags.classpath, kotlinJar)
945
946 kotlinJars = append(kotlinJars, kotlinJar)
947 // Jar kotlin classes into the final jar after javac
948 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
949 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
950 }
951 }
952
953 jars := append(android.Paths(nil), kotlinJars...)
954
955 // Store the list of .java files that was passed to javac
956 j.compiledJavaSrcs = uniqueSrcFiles
957 j.compiledSrcJars = srcJars
958
959 enableSharding := false
960 var headerJarFileWithoutJarjar android.Path
961 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
962 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
963 enableSharding = true
964 // Formerly, there was a check here that prevented annotation processors
965 // from being used when sharding was enabled, as some annotation processors
966 // do not function correctly in sharded environments. It was removed to
967 // allow for the use of annotation processors that do function correctly
968 // with sharding enabled. See: b/77284273.
969 }
970 headerJarFileWithoutJarjar, j.headerJarFile =
971 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
972 if ctx.Failed() {
973 return
974 }
975 }
976 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
977 var extraJarDeps android.Paths
978 if ctx.Config().RunErrorProne() {
979 // If error-prone is enabled, add an additional rule to compile the java files into
980 // a separate set of classes (so that they don't overwrite the normal ones and require
981 // a rebuild when error-prone is turned off).
982 // TODO(ccross): Once we always compile with javac9 we may be able to conditionally
983 // enable error-prone without affecting the output class files.
984 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
985 RunErrorProne(ctx, errorprone, uniqueSrcFiles, srcJars, flags)
986 extraJarDeps = append(extraJarDeps, errorprone)
987 }
988
989 if enableSharding {
990 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
991 shardSize := int(*(j.properties.Javac_shard_size))
992 var shardSrcs []android.Paths
993 if len(uniqueSrcFiles) > 0 {
994 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
995 for idx, shardSrc := range shardSrcs {
996 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
997 nil, flags, extraJarDeps)
998 jars = append(jars, classes)
999 }
1000 }
1001 if len(srcJars) > 0 {
1002 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1003 nil, srcJars, flags, extraJarDeps)
1004 jars = append(jars, classes)
1005 }
1006 } else {
1007 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1008 jars = append(jars, classes)
1009 }
1010 if ctx.Failed() {
1011 return
1012 }
1013 }
1014
1015 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1016
1017 var includeSrcJar android.WritablePath
1018 if Bool(j.properties.Include_srcs) {
1019 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1020 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1021 }
1022
1023 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1024 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1025 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1026 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1027
1028 var resArgs []string
1029 var resDeps android.Paths
1030
1031 resArgs = append(resArgs, dirArgs...)
1032 resDeps = append(resDeps, dirDeps...)
1033
1034 resArgs = append(resArgs, fileArgs...)
1035 resDeps = append(resDeps, fileDeps...)
1036
1037 resArgs = append(resArgs, extraArgs...)
1038 resDeps = append(resDeps, extraDeps...)
1039
1040 if len(resArgs) > 0 {
1041 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1042 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1043 j.resourceJar = resourceJar
1044 if ctx.Failed() {
1045 return
1046 }
1047 }
1048
1049 var resourceJars android.Paths
1050 if j.resourceJar != nil {
1051 resourceJars = append(resourceJars, j.resourceJar)
1052 }
1053 if Bool(j.properties.Include_srcs) {
1054 resourceJars = append(resourceJars, includeSrcJar)
1055 }
1056 resourceJars = append(resourceJars, deps.staticResourceJars...)
1057
1058 if len(resourceJars) > 1 {
1059 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1060 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1061 false, nil, nil)
1062 j.resourceJar = combinedJar
1063 } else if len(resourceJars) == 1 {
1064 j.resourceJar = resourceJars[0]
1065 }
1066
1067 if len(deps.staticJars) > 0 {
1068 jars = append(jars, deps.staticJars...)
1069 }
1070
1071 manifest := j.overrideManifest
1072 if !manifest.Valid() && j.properties.Manifest != nil {
1073 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1074 }
1075
1076 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1077 if len(services) > 0 {
1078 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1079 var zipargs []string
1080 for _, file := range services {
1081 serviceFile := file.String()
1082 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1083 }
1084 rule := zip
1085 args := map[string]string{
1086 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1087 }
1088 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1089 rule = zipRE
1090 args["implicits"] = strings.Join(services.Strings(), ",")
1091 }
1092 ctx.Build(pctx, android.BuildParams{
1093 Rule: rule,
1094 Output: servicesJar,
1095 Implicits: services,
1096 Args: args,
1097 })
1098 jars = append(jars, servicesJar)
1099 }
1100
1101 // Combine the classes built from sources, any manifests, and any static libraries into
1102 // classes.jar. If there is only one input jar this step will be skipped.
1103 var outputFile android.OutputPath
1104
1105 if len(jars) == 1 && !manifest.Valid() {
1106 // Optimization: skip the combine step as there is nothing to do
1107 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1108 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1109 // any if len(jars) == 1.
1110
1111 // Transform the single path to the jar into an OutputPath as that is required by the following
1112 // code.
1113 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1114 // The path contains an embedded OutputPath so reuse that.
1115 outputFile = moduleOutPath.OutputPath
1116 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1117 // The path is an OutputPath so reuse it directly.
1118 outputFile = outputPath
1119 } else {
1120 // The file is not in the out directory so create an OutputPath into which it can be copied
1121 // and which the following code can use to refer to it.
1122 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1123 ctx.Build(pctx, android.BuildParams{
1124 Rule: android.Cp,
1125 Input: jars[0],
1126 Output: combinedJar,
1127 })
1128 outputFile = combinedJar.OutputPath
1129 }
1130 } else {
1131 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1132 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1133 false, nil, nil)
1134 outputFile = combinedJar.OutputPath
1135 }
1136
1137 // jarjar implementation jar if necessary
1138 if j.expandJarjarRules != nil {
1139 // Transform classes.jar into classes-jarjar.jar
1140 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1141 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1142 outputFile = jarjarFile
1143
1144 // jarjar resource jar if necessary
1145 if j.resourceJar != nil {
1146 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1147 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1148 j.resourceJar = resourceJarJarFile
1149 }
1150
1151 if ctx.Failed() {
1152 return
1153 }
1154 }
1155
1156 // Check package restrictions if necessary.
1157 if len(j.properties.Permitted_packages) > 0 {
1158 // Check packages and copy to package-checked file.
1159 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1160 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1161 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1162
1163 if ctx.Failed() {
1164 return
1165 }
1166 }
1167
1168 j.implementationJarFile = outputFile
1169 if j.headerJarFile == nil {
1170 j.headerJarFile = j.implementationJarFile
1171 }
1172
1173 if j.shouldInstrumentInApex(ctx) {
1174 j.properties.Instrument = true
1175 }
1176
1177 if j.shouldInstrument(ctx) {
1178 outputFile = j.instrument(ctx, flags, outputFile, jarName)
1179 }
1180
1181 // merge implementation jar with resources if necessary
1182 implementationAndResourcesJar := outputFile
1183 if j.resourceJar != nil {
1184 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1185 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1186 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1187 false, nil, nil)
1188 implementationAndResourcesJar = combinedJar
1189 }
1190
1191 j.implementationAndResourcesJar = implementationAndResourcesJar
1192
1193 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1194 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1195 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1196 if j.dexProperties.Compile_dex == nil {
1197 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1198 }
1199 if j.deviceProperties.Hostdex == nil {
1200 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1201 }
1202 }
1203
1204 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1205 if j.hasCode(ctx) {
1206 if j.shouldInstrumentStatic(ctx) {
1207 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1208 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1209 }
1210 // Dex compilation
1211 var dexOutputFile android.OutputPath
Jiyong Parkf1691d22021-03-29 20:11:58 +09001212 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(), outputFile, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001213 if ctx.Failed() {
1214 return
1215 }
1216
1217 // Hidden API CSV generation and dex encoding
1218 dexOutputFile = j.hiddenAPIExtractAndEncode(ctx, dexOutputFile, j.implementationJarFile,
1219 proptools.Bool(j.dexProperties.Uncompress_dex))
1220
1221 // merge dex jar with resources if necessary
1222 if j.resourceJar != nil {
1223 jars := android.Paths{dexOutputFile, j.resourceJar}
1224 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1225 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1226 false, nil, nil)
1227 if *j.dexProperties.Uncompress_dex {
1228 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1229 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1230 dexOutputFile = combinedAlignedJar
1231 } else {
1232 dexOutputFile = combinedJar
1233 }
1234 }
1235
1236 j.dexJarFile = dexOutputFile
1237
1238 // Dexpreopting
1239 j.dexpreopt(ctx, dexOutputFile)
1240
1241 outputFile = dexOutputFile
1242 } else {
1243 // There is no code to compile into a dex jar, make sure the resources are propagated
1244 // to the APK if this is an app.
1245 outputFile = implementationAndResourcesJar
1246 j.dexJarFile = j.resourceJar
1247 }
1248
1249 if ctx.Failed() {
1250 return
1251 }
1252 } else {
1253 outputFile = implementationAndResourcesJar
1254 }
1255
1256 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001257 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
1258 if v := sdkSpec.Version; v.IsNumbered() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001259 return v.String()
1260 } else {
1261 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1262 }
1263 }
1264
1265 j.linter.name = ctx.ModuleName()
1266 j.linter.srcs = srcFiles
1267 j.linter.srcJars = srcJars
1268 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1269 j.linter.classes = j.implementationJarFile
Jiyong Parkf1691d22021-03-29 20:11:58 +09001270 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion())
1271 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion())
1272 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion())
Jaewoong Jung26342642021-03-17 15:56:23 -07001273 j.linter.javaLanguageLevel = flags.javaVersion.String()
1274 j.linter.kotlinLanguageLevel = "1.3"
1275 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1276 j.linter.buildModuleReportZip = true
1277 }
1278 j.linter.lint(ctx)
1279 }
1280
1281 ctx.CheckbuildFile(outputFile)
1282
1283 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1284 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1285 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1286 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1287 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1288 AidlIncludeDirs: j.exportAidlIncludeDirs,
1289 SrcJarArgs: j.srcJarArgs,
1290 SrcJarDeps: j.srcJarDeps,
1291 ExportedPlugins: j.exportedPluginJars,
1292 ExportedPluginClasses: j.exportedPluginClasses,
1293 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1294 JacocoReportClassesFile: j.jacocoReportClassesFile,
1295 })
1296
1297 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1298 j.outputFile = outputFile.WithoutRel()
1299}
1300
1301func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1302 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1303
1304 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1305 if idx >= 0 {
1306 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1307 jarName += strconv.Itoa(idx)
1308 }
1309
1310 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1311 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1312
1313 if ctx.Config().EmitXrefRules() {
1314 extractionFile := android.PathForModuleOut(ctx, kzipName)
1315 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1316 j.kytheFiles = append(j.kytheFiles, extractionFile)
1317 }
1318
1319 return classes
1320}
1321
1322// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1323// since some of these flags may be used internally.
1324func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1325 for _, flag := range flags {
1326 flag = strings.TrimSpace(flag)
1327
1328 if !strings.HasPrefix(flag, "-") {
1329 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1330 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1331 ctx.PropertyErrorf("kotlincflags",
1332 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1333 } else if inList(flag, config.KotlincIllegalFlags) {
1334 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1335 } else if flag == "-include-runtime" {
1336 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1337 } else {
1338 args := strings.Split(flag, " ")
1339 if args[0] == "-kotlin-home" {
1340 ctx.PropertyErrorf("kotlincflags",
1341 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1342 }
1343 }
1344 }
1345}
1346
1347func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1348 deps deps, flags javaBuilderFlags, jarName string,
1349 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1350
1351 var jars android.Paths
1352 if len(srcFiles) > 0 || len(srcJars) > 0 {
1353 // Compile java sources into turbine.jar.
1354 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1355 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1356 if ctx.Failed() {
1357 return nil, nil
1358 }
1359 jars = append(jars, turbineJar)
1360 }
1361
1362 jars = append(jars, extraJars...)
1363
1364 // Combine any static header libraries into classes-header.jar. If there is only
1365 // one input jar this step will be skipped.
1366 jars = append(jars, deps.staticHeaderJars...)
1367
1368 // we cannot skip the combine step for now if there is only one jar
1369 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1370 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1371 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1372 false, nil, []string{"META-INF/TRANSITIVE"})
1373 headerJar = combinedJar
1374 jarjarHeaderJar = combinedJar
1375
1376 if j.expandJarjarRules != nil {
1377 // Transform classes.jar into classes-jarjar.jar
1378 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1379 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1380 jarjarHeaderJar = jarjarFile
1381 if ctx.Failed() {
1382 return nil, nil
1383 }
1384 }
1385
1386 return headerJar, jarjarHeaderJar
1387}
1388
1389func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
1390 classesJar android.Path, jarName string) android.OutputPath {
1391
1392 specs := j.jacocoModuleToZipCommand(ctx)
1393
1394 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1395 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1396
1397 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1398
1399 j.jacocoReportClassesFile = jacocoReportClassesFile
1400
1401 return instrumentedJar
1402}
1403
1404func (j *Module) HeaderJars() android.Paths {
1405 if j.headerJarFile == nil {
1406 return nil
1407 }
1408 return android.Paths{j.headerJarFile}
1409}
1410
1411func (j *Module) ImplementationJars() android.Paths {
1412 if j.implementationJarFile == nil {
1413 return nil
1414 }
1415 return android.Paths{j.implementationJarFile}
1416}
1417
1418func (j *Module) DexJarBuildPath() android.Path {
1419 return j.dexJarFile
1420}
1421
1422func (j *Module) DexJarInstallPath() android.Path {
1423 return j.installFile
1424}
1425
1426func (j *Module) ImplementationAndResourcesJars() android.Paths {
1427 if j.implementationAndResourcesJar == nil {
1428 return nil
1429 }
1430 return android.Paths{j.implementationAndResourcesJar}
1431}
1432
1433func (j *Module) AidlIncludeDirs() android.Paths {
1434 // exportAidlIncludeDirs is type android.Paths already
1435 return j.exportAidlIncludeDirs
1436}
1437
1438func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1439 return j.classLoaderContexts
1440}
1441
1442// Collect information for opening IDE project files in java/jdeps.go.
1443func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1444 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1445 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1446 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1447 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1448 if j.expandJarjarRules != nil {
1449 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1450 }
1451 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1452}
1453
1454func (j *Module) CompilerDeps() []string {
1455 jdeps := []string{}
1456 jdeps = append(jdeps, j.properties.Libs...)
1457 jdeps = append(jdeps, j.properties.Static_libs...)
1458 return jdeps
1459}
1460
1461func (j *Module) hasCode(ctx android.ModuleContext) bool {
1462 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1463 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1464}
1465
1466// Implements android.ApexModule
1467func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1468 return j.depIsInSameApex(ctx, dep)
1469}
1470
1471// Implements android.ApexModule
1472func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1473 sdkVersion android.ApiLevel) error {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001474 sdkSpec := j.MinSdkVersion()
1475 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001476 return fmt.Errorf("min_sdk_version is not specified")
1477 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001478 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001479 return nil
1480 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001481 ver, err := sdkSpec.EffectiveVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001482 if err != nil {
1483 return err
1484 }
1485 if ver.ApiLevel(ctx).GreaterThan(sdkVersion) {
1486 return fmt.Errorf("newer SDK(%v)", ver)
1487 }
1488 return nil
1489}
1490
1491func (j *Module) Stem() string {
1492 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1493}
1494
1495// ConfigurationName returns the name of the module as used in build configuration.
1496//
1497// This is usually the same as BaseModuleName() except for the <x>.impl libraries created by
1498// java_sdk_library in which case this is the BaseModuleName() without the ".impl" suffix,
1499// i.e. just <x>.
1500func (j *Module) ConfigurationName() string {
1501 return proptools.StringDefault(j.deviceProperties.ConfigurationName, j.BaseModuleName())
1502}
1503
1504func (j *Module) JacocoReportClassesFile() android.Path {
1505 return j.jacocoReportClassesFile
1506}
1507
1508func (j *Module) IsInstallable() bool {
1509 return Bool(j.properties.Installable)
1510}
1511
1512type sdkLinkType int
1513
1514const (
1515 // TODO(jiyong) rename these for better readability. Make the allowed
1516 // and disallowed link types explicit
1517 // order is important here. See rank()
1518 javaCore sdkLinkType = iota
1519 javaSdk
1520 javaSystem
1521 javaModule
1522 javaSystemServer
1523 javaPlatform
1524)
1525
1526func (lt sdkLinkType) String() string {
1527 switch lt {
1528 case javaCore:
1529 return "core Java API"
1530 case javaSdk:
1531 return "Android API"
1532 case javaSystem:
1533 return "system API"
1534 case javaModule:
1535 return "module API"
1536 case javaSystemServer:
1537 return "system server API"
1538 case javaPlatform:
1539 return "private API"
1540 default:
1541 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1542 }
1543}
1544
1545// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1546// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1547// can't statically depend on modules that use Platform API.
1548func (lt sdkLinkType) rank() int {
1549 return int(lt)
1550}
1551
1552type moduleWithSdkDep interface {
1553 android.Module
1554 getSdkLinkType(name string) (ret sdkLinkType, stubs bool)
1555}
1556
1557func (m *Module) getSdkLinkType(name string) (ret sdkLinkType, stubs bool) {
1558 switch name {
1559 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1560 "stub-annotations", "private-stub-annotations-jar",
1561 "core-lambda-stubs", "core-generated-annotation-stubs":
1562 return javaCore, true
1563 case "android_stubs_current":
1564 return javaSdk, true
1565 case "android_system_stubs_current":
1566 return javaSystem, true
1567 case "android_module_lib_stubs_current":
1568 return javaModule, true
1569 case "android_system_server_stubs_current":
1570 return javaSystemServer, true
1571 case "android_test_stubs_current":
1572 return javaSystem, true
1573 }
1574
1575 if stub, linkType := moduleStubLinkType(name); stub {
1576 return linkType, true
1577 }
1578
Jiyong Parkf1691d22021-03-29 20:11:58 +09001579 ver := m.SdkVersion()
1580 switch ver.Kind {
1581 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001582 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001583 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001584 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001585 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001586 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001587 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001588 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001589 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001590 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001591 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001592 return javaPlatform, false
1593 }
1594
Jiyong Parkf1691d22021-03-29 20:11:58 +09001595 if !ver.Valid() {
1596 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001597 }
1598 return javaSdk, false
1599}
1600
1601// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1602// this module's. See the comment on rank() for details and an example.
1603func (j *Module) checkSdkLinkType(
1604 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1605 if ctx.Host() {
1606 return
1607 }
1608
1609 myLinkType, stubs := j.getSdkLinkType(ctx.ModuleName())
1610 if stubs {
1611 return
1612 }
1613 depLinkType, _ := dep.getSdkLinkType(ctx.OtherModuleName(dep))
1614
1615 if myLinkType.rank() < depLinkType.rank() {
1616 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1617 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1618 "property of the source or target module so that target module is built "+
1619 "with the same or smaller API set when compared to the source.",
1620 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1621 }
1622}
1623
1624func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1625 var deps deps
1626
1627 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001628 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001629 if sdkDep.invalidVersion {
1630 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1631 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1632 } else if sdkDep.useFiles {
1633 // sdkDep.jar is actually equivalent to turbine header.jar.
1634 deps.classpath = append(deps.classpath, sdkDep.jars...)
1635 deps.aidlPreprocess = sdkDep.aidl
1636 } else {
1637 deps.aidlPreprocess = sdkDep.aidl
1638 }
1639 }
1640
1641 sdkLinkType, _ := j.getSdkLinkType(ctx.ModuleName())
1642
1643 ctx.VisitDirectDeps(func(module android.Module) {
1644 otherName := ctx.OtherModuleName(module)
1645 tag := ctx.OtherModuleDependencyTag(module)
1646
1647 if IsJniDepTag(tag) {
1648 // Handled by AndroidApp.collectAppDeps
1649 return
1650 }
1651 if tag == certificateTag {
1652 // Handled by AndroidApp.collectAppDeps
1653 return
1654 }
1655
1656 if dep, ok := module.(SdkLibraryDependency); ok {
1657 switch tag {
1658 case libTag:
Jiyong Parkf1691d22021-03-29 20:11:58 +09001659 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion())...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001660 case staticLibTag:
1661 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1662 }
1663 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1664 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1665 if sdkLinkType != javaPlatform &&
1666 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1667 // dep is a sysprop implementation library, but this module is not linking against
1668 // the platform, so it gets the sysprop public stubs library instead. Replace
1669 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1670 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1671 dep = syspropDep.JavaInfo
1672 }
1673 switch tag {
1674 case bootClasspathTag:
1675 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1676 case libTag, instrumentationForTag:
1677 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1678 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1679 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1680 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1681 case java9LibTag:
1682 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1683 case staticLibTag:
1684 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1685 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1686 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1687 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1688 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1689 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1690 // Turbine doesn't run annotation processors, so any module that uses an
1691 // annotation processor that generates API is incompatible with the turbine
1692 // optimization.
1693 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1694 case pluginTag:
1695 if plugin, ok := module.(*Plugin); ok {
1696 if plugin.pluginProperties.Processor_class != nil {
1697 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1698 } else {
1699 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1700 }
1701 // Turbine doesn't run annotation processors, so any module that uses an
1702 // annotation processor that generates API is incompatible with the turbine
1703 // optimization.
1704 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1705 } else {
1706 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1707 }
1708 case errorpronePluginTag:
1709 if _, ok := module.(*Plugin); ok {
1710 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1711 } else {
1712 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1713 }
1714 case exportedPluginTag:
1715 if plugin, ok := module.(*Plugin); ok {
1716 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1717 if plugin.pluginProperties.Processor_class != nil {
1718 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1719 }
1720 // Turbine doesn't run annotation processors, so any module that uses an
1721 // annotation processor that generates API is incompatible with the turbine
1722 // optimization.
1723 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1724 } else {
1725 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1726 }
1727 case kotlinStdlibTag:
1728 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1729 case kotlinAnnotationsTag:
1730 deps.kotlinAnnotations = dep.HeaderJars
1731 case syspropPublicStubDepTag:
1732 // This is a sysprop implementation library, forward the JavaInfoProvider from
1733 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1734 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1735 JavaInfo: dep,
1736 })
1737 }
1738 } else if dep, ok := module.(android.SourceFileProducer); ok {
1739 switch tag {
1740 case libTag:
1741 checkProducesJars(ctx, dep)
1742 deps.classpath = append(deps.classpath, dep.Srcs()...)
1743 case staticLibTag:
1744 checkProducesJars(ctx, dep)
1745 deps.classpath = append(deps.classpath, dep.Srcs()...)
1746 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1747 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1748 }
1749 } else {
1750 switch tag {
1751 case bootClasspathTag:
1752 // If a system modules dependency has been added to the bootclasspath
1753 // then add its libs to the bootclasspath.
1754 sm := module.(SystemModulesProvider)
1755 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1756
1757 case systemModulesTag:
1758 if deps.systemModules != nil {
1759 panic("Found two system module dependencies")
1760 }
1761 sm := module.(SystemModulesProvider)
1762 outputDir, outputDeps := sm.OutputDirAndDeps()
1763 deps.systemModules = &systemModules{outputDir, outputDeps}
1764 }
1765 }
1766
1767 addCLCFromDep(ctx, module, j.classLoaderContexts)
1768 })
1769
1770 return deps
1771}
1772
1773func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1774 deps.processorPath = append(deps.processorPath, pluginJars...)
1775 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1776}
1777
1778// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1779// this interface.
1780type ProvidesUsesLib interface {
1781 ProvidesUsesLib() *string
1782}
1783
1784func (j *Module) ProvidesUsesLib() *string {
1785 return j.usesLibraryProperties.Provides_uses_lib
1786}