blob: ef8c563b789f7a8dbf85beb2a616740d1e6ad4d1 [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
Jiyong Park92315372021-04-02 08:45:46 +0900373
374 sdkVersion android.SdkSpec
375 minSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700376}
377
Jiyong Park92315372021-04-02 08:45:46 +0900378func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
379 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900380 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700381 return nil
382 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900383 if sdkVersion.Kind == android.SdkCorePlatform {
Jaewoong Jung26342642021-03-17 15:56:23 -0700384 if useLegacyCorePlatformApiByName(j.BaseModuleName()) {
385 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
386 } else {
387 // Treat stable core platform as stable.
388 return nil
389 }
390 } else {
391 return fmt.Errorf("non stable SDK %v", sdkVersion)
392 }
393}
394
395// checkSdkVersions enforces restrictions around SDK dependencies.
396func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
397 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900398 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900399 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700400 ctx.PropertyErrorf("sdk_version",
401 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
402 }
403 }
404 }
405
406 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
407 // See rank() for details.
408 ctx.VisitDirectDeps(func(module android.Module) {
409 tag := ctx.OtherModuleDependencyTag(module)
410 switch module.(type) {
411 // TODO(satayev): cover other types as well, e.g. imports
412 case *Library, *AndroidLibrary:
413 switch tag {
414 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
415 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
416 }
417 }
418 })
419}
420
421func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900422 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700423 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900424 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700425 if usePlatformAPI && sdkVersionSpecified {
426 ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
427 } else if !usePlatformAPI && !sdkVersionSpecified {
428 ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
429 }
430
431 }
432}
433
434func (j *Module) addHostProperties() {
435 j.AddProperties(
436 &j.properties,
437 &j.protoProperties,
438 &j.usesLibraryProperties,
439 )
440}
441
442func (j *Module) addHostAndDeviceProperties() {
443 j.addHostProperties()
444 j.AddProperties(
445 &j.deviceProperties,
446 &j.dexer.dexProperties,
447 &j.dexpreoptProperties,
448 &j.linter.properties,
449 )
450}
451
452func (j *Module) OutputFiles(tag string) (android.Paths, error) {
453 switch tag {
454 case "":
455 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
456 case android.DefaultDistTag:
457 return android.Paths{j.outputFile}, nil
458 case ".jar":
459 return android.Paths{j.implementationAndResourcesJar}, nil
460 case ".proguard_map":
461 if j.dexer.proguardDictionary.Valid() {
462 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
463 }
464 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
465 default:
466 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
467 }
468}
469
470var _ android.OutputFileProducer = (*Module)(nil)
471
472func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
473 initJavaModule(module, hod, false)
474}
475
476func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
477 initJavaModule(module, hod, true)
478}
479
480func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
481 multilib := android.MultilibCommon
482 if multiTargets {
483 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
484 } else {
485 android.InitAndroidArchModule(module, hod, multilib)
486 }
487 android.InitDefaultableModule(module)
488}
489
490func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
491 return j.properties.Instrument &&
492 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
493 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
494}
495
496func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
497 return j.shouldInstrument(ctx) &&
498 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
499 ctx.Config().UnbundledBuild())
500}
501
502func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
503 // Force enable the instrumentation for java code that is built for APEXes ...
504 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
505 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
506 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
507 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
508 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
509 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
510 return true
511 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
512 return true
513 }
514 }
515 return false
516}
517
Jiyong Park92315372021-04-02 08:45:46 +0900518func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
519 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700520}
521
Jiyong Parkf1691d22021-03-29 20:11:58 +0900522func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700523 return proptools.String(j.deviceProperties.System_modules)
524}
525
Jiyong Park92315372021-04-02 08:45:46 +0900526func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700527 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900528 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700529 }
Jiyong Park92315372021-04-02 08:45:46 +0900530 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700531}
532
Jiyong Parkf1691d22021-03-29 20:11:58 +0900533func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900534 return j.minSdkVersion.Raw
535}
536
537func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
538 if j.deviceProperties.Target_sdk_version != nil {
539 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
540 }
541 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700542}
543
544func (j *Module) AvailableFor(what string) bool {
545 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
546 // Exception: for hostdex: true libraries, the platform variant is created
547 // even if it's not marked as available to platform. In that case, the platform
548 // variant is used only for the hostdex and not installed to the device.
549 return true
550 }
551 return j.ApexModuleBase.AvailableFor(what)
552}
553
554func (j *Module) deps(ctx android.BottomUpMutatorContext) {
555 if ctx.Device() {
556 j.linter.deps(ctx)
557
Jiyong Parkf1691d22021-03-29 20:11:58 +0900558 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700559
560 if j.deviceProperties.SyspropPublicStub != "" {
561 // This is a sysprop implementation library that has a corresponding sysprop public
562 // stubs library, and a dependency on it so that dependencies on the implementation can
563 // be forwarded to the public stubs library when necessary.
564 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
565 }
566 }
567
568 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
569 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
570
571 // Add dependency on libraries that provide additional hidden api annotations.
572 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
573
574 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
575 // Require java_sdk_library at inter-partition java dependency to ensure stable
576 // interface between partitions. If inter-partition java_library dependency is detected,
577 // raise build error because java_library doesn't have a stable interface.
578 //
579 // Inputs:
580 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
581 // if true, enable enforcement
582 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
583 // exception list of java_library names to allow inter-partition dependency
584 for idx := range j.properties.Libs {
585 if libDeps[idx] == nil {
586 continue
587 }
588
589 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
590 // java_sdk_library is always allowed at inter-partition dependency.
591 // So, skip check.
592 if _, ok := javaDep.(*SdkLibrary); ok {
593 continue
594 }
595
596 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
597 }
598 }
599 }
600
601 // For library dependencies that are component libraries (like stubs), add the implementation
602 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
603 for _, dep := range libDeps {
604 if dep != nil {
605 if component, ok := dep.(SdkLibraryComponentDependency); ok {
606 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
607 ctx.AddVariationDependencies(nil, usesLibTag, *lib)
608 }
609 }
610 }
611 }
612
613 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
614 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
615 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
616
617 android.ProtoDeps(ctx, &j.protoProperties)
618 if j.hasSrcExt(".proto") {
619 protoDeps(ctx, &j.protoProperties)
620 }
621
622 if j.hasSrcExt(".kt") {
623 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
624 // Kotlin files
625 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
626 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
627 if len(j.properties.Plugins) > 0 {
628 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
629 }
630 }
631
632 // Framework libraries need special handling in static coverage builds: they should not have
633 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
634 // the same jacoco classes coming from different bootclasspath jars.
635 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
636 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
637 j.properties.Instrument = true
638 }
639 } else if j.shouldInstrumentStatic(ctx) {
640 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
641 }
642}
643
644func hasSrcExt(srcs []string, ext string) bool {
645 for _, src := range srcs {
646 if filepath.Ext(src) == ext {
647 return true
648 }
649 }
650
651 return false
652}
653
654func (j *Module) hasSrcExt(ext string) bool {
655 return hasSrcExt(j.properties.Srcs, ext)
656}
657
658func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
659 aidlIncludeDirs android.Paths) (string, android.Paths) {
660
661 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
662 aidlIncludes = append(aidlIncludes,
663 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
664 aidlIncludes = append(aidlIncludes,
665 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
666
667 var flags []string
668 var deps android.Paths
669
670 flags = append(flags, j.deviceProperties.Aidl.Flags...)
671
672 if aidlPreprocess.Valid() {
673 flags = append(flags, "-p"+aidlPreprocess.String())
674 deps = append(deps, aidlPreprocess.Path())
675 } else if len(aidlIncludeDirs) > 0 {
676 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
677 }
678
679 if len(j.exportAidlIncludeDirs) > 0 {
680 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
681 }
682
683 if len(aidlIncludes) > 0 {
684 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
685 }
686
687 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
688 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
689 flags = append(flags, "-I"+src.String())
690 }
691
692 if Bool(j.deviceProperties.Aidl.Generate_traces) {
693 flags = append(flags, "-t")
694 }
695
696 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
697 flags = append(flags, "--transaction_names")
698 }
699
700 return strings.Join(flags, " "), deps
701}
702
703func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
704
705 var flags javaBuilderFlags
706
707 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900708 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700709
710 if ctx.Config().RunErrorProne() {
711 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
712 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
713 }
714
715 errorProneFlags := []string{
716 "-Xplugin:ErrorProne",
717 "${config.ErrorProneChecks}",
718 }
719 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
720
721 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
722 "'" + strings.Join(errorProneFlags, " ") + "'"
723 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
724 }
725
726 // classpath
727 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
728 flags.classpath = append(flags.classpath, deps.classpath...)
729 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
730 flags.processorPath = append(flags.processorPath, deps.processorPath...)
731 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
732
733 flags.processors = append(flags.processors, deps.processorClasses...)
734 flags.processors = android.FirstUniqueStrings(flags.processors)
735
736 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900737 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700738 // Give host-side tools a version of OpenJDK's standard libraries
739 // close to what they're targeting. As of Dec 2017, AOSP is only
740 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
741 //
742 // When building with OpenJDK 8, the following should have no
743 // effect since those jars would be available by default.
744 //
745 // When building with OpenJDK 9 but targeting a version < 1.8,
746 // putting them on the bootclasspath means that:
747 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
748 // b) references to existing APIs are not reinterpreted in an
749 // OpenJDK 9-specific way, eg. calls to subclasses of
750 // java.nio.Buffer as in http://b/70862583
751 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
752 flags.bootClasspath = append(flags.bootClasspath,
753 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
754 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
755 if Bool(j.properties.Use_tools_jar) {
756 flags.bootClasspath = append(flags.bootClasspath,
757 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
758 }
759 }
760
761 // systemModules
762 flags.systemModules = deps.systemModules
763
764 // aidl flags.
765 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
766
767 return flags
768}
769
770func (j *Module) collectJavacFlags(
771 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
772 // javac flags.
773 javacFlags := j.properties.Javacflags
774
775 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
776 // For non-host binaries, override the -g flag passed globally to remove
777 // local variable debug info to reduce disk and memory usage.
778 javacFlags = append(javacFlags, "-g:source,lines")
779 }
780 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
781
782 if flags.javaVersion.usesJavaModules() {
783 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
784
785 if j.properties.Patch_module != nil {
786 // Manually specify build directory in case it is not under the repo root.
787 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
788 // just adding a symlink under the root doesn't help.)
789 patchPaths := []string{".", ctx.Config().BuildDir()}
790
791 // b/150878007
792 //
793 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
794 // execution root for --patch-module. If this javac command line is
795 // invoked within Bazel's execution root working directory, the top
796 // level directories (e.g. libcore/, tools/, frameworks/) are all
797 // symlinks. JDK9 javac does not traverse into symlinks, which causes
798 // --patch-module to fail source file lookups when invoked in the
799 // execution root.
800 //
801 // Short of patching javac or enumerating *all* directories as possible
802 // input dirs, manually add the top level dir of the source files to be
803 // compiled.
804 topLevelDirs := map[string]bool{}
805 for _, srcFilePath := range srcFiles {
806 srcFileParts := strings.Split(srcFilePath.String(), "/")
807 // Ignore source files that are already in the top level directory
808 // as well as generated files in the out directory. The out
809 // directory may be an absolute path, which means srcFileParts[0] is the
810 // empty string, so check that as well. Note that "out" in Bazel's execution
811 // root is *not* a symlink, which doesn't cause problems for --patch-modules
812 // anyway, so it's fine to not apply this workaround for generated
813 // source files.
814 if len(srcFileParts) > 1 &&
815 srcFileParts[0] != "" &&
816 srcFileParts[0] != "out" {
817 topLevelDirs[srcFileParts[0]] = true
818 }
819 }
820 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
821
822 classPath := flags.classpath.FormJavaClassPath("")
823 if classPath != "" {
824 patchPaths = append(patchPaths, classPath)
825 }
826 javacFlags = append(
827 javacFlags,
828 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
829 }
830 }
831
832 if len(javacFlags) > 0 {
833 // optimization.
834 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
835 flags.javacFlags = "$javacFlags"
836 }
837
838 return flags
839}
840
841func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
842 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
843
844 deps := j.collectDeps(ctx)
845 flags := j.collectBuilderFlags(ctx, deps)
846
847 if flags.javaVersion.usesJavaModules() {
848 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
849 }
850 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
851 if hasSrcExt(srcFiles.Strings(), ".proto") {
852 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
853 }
854
855 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
856 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
857 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
858 }
859
860 srcFiles = j.genSources(ctx, srcFiles, flags)
861
862 // Collect javac flags only after computing the full set of srcFiles to
863 // ensure that the --patch-module lookup paths are complete.
864 flags = j.collectJavacFlags(ctx, flags, srcFiles)
865
866 srcJars := srcFiles.FilterByExt(".srcjar")
867 srcJars = append(srcJars, deps.srcJars...)
868 if aaptSrcJar != nil {
869 srcJars = append(srcJars, aaptSrcJar)
870 }
871
872 if j.properties.Jarjar_rules != nil {
873 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
874 }
875
876 jarName := ctx.ModuleName() + ".jar"
877
878 javaSrcFiles := srcFiles.FilterByExt(".java")
879 var uniqueSrcFiles android.Paths
880 set := make(map[string]bool)
881 for _, v := range javaSrcFiles {
882 if _, found := set[v.String()]; !found {
883 set[v.String()] = true
884 uniqueSrcFiles = append(uniqueSrcFiles, v)
885 }
886 }
887
888 // Collect .java files for AIDEGen
889 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
890
891 var kotlinJars android.Paths
892
893 if srcFiles.HasExt(".kt") {
894 // user defined kotlin flags.
895 kotlincFlags := j.properties.Kotlincflags
896 CheckKotlincFlags(ctx, kotlincFlags)
897
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000898 // Workaround for KT-46512
899 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700900
901 // If there are kotlin files, compile them first but pass all the kotlin and java files
902 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
903 // won't emit any classes for them.
904 kotlincFlags = append(kotlincFlags, "-no-stdlib")
905 if ctx.Device() {
906 kotlincFlags = append(kotlincFlags, "-no-jdk")
907 }
908 if len(kotlincFlags) > 0 {
909 // optimization.
910 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
911 flags.kotlincFlags += "$kotlincFlags"
912 }
913
914 var kotlinSrcFiles android.Paths
915 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
916 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
917
918 // Collect .kt files for AIDEGen
919 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
920 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
921
922 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
923 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
924
925 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
926 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
927
928 if len(flags.processorPath) > 0 {
929 // Use kapt for annotation processing
930 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
931 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
932 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
933 srcJars = append(srcJars, kaptSrcJar)
934 kotlinJars = append(kotlinJars, kaptResJar)
935 // Disable annotation processing in javac, it's already been handled by kapt
936 flags.processorPath = nil
937 flags.processors = nil
938 }
939
940 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
941 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
942 if ctx.Failed() {
943 return
944 }
945
946 // Make javac rule depend on the kotlinc rule
947 flags.classpath = append(flags.classpath, kotlinJar)
948
949 kotlinJars = append(kotlinJars, kotlinJar)
950 // Jar kotlin classes into the final jar after javac
951 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
952 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
953 }
954 }
955
956 jars := append(android.Paths(nil), kotlinJars...)
957
958 // Store the list of .java files that was passed to javac
959 j.compiledJavaSrcs = uniqueSrcFiles
960 j.compiledSrcJars = srcJars
961
962 enableSharding := false
963 var headerJarFileWithoutJarjar android.Path
964 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
965 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
966 enableSharding = true
967 // Formerly, there was a check here that prevented annotation processors
968 // from being used when sharding was enabled, as some annotation processors
969 // do not function correctly in sharded environments. It was removed to
970 // allow for the use of annotation processors that do function correctly
971 // with sharding enabled. See: b/77284273.
972 }
973 headerJarFileWithoutJarjar, j.headerJarFile =
974 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
975 if ctx.Failed() {
976 return
977 }
978 }
979 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
980 var extraJarDeps android.Paths
981 if ctx.Config().RunErrorProne() {
982 // If error-prone is enabled, add an additional rule to compile the java files into
983 // a separate set of classes (so that they don't overwrite the normal ones and require
984 // a rebuild when error-prone is turned off).
985 // TODO(ccross): Once we always compile with javac9 we may be able to conditionally
986 // enable error-prone without affecting the output class files.
987 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
988 RunErrorProne(ctx, errorprone, uniqueSrcFiles, srcJars, flags)
989 extraJarDeps = append(extraJarDeps, errorprone)
990 }
991
992 if enableSharding {
993 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
994 shardSize := int(*(j.properties.Javac_shard_size))
995 var shardSrcs []android.Paths
996 if len(uniqueSrcFiles) > 0 {
997 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
998 for idx, shardSrc := range shardSrcs {
999 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1000 nil, flags, extraJarDeps)
1001 jars = append(jars, classes)
1002 }
1003 }
1004 if len(srcJars) > 0 {
1005 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1006 nil, srcJars, flags, extraJarDeps)
1007 jars = append(jars, classes)
1008 }
1009 } else {
1010 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1011 jars = append(jars, classes)
1012 }
1013 if ctx.Failed() {
1014 return
1015 }
1016 }
1017
1018 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1019
1020 var includeSrcJar android.WritablePath
1021 if Bool(j.properties.Include_srcs) {
1022 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1023 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1024 }
1025
1026 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1027 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1028 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1029 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1030
1031 var resArgs []string
1032 var resDeps android.Paths
1033
1034 resArgs = append(resArgs, dirArgs...)
1035 resDeps = append(resDeps, dirDeps...)
1036
1037 resArgs = append(resArgs, fileArgs...)
1038 resDeps = append(resDeps, fileDeps...)
1039
1040 resArgs = append(resArgs, extraArgs...)
1041 resDeps = append(resDeps, extraDeps...)
1042
1043 if len(resArgs) > 0 {
1044 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1045 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1046 j.resourceJar = resourceJar
1047 if ctx.Failed() {
1048 return
1049 }
1050 }
1051
1052 var resourceJars android.Paths
1053 if j.resourceJar != nil {
1054 resourceJars = append(resourceJars, j.resourceJar)
1055 }
1056 if Bool(j.properties.Include_srcs) {
1057 resourceJars = append(resourceJars, includeSrcJar)
1058 }
1059 resourceJars = append(resourceJars, deps.staticResourceJars...)
1060
1061 if len(resourceJars) > 1 {
1062 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1063 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1064 false, nil, nil)
1065 j.resourceJar = combinedJar
1066 } else if len(resourceJars) == 1 {
1067 j.resourceJar = resourceJars[0]
1068 }
1069
1070 if len(deps.staticJars) > 0 {
1071 jars = append(jars, deps.staticJars...)
1072 }
1073
1074 manifest := j.overrideManifest
1075 if !manifest.Valid() && j.properties.Manifest != nil {
1076 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1077 }
1078
1079 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1080 if len(services) > 0 {
1081 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1082 var zipargs []string
1083 for _, file := range services {
1084 serviceFile := file.String()
1085 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1086 }
1087 rule := zip
1088 args := map[string]string{
1089 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1090 }
1091 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1092 rule = zipRE
1093 args["implicits"] = strings.Join(services.Strings(), ",")
1094 }
1095 ctx.Build(pctx, android.BuildParams{
1096 Rule: rule,
1097 Output: servicesJar,
1098 Implicits: services,
1099 Args: args,
1100 })
1101 jars = append(jars, servicesJar)
1102 }
1103
1104 // Combine the classes built from sources, any manifests, and any static libraries into
1105 // classes.jar. If there is only one input jar this step will be skipped.
1106 var outputFile android.OutputPath
1107
1108 if len(jars) == 1 && !manifest.Valid() {
1109 // Optimization: skip the combine step as there is nothing to do
1110 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1111 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1112 // any if len(jars) == 1.
1113
1114 // Transform the single path to the jar into an OutputPath as that is required by the following
1115 // code.
1116 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1117 // The path contains an embedded OutputPath so reuse that.
1118 outputFile = moduleOutPath.OutputPath
1119 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1120 // The path is an OutputPath so reuse it directly.
1121 outputFile = outputPath
1122 } else {
1123 // The file is not in the out directory so create an OutputPath into which it can be copied
1124 // and which the following code can use to refer to it.
1125 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1126 ctx.Build(pctx, android.BuildParams{
1127 Rule: android.Cp,
1128 Input: jars[0],
1129 Output: combinedJar,
1130 })
1131 outputFile = combinedJar.OutputPath
1132 }
1133 } else {
1134 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1135 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1136 false, nil, nil)
1137 outputFile = combinedJar.OutputPath
1138 }
1139
1140 // jarjar implementation jar if necessary
1141 if j.expandJarjarRules != nil {
1142 // Transform classes.jar into classes-jarjar.jar
1143 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1144 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1145 outputFile = jarjarFile
1146
1147 // jarjar resource jar if necessary
1148 if j.resourceJar != nil {
1149 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1150 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1151 j.resourceJar = resourceJarJarFile
1152 }
1153
1154 if ctx.Failed() {
1155 return
1156 }
1157 }
1158
1159 // Check package restrictions if necessary.
1160 if len(j.properties.Permitted_packages) > 0 {
1161 // Check packages and copy to package-checked file.
1162 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1163 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1164 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1165
1166 if ctx.Failed() {
1167 return
1168 }
1169 }
1170
1171 j.implementationJarFile = outputFile
1172 if j.headerJarFile == nil {
1173 j.headerJarFile = j.implementationJarFile
1174 }
1175
1176 if j.shouldInstrumentInApex(ctx) {
1177 j.properties.Instrument = true
1178 }
1179
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001180 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1181 specs := j.jacocoModuleToZipCommand(ctx)
1182 if ctx.Failed() {
1183 return
1184 }
1185
Jaewoong Jung26342642021-03-17 15:56:23 -07001186 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001187 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001188 }
1189
1190 // merge implementation jar with resources if necessary
1191 implementationAndResourcesJar := outputFile
1192 if j.resourceJar != nil {
1193 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1194 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1195 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1196 false, nil, nil)
1197 implementationAndResourcesJar = combinedJar
1198 }
1199
1200 j.implementationAndResourcesJar = implementationAndResourcesJar
1201
1202 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1203 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1204 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1205 if j.dexProperties.Compile_dex == nil {
1206 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1207 }
1208 if j.deviceProperties.Hostdex == nil {
1209 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1210 }
1211 }
1212
1213 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1214 if j.hasCode(ctx) {
1215 if j.shouldInstrumentStatic(ctx) {
1216 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1217 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1218 }
1219 // Dex compilation
1220 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001221 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001222 if ctx.Failed() {
1223 return
1224 }
1225
Paul Duffinafaa47c2021-05-14 13:04:04 +01001226 // Update hidden API paths.
1227 j.hiddenAPIUpdatePaths(ctx, dexOutputFile, j.implementationJarFile)
1228
1229 // Encode hidden API flags in dex file.
1230 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile, proptools.Bool(j.dexProperties.Uncompress_dex))
Jaewoong Jung26342642021-03-17 15:56:23 -07001231
1232 // merge dex jar with resources if necessary
1233 if j.resourceJar != nil {
1234 jars := android.Paths{dexOutputFile, j.resourceJar}
1235 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1236 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1237 false, nil, nil)
1238 if *j.dexProperties.Uncompress_dex {
1239 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1240 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1241 dexOutputFile = combinedAlignedJar
1242 } else {
1243 dexOutputFile = combinedJar
1244 }
1245 }
1246
1247 j.dexJarFile = dexOutputFile
1248
1249 // Dexpreopting
1250 j.dexpreopt(ctx, dexOutputFile)
1251
1252 outputFile = dexOutputFile
1253 } else {
1254 // There is no code to compile into a dex jar, make sure the resources are propagated
1255 // to the APK if this is an app.
1256 outputFile = implementationAndResourcesJar
1257 j.dexJarFile = j.resourceJar
1258 }
1259
1260 if ctx.Failed() {
1261 return
1262 }
1263 } else {
1264 outputFile = implementationAndResourcesJar
1265 }
1266
1267 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001268 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001269 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001270 return v.String()
1271 } else {
1272 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1273 }
1274 }
1275
1276 j.linter.name = ctx.ModuleName()
1277 j.linter.srcs = srcFiles
1278 j.linter.srcJars = srcJars
1279 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1280 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001281 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1282 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1283 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -07001284 j.linter.javaLanguageLevel = flags.javaVersion.String()
1285 j.linter.kotlinLanguageLevel = "1.3"
1286 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1287 j.linter.buildModuleReportZip = true
1288 }
1289 j.linter.lint(ctx)
1290 }
1291
1292 ctx.CheckbuildFile(outputFile)
1293
1294 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1295 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1296 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1297 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1298 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1299 AidlIncludeDirs: j.exportAidlIncludeDirs,
1300 SrcJarArgs: j.srcJarArgs,
1301 SrcJarDeps: j.srcJarDeps,
1302 ExportedPlugins: j.exportedPluginJars,
1303 ExportedPluginClasses: j.exportedPluginClasses,
1304 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1305 JacocoReportClassesFile: j.jacocoReportClassesFile,
1306 })
1307
1308 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1309 j.outputFile = outputFile.WithoutRel()
1310}
1311
1312func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1313 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1314
1315 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1316 if idx >= 0 {
1317 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1318 jarName += strconv.Itoa(idx)
1319 }
1320
1321 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1322 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1323
1324 if ctx.Config().EmitXrefRules() {
1325 extractionFile := android.PathForModuleOut(ctx, kzipName)
1326 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1327 j.kytheFiles = append(j.kytheFiles, extractionFile)
1328 }
1329
1330 return classes
1331}
1332
1333// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1334// since some of these flags may be used internally.
1335func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1336 for _, flag := range flags {
1337 flag = strings.TrimSpace(flag)
1338
1339 if !strings.HasPrefix(flag, "-") {
1340 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1341 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1342 ctx.PropertyErrorf("kotlincflags",
1343 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1344 } else if inList(flag, config.KotlincIllegalFlags) {
1345 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1346 } else if flag == "-include-runtime" {
1347 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1348 } else {
1349 args := strings.Split(flag, " ")
1350 if args[0] == "-kotlin-home" {
1351 ctx.PropertyErrorf("kotlincflags",
1352 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1353 }
1354 }
1355 }
1356}
1357
1358func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1359 deps deps, flags javaBuilderFlags, jarName string,
1360 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1361
1362 var jars android.Paths
1363 if len(srcFiles) > 0 || len(srcJars) > 0 {
1364 // Compile java sources into turbine.jar.
1365 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1366 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1367 if ctx.Failed() {
1368 return nil, nil
1369 }
1370 jars = append(jars, turbineJar)
1371 }
1372
1373 jars = append(jars, extraJars...)
1374
1375 // Combine any static header libraries into classes-header.jar. If there is only
1376 // one input jar this step will be skipped.
1377 jars = append(jars, deps.staticHeaderJars...)
1378
1379 // we cannot skip the combine step for now if there is only one jar
1380 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1381 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1382 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1383 false, nil, []string{"META-INF/TRANSITIVE"})
1384 headerJar = combinedJar
1385 jarjarHeaderJar = combinedJar
1386
1387 if j.expandJarjarRules != nil {
1388 // Transform classes.jar into classes-jarjar.jar
1389 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1390 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1391 jarjarHeaderJar = jarjarFile
1392 if ctx.Failed() {
1393 return nil, nil
1394 }
1395 }
1396
1397 return headerJar, jarjarHeaderJar
1398}
1399
1400func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001401 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001402
1403 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1404 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1405
1406 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1407
1408 j.jacocoReportClassesFile = jacocoReportClassesFile
1409
1410 return instrumentedJar
1411}
1412
1413func (j *Module) HeaderJars() android.Paths {
1414 if j.headerJarFile == nil {
1415 return nil
1416 }
1417 return android.Paths{j.headerJarFile}
1418}
1419
1420func (j *Module) ImplementationJars() android.Paths {
1421 if j.implementationJarFile == nil {
1422 return nil
1423 }
1424 return android.Paths{j.implementationJarFile}
1425}
1426
1427func (j *Module) DexJarBuildPath() android.Path {
1428 return j.dexJarFile
1429}
1430
1431func (j *Module) DexJarInstallPath() android.Path {
1432 return j.installFile
1433}
1434
1435func (j *Module) ImplementationAndResourcesJars() android.Paths {
1436 if j.implementationAndResourcesJar == nil {
1437 return nil
1438 }
1439 return android.Paths{j.implementationAndResourcesJar}
1440}
1441
1442func (j *Module) AidlIncludeDirs() android.Paths {
1443 // exportAidlIncludeDirs is type android.Paths already
1444 return j.exportAidlIncludeDirs
1445}
1446
1447func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1448 return j.classLoaderContexts
1449}
1450
1451// Collect information for opening IDE project files in java/jdeps.go.
1452func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1453 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1454 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1455 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1456 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1457 if j.expandJarjarRules != nil {
1458 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1459 }
1460 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1461}
1462
1463func (j *Module) CompilerDeps() []string {
1464 jdeps := []string{}
1465 jdeps = append(jdeps, j.properties.Libs...)
1466 jdeps = append(jdeps, j.properties.Static_libs...)
1467 return jdeps
1468}
1469
1470func (j *Module) hasCode(ctx android.ModuleContext) bool {
1471 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1472 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1473}
1474
1475// Implements android.ApexModule
1476func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1477 return j.depIsInSameApex(ctx, dep)
1478}
1479
1480// Implements android.ApexModule
1481func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1482 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001483 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001484 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 return fmt.Errorf("min_sdk_version is not specified")
1486 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001487 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001488 return nil
1489 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001490 ver, err := sdkSpec.EffectiveVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001491 if err != nil {
1492 return err
1493 }
Jiyong Park54105c42021-03-31 18:17:53 +09001494 if ver.GreaterThan(sdkVersion) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001495 return fmt.Errorf("newer SDK(%v)", ver)
1496 }
1497 return nil
1498}
1499
1500func (j *Module) Stem() string {
1501 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1502}
1503
1504// ConfigurationName returns the name of the module as used in build configuration.
1505//
1506// This is usually the same as BaseModuleName() except for the <x>.impl libraries created by
1507// java_sdk_library in which case this is the BaseModuleName() without the ".impl" suffix,
1508// i.e. just <x>.
1509func (j *Module) ConfigurationName() string {
1510 return proptools.StringDefault(j.deviceProperties.ConfigurationName, j.BaseModuleName())
1511}
1512
1513func (j *Module) JacocoReportClassesFile() android.Path {
1514 return j.jacocoReportClassesFile
1515}
1516
1517func (j *Module) IsInstallable() bool {
1518 return Bool(j.properties.Installable)
1519}
1520
1521type sdkLinkType int
1522
1523const (
1524 // TODO(jiyong) rename these for better readability. Make the allowed
1525 // and disallowed link types explicit
1526 // order is important here. See rank()
1527 javaCore sdkLinkType = iota
1528 javaSdk
1529 javaSystem
1530 javaModule
1531 javaSystemServer
1532 javaPlatform
1533)
1534
1535func (lt sdkLinkType) String() string {
1536 switch lt {
1537 case javaCore:
1538 return "core Java API"
1539 case javaSdk:
1540 return "Android API"
1541 case javaSystem:
1542 return "system API"
1543 case javaModule:
1544 return "module API"
1545 case javaSystemServer:
1546 return "system server API"
1547 case javaPlatform:
1548 return "private API"
1549 default:
1550 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1551 }
1552}
1553
1554// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1555// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1556// can't statically depend on modules that use Platform API.
1557func (lt sdkLinkType) rank() int {
1558 return int(lt)
1559}
1560
1561type moduleWithSdkDep interface {
1562 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001563 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001564}
1565
Jiyong Park92315372021-04-02 08:45:46 +09001566func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001567 switch name {
1568 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1569 "stub-annotations", "private-stub-annotations-jar",
1570 "core-lambda-stubs", "core-generated-annotation-stubs":
1571 return javaCore, true
1572 case "android_stubs_current":
1573 return javaSdk, true
1574 case "android_system_stubs_current":
1575 return javaSystem, true
1576 case "android_module_lib_stubs_current":
1577 return javaModule, true
1578 case "android_system_server_stubs_current":
1579 return javaSystemServer, true
1580 case "android_test_stubs_current":
1581 return javaSystem, true
1582 }
1583
1584 if stub, linkType := moduleStubLinkType(name); stub {
1585 return linkType, true
1586 }
1587
Jiyong Park92315372021-04-02 08:45:46 +09001588 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001589 switch ver.Kind {
1590 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001591 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001592 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001593 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001594 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001595 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001596 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001597 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001598 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001599 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001600 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001601 return javaPlatform, false
1602 }
1603
Jiyong Parkf1691d22021-03-29 20:11:58 +09001604 if !ver.Valid() {
1605 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001606 }
1607 return javaSdk, false
1608}
1609
1610// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1611// this module's. See the comment on rank() for details and an example.
1612func (j *Module) checkSdkLinkType(
1613 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1614 if ctx.Host() {
1615 return
1616 }
1617
Jiyong Park92315372021-04-02 08:45:46 +09001618 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001619 if stubs {
1620 return
1621 }
Jiyong Park92315372021-04-02 08:45:46 +09001622 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001623
1624 if myLinkType.rank() < depLinkType.rank() {
1625 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1626 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1627 "property of the source or target module so that target module is built "+
1628 "with the same or smaller API set when compared to the source.",
1629 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1630 }
1631}
1632
1633func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1634 var deps deps
1635
1636 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001637 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001638 if sdkDep.invalidVersion {
1639 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1640 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1641 } else if sdkDep.useFiles {
1642 // sdkDep.jar is actually equivalent to turbine header.jar.
1643 deps.classpath = append(deps.classpath, sdkDep.jars...)
1644 deps.aidlPreprocess = sdkDep.aidl
1645 } else {
1646 deps.aidlPreprocess = sdkDep.aidl
1647 }
1648 }
1649
Jiyong Park92315372021-04-02 08:45:46 +09001650 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001651
1652 ctx.VisitDirectDeps(func(module android.Module) {
1653 otherName := ctx.OtherModuleName(module)
1654 tag := ctx.OtherModuleDependencyTag(module)
1655
1656 if IsJniDepTag(tag) {
1657 // Handled by AndroidApp.collectAppDeps
1658 return
1659 }
1660 if tag == certificateTag {
1661 // Handled by AndroidApp.collectAppDeps
1662 return
1663 }
1664
1665 if dep, ok := module.(SdkLibraryDependency); ok {
1666 switch tag {
1667 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001668 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001669 case staticLibTag:
1670 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1671 }
1672 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1673 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1674 if sdkLinkType != javaPlatform &&
1675 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1676 // dep is a sysprop implementation library, but this module is not linking against
1677 // the platform, so it gets the sysprop public stubs library instead. Replace
1678 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1679 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1680 dep = syspropDep.JavaInfo
1681 }
1682 switch tag {
1683 case bootClasspathTag:
1684 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1685 case libTag, instrumentationForTag:
1686 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1687 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1688 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1689 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1690 case java9LibTag:
1691 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1692 case staticLibTag:
1693 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1694 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1695 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1696 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1697 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1698 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1699 // Turbine doesn't run annotation processors, so any module that uses an
1700 // annotation processor that generates API is incompatible with the turbine
1701 // optimization.
1702 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1703 case pluginTag:
1704 if plugin, ok := module.(*Plugin); ok {
1705 if plugin.pluginProperties.Processor_class != nil {
1706 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1707 } else {
1708 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1709 }
1710 // Turbine doesn't run annotation processors, so any module that uses an
1711 // annotation processor that generates API is incompatible with the turbine
1712 // optimization.
1713 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1714 } else {
1715 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1716 }
1717 case errorpronePluginTag:
1718 if _, ok := module.(*Plugin); ok {
1719 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1720 } else {
1721 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1722 }
1723 case exportedPluginTag:
1724 if plugin, ok := module.(*Plugin); ok {
1725 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1726 if plugin.pluginProperties.Processor_class != nil {
1727 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1728 }
1729 // Turbine doesn't run annotation processors, so any module that uses an
1730 // annotation processor that generates API is incompatible with the turbine
1731 // optimization.
1732 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1733 } else {
1734 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1735 }
1736 case kotlinStdlibTag:
1737 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1738 case kotlinAnnotationsTag:
1739 deps.kotlinAnnotations = dep.HeaderJars
1740 case syspropPublicStubDepTag:
1741 // This is a sysprop implementation library, forward the JavaInfoProvider from
1742 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1743 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1744 JavaInfo: dep,
1745 })
1746 }
1747 } else if dep, ok := module.(android.SourceFileProducer); ok {
1748 switch tag {
1749 case libTag:
1750 checkProducesJars(ctx, dep)
1751 deps.classpath = append(deps.classpath, dep.Srcs()...)
1752 case staticLibTag:
1753 checkProducesJars(ctx, dep)
1754 deps.classpath = append(deps.classpath, dep.Srcs()...)
1755 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1756 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1757 }
1758 } else {
1759 switch tag {
1760 case bootClasspathTag:
1761 // If a system modules dependency has been added to the bootclasspath
1762 // then add its libs to the bootclasspath.
1763 sm := module.(SystemModulesProvider)
1764 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1765
1766 case systemModulesTag:
1767 if deps.systemModules != nil {
1768 panic("Found two system module dependencies")
1769 }
1770 sm := module.(SystemModulesProvider)
1771 outputDir, outputDeps := sm.OutputDirAndDeps()
1772 deps.systemModules = &systemModules{outputDir, outputDeps}
1773 }
1774 }
1775
1776 addCLCFromDep(ctx, module, j.classLoaderContexts)
1777 })
1778
1779 return deps
1780}
1781
1782func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1783 deps.processorPath = append(deps.processorPath, pluginJars...)
1784 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1785}
1786
1787// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1788// this interface.
1789type ProvidesUsesLib interface {
1790 ProvidesUsesLib() *string
1791}
1792
1793func (j *Module) ProvidesUsesLib() *string {
1794 return j.usesLibraryProperties.Provides_uses_lib
1795}