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