blob: 0294c50900d70b62fa6b731487ca1f64bbf45013 [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
Paul Duffin3accbb52021-06-23 11:39:47 +0100256func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
257 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700258}
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
892 // Dogfood the JVM_IR backend.
893 kotlincFlags = append(kotlincFlags, "-Xuse-ir")
894
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
Colin Cross0ba588d2021-11-18 22:23:12 -0800957 var headerJarFileWithoutDepsOrJarjar android.Path
Jaewoong Jung26342642021-03-17 15:56:23 -0700958 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 }
Colin Cross0ba588d2021-11-18 22:23:12 -0800967 headerJarFileWithoutDepsOrJarjar, j.headerJarFile =
Jaewoong Jung26342642021-03-17 15:56:23 -0700968 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 {
Colin Cross0ba588d2021-11-18 22:23:12 -0800987 if headerJarFileWithoutDepsOrJarjar != nil {
988 flags.classpath = append(classpath{headerJarFileWithoutDepsOrJarjar}, flags.classpath...)
989 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700990 shardSize := int(*(j.properties.Javac_shard_size))
991 var shardSrcs []android.Paths
992 if len(uniqueSrcFiles) > 0 {
993 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
994 for idx, shardSrc := range shardSrcs {
995 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
996 nil, flags, extraJarDeps)
997 jars = append(jars, classes)
998 }
999 }
1000 if len(srcJars) > 0 {
1001 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1002 nil, srcJars, flags, extraJarDeps)
1003 jars = append(jars, classes)
1004 }
1005 } else {
1006 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1007 jars = append(jars, classes)
1008 }
1009 if ctx.Failed() {
1010 return
1011 }
1012 }
1013
1014 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1015
1016 var includeSrcJar android.WritablePath
1017 if Bool(j.properties.Include_srcs) {
1018 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1019 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1020 }
1021
1022 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1023 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1024 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1025 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1026
1027 var resArgs []string
1028 var resDeps android.Paths
1029
1030 resArgs = append(resArgs, dirArgs...)
1031 resDeps = append(resDeps, dirDeps...)
1032
1033 resArgs = append(resArgs, fileArgs...)
1034 resDeps = append(resDeps, fileDeps...)
1035
1036 resArgs = append(resArgs, extraArgs...)
1037 resDeps = append(resDeps, extraDeps...)
1038
1039 if len(resArgs) > 0 {
1040 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1041 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1042 j.resourceJar = resourceJar
1043 if ctx.Failed() {
1044 return
1045 }
1046 }
1047
1048 var resourceJars android.Paths
1049 if j.resourceJar != nil {
1050 resourceJars = append(resourceJars, j.resourceJar)
1051 }
1052 if Bool(j.properties.Include_srcs) {
1053 resourceJars = append(resourceJars, includeSrcJar)
1054 }
1055 resourceJars = append(resourceJars, deps.staticResourceJars...)
1056
1057 if len(resourceJars) > 1 {
1058 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1059 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1060 false, nil, nil)
1061 j.resourceJar = combinedJar
1062 } else if len(resourceJars) == 1 {
1063 j.resourceJar = resourceJars[0]
1064 }
1065
1066 if len(deps.staticJars) > 0 {
1067 jars = append(jars, deps.staticJars...)
1068 }
1069
1070 manifest := j.overrideManifest
1071 if !manifest.Valid() && j.properties.Manifest != nil {
1072 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1073 }
1074
1075 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1076 if len(services) > 0 {
1077 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1078 var zipargs []string
1079 for _, file := range services {
1080 serviceFile := file.String()
1081 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1082 }
1083 rule := zip
1084 args := map[string]string{
1085 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1086 }
1087 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1088 rule = zipRE
1089 args["implicits"] = strings.Join(services.Strings(), ",")
1090 }
1091 ctx.Build(pctx, android.BuildParams{
1092 Rule: rule,
1093 Output: servicesJar,
1094 Implicits: services,
1095 Args: args,
1096 })
1097 jars = append(jars, servicesJar)
1098 }
1099
1100 // Combine the classes built from sources, any manifests, and any static libraries into
1101 // classes.jar. If there is only one input jar this step will be skipped.
1102 var outputFile android.OutputPath
1103
1104 if len(jars) == 1 && !manifest.Valid() {
1105 // Optimization: skip the combine step as there is nothing to do
1106 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1107 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1108 // any if len(jars) == 1.
1109
1110 // Transform the single path to the jar into an OutputPath as that is required by the following
1111 // code.
1112 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1113 // The path contains an embedded OutputPath so reuse that.
1114 outputFile = moduleOutPath.OutputPath
1115 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1116 // The path is an OutputPath so reuse it directly.
1117 outputFile = outputPath
1118 } else {
1119 // The file is not in the out directory so create an OutputPath into which it can be copied
1120 // and which the following code can use to refer to it.
1121 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1122 ctx.Build(pctx, android.BuildParams{
1123 Rule: android.Cp,
1124 Input: jars[0],
1125 Output: combinedJar,
1126 })
1127 outputFile = combinedJar.OutputPath
1128 }
1129 } else {
1130 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1131 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1132 false, nil, nil)
1133 outputFile = combinedJar.OutputPath
1134 }
1135
1136 // jarjar implementation jar if necessary
1137 if j.expandJarjarRules != nil {
1138 // Transform classes.jar into classes-jarjar.jar
1139 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1140 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1141 outputFile = jarjarFile
1142
1143 // jarjar resource jar if necessary
1144 if j.resourceJar != nil {
1145 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1146 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1147 j.resourceJar = resourceJarJarFile
1148 }
1149
1150 if ctx.Failed() {
1151 return
1152 }
1153 }
1154
1155 // Check package restrictions if necessary.
1156 if len(j.properties.Permitted_packages) > 0 {
1157 // Check packages and copy to package-checked file.
1158 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1159 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1160 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1161
1162 if ctx.Failed() {
1163 return
1164 }
1165 }
1166
1167 j.implementationJarFile = outputFile
1168 if j.headerJarFile == nil {
1169 j.headerJarFile = j.implementationJarFile
1170 }
1171
1172 if j.shouldInstrumentInApex(ctx) {
1173 j.properties.Instrument = true
1174 }
1175
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001176 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1177 specs := j.jacocoModuleToZipCommand(ctx)
1178 if ctx.Failed() {
1179 return
1180 }
1181
Jaewoong Jung26342642021-03-17 15:56:23 -07001182 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001183 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001184 }
1185
1186 // merge implementation jar with resources if necessary
1187 implementationAndResourcesJar := outputFile
1188 if j.resourceJar != nil {
1189 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1190 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1191 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1192 false, nil, nil)
1193 implementationAndResourcesJar = combinedJar
1194 }
1195
1196 j.implementationAndResourcesJar = implementationAndResourcesJar
1197
1198 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1199 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1200 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1201 if j.dexProperties.Compile_dex == nil {
1202 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1203 }
1204 if j.deviceProperties.Hostdex == nil {
1205 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1206 }
1207 }
1208
1209 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1210 if j.hasCode(ctx) {
1211 if j.shouldInstrumentStatic(ctx) {
1212 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1213 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1214 }
1215 // Dex compilation
1216 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001217 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001218 if ctx.Failed() {
1219 return
1220 }
1221
Jaewoong Jung26342642021-03-17 15:56:23 -07001222 // merge dex jar with resources if necessary
1223 if j.resourceJar != nil {
1224 jars := android.Paths{dexOutputFile, j.resourceJar}
1225 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1226 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1227 false, nil, nil)
1228 if *j.dexProperties.Uncompress_dex {
1229 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1230 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1231 dexOutputFile = combinedAlignedJar
1232 } else {
1233 dexOutputFile = combinedJar
1234 }
1235 }
1236
Paul Duffin0bd5b062021-05-16 05:21:16 +01001237 // Initialize the hiddenapi structure.
1238 j.initHiddenAPI(ctx, dexOutputFile, j.implementationJarFile, j.dexProperties.Uncompress_dex)
1239
1240 // Encode hidden API flags in dex file, if needed.
1241 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1242
Jaewoong Jung26342642021-03-17 15:56:23 -07001243 j.dexJarFile = dexOutputFile
1244
1245 // Dexpreopting
1246 j.dexpreopt(ctx, dexOutputFile)
1247
1248 outputFile = dexOutputFile
1249 } else {
1250 // There is no code to compile into a dex jar, make sure the resources are propagated
1251 // to the APK if this is an app.
1252 outputFile = implementationAndResourcesJar
1253 j.dexJarFile = j.resourceJar
1254 }
1255
1256 if ctx.Failed() {
1257 return
1258 }
1259 } else {
1260 outputFile = implementationAndResourcesJar
1261 }
1262
1263 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001264 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001265 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001266 return v.String()
1267 } else {
1268 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1269 }
1270 }
1271
1272 j.linter.name = ctx.ModuleName()
1273 j.linter.srcs = srcFiles
1274 j.linter.srcJars = srcJars
1275 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1276 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001277 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1278 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1279 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureirof1be9ba2021-06-08 18:11:21 +00001280 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001281 j.linter.javaLanguageLevel = flags.javaVersion.String()
1282 j.linter.kotlinLanguageLevel = "1.3"
1283 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1284 j.linter.buildModuleReportZip = true
1285 }
1286 j.linter.lint(ctx)
1287 }
1288
1289 ctx.CheckbuildFile(outputFile)
1290
1291 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1292 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1293 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1294 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1295 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1296 AidlIncludeDirs: j.exportAidlIncludeDirs,
1297 SrcJarArgs: j.srcJarArgs,
1298 SrcJarDeps: j.srcJarDeps,
1299 ExportedPlugins: j.exportedPluginJars,
1300 ExportedPluginClasses: j.exportedPluginClasses,
1301 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1302 JacocoReportClassesFile: j.jacocoReportClassesFile,
1303 })
1304
1305 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1306 j.outputFile = outputFile.WithoutRel()
1307}
1308
1309func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1310 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1311
1312 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1313 if idx >= 0 {
1314 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1315 jarName += strconv.Itoa(idx)
1316 }
1317
1318 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1319 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1320
1321 if ctx.Config().EmitXrefRules() {
1322 extractionFile := android.PathForModuleOut(ctx, kzipName)
1323 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1324 j.kytheFiles = append(j.kytheFiles, extractionFile)
1325 }
1326
1327 return classes
1328}
1329
1330// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1331// since some of these flags may be used internally.
1332func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1333 for _, flag := range flags {
1334 flag = strings.TrimSpace(flag)
1335
1336 if !strings.HasPrefix(flag, "-") {
1337 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1338 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1339 ctx.PropertyErrorf("kotlincflags",
1340 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1341 } else if inList(flag, config.KotlincIllegalFlags) {
1342 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1343 } else if flag == "-include-runtime" {
1344 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1345 } else {
1346 args := strings.Split(flag, " ")
1347 if args[0] == "-kotlin-home" {
1348 ctx.PropertyErrorf("kotlincflags",
1349 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1350 }
1351 }
1352 }
1353}
1354
1355func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1356 deps deps, flags javaBuilderFlags, jarName string,
Colin Cross0ba588d2021-11-18 22:23:12 -08001357 extraJars android.Paths) (headerJar, jarjarAndDepsHeaderJar android.Path) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001358
1359 var jars android.Paths
1360 if len(srcFiles) > 0 || len(srcJars) > 0 {
1361 // Compile java sources into turbine.jar.
1362 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1363 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1364 if ctx.Failed() {
1365 return nil, nil
1366 }
1367 jars = append(jars, turbineJar)
Colin Cross0ba588d2021-11-18 22:23:12 -08001368 headerJar = turbineJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001369 }
1370
1371 jars = append(jars, extraJars...)
1372
1373 // Combine any static header libraries into classes-header.jar. If there is only
1374 // one input jar this step will be skipped.
1375 jars = append(jars, deps.staticHeaderJars...)
1376
1377 // we cannot skip the combine step for now if there is only one jar
1378 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1379 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1380 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1381 false, nil, []string{"META-INF/TRANSITIVE"})
Colin Cross0ba588d2021-11-18 22:23:12 -08001382 jarjarAndDepsHeaderJar = combinedJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001383
1384 if j.expandJarjarRules != nil {
1385 // Transform classes.jar into classes-jarjar.jar
1386 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
Colin Cross0ba588d2021-11-18 22:23:12 -08001387 TransformJarJar(ctx, jarjarFile, jarjarAndDepsHeaderJar, j.expandJarjarRules)
1388 jarjarAndDepsHeaderJar = jarjarFile
Jaewoong Jung26342642021-03-17 15:56:23 -07001389 if ctx.Failed() {
1390 return nil, nil
1391 }
1392 }
1393
Colin Cross0ba588d2021-11-18 22:23:12 -08001394 return headerJar, jarjarAndDepsHeaderJar
Jaewoong Jung26342642021-03-17 15:56:23 -07001395}
1396
1397func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001398 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001399
1400 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1401 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1402
1403 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1404
1405 j.jacocoReportClassesFile = jacocoReportClassesFile
1406
1407 return instrumentedJar
1408}
1409
1410func (j *Module) HeaderJars() android.Paths {
1411 if j.headerJarFile == nil {
1412 return nil
1413 }
1414 return android.Paths{j.headerJarFile}
1415}
1416
1417func (j *Module) ImplementationJars() android.Paths {
1418 if j.implementationJarFile == nil {
1419 return nil
1420 }
1421 return android.Paths{j.implementationJarFile}
1422}
1423
1424func (j *Module) DexJarBuildPath() android.Path {
1425 return j.dexJarFile
1426}
1427
1428func (j *Module) DexJarInstallPath() android.Path {
1429 return j.installFile
1430}
1431
1432func (j *Module) ImplementationAndResourcesJars() android.Paths {
1433 if j.implementationAndResourcesJar == nil {
1434 return nil
1435 }
1436 return android.Paths{j.implementationAndResourcesJar}
1437}
1438
1439func (j *Module) AidlIncludeDirs() android.Paths {
1440 // exportAidlIncludeDirs is type android.Paths already
1441 return j.exportAidlIncludeDirs
1442}
1443
1444func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1445 return j.classLoaderContexts
1446}
1447
1448// Collect information for opening IDE project files in java/jdeps.go.
1449func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1450 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1451 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1452 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1453 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1454 if j.expandJarjarRules != nil {
1455 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1456 }
1457 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1458}
1459
1460func (j *Module) CompilerDeps() []string {
1461 jdeps := []string{}
1462 jdeps = append(jdeps, j.properties.Libs...)
1463 jdeps = append(jdeps, j.properties.Static_libs...)
1464 return jdeps
1465}
1466
1467func (j *Module) hasCode(ctx android.ModuleContext) bool {
1468 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1469 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1470}
1471
1472// Implements android.ApexModule
1473func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1474 return j.depIsInSameApex(ctx, dep)
1475}
1476
1477// Implements android.ApexModule
1478func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1479 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001480 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001481 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001482 return fmt.Errorf("min_sdk_version is not specified")
1483 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001484 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001485 return nil
1486 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001487 ver, err := sdkSpec.EffectiveVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001488 if err != nil {
1489 return err
1490 }
Jiyong Park54105c42021-03-31 18:17:53 +09001491 if ver.GreaterThan(sdkVersion) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001492 return fmt.Errorf("newer SDK(%v)", ver)
1493 }
1494 return nil
1495}
1496
1497func (j *Module) Stem() string {
1498 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1499}
1500
Jaewoong Jung26342642021-03-17 15:56:23 -07001501func (j *Module) JacocoReportClassesFile() android.Path {
1502 return j.jacocoReportClassesFile
1503}
1504
1505func (j *Module) IsInstallable() bool {
1506 return Bool(j.properties.Installable)
1507}
1508
1509type sdkLinkType int
1510
1511const (
1512 // TODO(jiyong) rename these for better readability. Make the allowed
1513 // and disallowed link types explicit
1514 // order is important here. See rank()
1515 javaCore sdkLinkType = iota
1516 javaSdk
1517 javaSystem
1518 javaModule
1519 javaSystemServer
1520 javaPlatform
1521)
1522
1523func (lt sdkLinkType) String() string {
1524 switch lt {
1525 case javaCore:
1526 return "core Java API"
1527 case javaSdk:
1528 return "Android API"
1529 case javaSystem:
1530 return "system API"
1531 case javaModule:
1532 return "module API"
1533 case javaSystemServer:
1534 return "system server API"
1535 case javaPlatform:
1536 return "private API"
1537 default:
1538 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1539 }
1540}
1541
1542// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1543// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1544// can't statically depend on modules that use Platform API.
1545func (lt sdkLinkType) rank() int {
1546 return int(lt)
1547}
1548
1549type moduleWithSdkDep interface {
1550 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001551 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001552}
1553
Jiyong Park92315372021-04-02 08:45:46 +09001554func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001555 switch name {
1556 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1557 "stub-annotations", "private-stub-annotations-jar",
1558 "core-lambda-stubs", "core-generated-annotation-stubs":
1559 return javaCore, true
1560 case "android_stubs_current":
1561 return javaSdk, true
1562 case "android_system_stubs_current":
1563 return javaSystem, true
1564 case "android_module_lib_stubs_current":
1565 return javaModule, true
1566 case "android_system_server_stubs_current":
1567 return javaSystemServer, true
1568 case "android_test_stubs_current":
1569 return javaSystem, true
1570 }
1571
1572 if stub, linkType := moduleStubLinkType(name); stub {
1573 return linkType, true
1574 }
1575
Jiyong Park92315372021-04-02 08:45:46 +09001576 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001577 switch ver.Kind {
1578 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001579 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001580 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001581 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001582 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001583 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001584 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001585 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001586 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001587 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001588 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001589 return javaPlatform, false
1590 }
1591
Jiyong Parkf1691d22021-03-29 20:11:58 +09001592 if !ver.Valid() {
1593 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001594 }
1595 return javaSdk, false
1596}
1597
1598// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1599// this module's. See the comment on rank() for details and an example.
1600func (j *Module) checkSdkLinkType(
1601 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1602 if ctx.Host() {
1603 return
1604 }
1605
Jiyong Park92315372021-04-02 08:45:46 +09001606 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001607 if stubs {
1608 return
1609 }
Jiyong Park92315372021-04-02 08:45:46 +09001610 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001611
1612 if myLinkType.rank() < depLinkType.rank() {
1613 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1614 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1615 "property of the source or target module so that target module is built "+
1616 "with the same or smaller API set when compared to the source.",
1617 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1618 }
1619}
1620
1621func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1622 var deps deps
1623
1624 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001625 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001626 if sdkDep.invalidVersion {
1627 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1628 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1629 } else if sdkDep.useFiles {
1630 // sdkDep.jar is actually equivalent to turbine header.jar.
1631 deps.classpath = append(deps.classpath, sdkDep.jars...)
1632 deps.aidlPreprocess = sdkDep.aidl
1633 } else {
1634 deps.aidlPreprocess = sdkDep.aidl
1635 }
1636 }
1637
Jiyong Park92315372021-04-02 08:45:46 +09001638 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001639
1640 ctx.VisitDirectDeps(func(module android.Module) {
1641 otherName := ctx.OtherModuleName(module)
1642 tag := ctx.OtherModuleDependencyTag(module)
1643
1644 if IsJniDepTag(tag) {
1645 // Handled by AndroidApp.collectAppDeps
1646 return
1647 }
1648 if tag == certificateTag {
1649 // Handled by AndroidApp.collectAppDeps
1650 return
1651 }
1652
1653 if dep, ok := module.(SdkLibraryDependency); ok {
1654 switch tag {
1655 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001656 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001657 case staticLibTag:
1658 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1659 }
1660 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1661 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1662 if sdkLinkType != javaPlatform &&
1663 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1664 // dep is a sysprop implementation library, but this module is not linking against
1665 // the platform, so it gets the sysprop public stubs library instead. Replace
1666 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1667 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1668 dep = syspropDep.JavaInfo
1669 }
1670 switch tag {
1671 case bootClasspathTag:
1672 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1673 case libTag, instrumentationForTag:
1674 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1675 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1676 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1677 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1678 case java9LibTag:
1679 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1680 case staticLibTag:
1681 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1682 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1683 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1684 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1685 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1686 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1687 // Turbine doesn't run annotation processors, so any module that uses an
1688 // annotation processor that generates API is incompatible with the turbine
1689 // optimization.
1690 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1691 case pluginTag:
1692 if plugin, ok := module.(*Plugin); ok {
1693 if plugin.pluginProperties.Processor_class != nil {
1694 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1695 } else {
1696 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1697 }
1698 // Turbine doesn't run annotation processors, so any module that uses an
1699 // annotation processor that generates API is incompatible with the turbine
1700 // optimization.
1701 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1702 } else {
1703 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1704 }
1705 case errorpronePluginTag:
1706 if _, ok := module.(*Plugin); ok {
1707 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1708 } else {
1709 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1710 }
1711 case exportedPluginTag:
1712 if plugin, ok := module.(*Plugin); ok {
1713 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1714 if plugin.pluginProperties.Processor_class != nil {
1715 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1716 }
1717 // Turbine doesn't run annotation processors, so any module that uses an
1718 // annotation processor that generates API is incompatible with the turbine
1719 // optimization.
1720 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1721 } else {
1722 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1723 }
1724 case kotlinStdlibTag:
1725 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1726 case kotlinAnnotationsTag:
1727 deps.kotlinAnnotations = dep.HeaderJars
1728 case syspropPublicStubDepTag:
1729 // This is a sysprop implementation library, forward the JavaInfoProvider from
1730 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1731 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1732 JavaInfo: dep,
1733 })
1734 }
1735 } else if dep, ok := module.(android.SourceFileProducer); ok {
1736 switch tag {
1737 case libTag:
1738 checkProducesJars(ctx, dep)
1739 deps.classpath = append(deps.classpath, dep.Srcs()...)
1740 case staticLibTag:
1741 checkProducesJars(ctx, dep)
1742 deps.classpath = append(deps.classpath, dep.Srcs()...)
1743 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1744 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1745 }
1746 } else {
1747 switch tag {
1748 case bootClasspathTag:
1749 // If a system modules dependency has been added to the bootclasspath
1750 // then add its libs to the bootclasspath.
1751 sm := module.(SystemModulesProvider)
1752 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1753
1754 case systemModulesTag:
1755 if deps.systemModules != nil {
1756 panic("Found two system module dependencies")
1757 }
1758 sm := module.(SystemModulesProvider)
1759 outputDir, outputDeps := sm.OutputDirAndDeps()
1760 deps.systemModules = &systemModules{outputDir, outputDeps}
1761 }
1762 }
1763
1764 addCLCFromDep(ctx, module, j.classLoaderContexts)
1765 })
1766
1767 return deps
1768}
1769
1770func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1771 deps.processorPath = append(deps.processorPath, pluginJars...)
1772 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1773}
1774
1775// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1776// this interface.
1777type ProvidesUsesLib interface {
1778 ProvidesUsesLib() *string
1779}
1780
1781func (j *Module) ProvidesUsesLib() *string {
1782 return j.usesLibraryProperties.Provides_uses_lib
1783}
satayev07753d82021-05-25 19:50:30 +01001784
1785type ModuleWithStem interface {
1786 Stem() string
1787}
1788
1789var _ ModuleWithStem = (*Module)(nil)