blob: 1daa10876b370a79854eee60035c279c0e6959ab [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
159 // Whether to run errorprone on a normal build. If this is false, errorprone
160 // will still be run if the RUN_ERROR_PRONE environment variable is true.
161 // Default false.
162 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700163 }
164
165 Proto struct {
166 // List of extra options that will be passed to the proto generator.
167 Output_params []string
168 }
169
170 Instrument bool `blueprint:"mutated"`
171
172 // List of files to include in the META-INF/services folder of the resulting jar.
173 Services []string `android:"path,arch_variant"`
174
175 // If true, package the kotlin stdlib into the jar. Defaults to true.
176 Static_kotlin_stdlib *bool `android:"arch_variant"`
177
178 // A list of java_library instances that provide additional hiddenapi annotations for the library.
179 Hiddenapi_additional_annotations []string
180}
181
182// Properties that are specific to device modules. Host module factories should not add these when
183// constructing a new module.
184type DeviceProperties struct {
185 // if not blank, set to the version of the sdk to compile against.
186 // Defaults to compiling against the current platform.
187 Sdk_version *string
188
189 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
190 // Defaults to sdk_version if not set.
191 Min_sdk_version *string
192
193 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
194 // Defaults to sdk_version if not set.
195 Target_sdk_version *string
196
197 // Whether to compile against the platform APIs instead of an SDK.
198 // If true, then sdk_version must be empty. The value of this field
199 // is ignored when module's type isn't android_app.
200 Platform_apis *bool
201
202 Aidl struct {
203 // Top level directories to pass to aidl tool
204 Include_dirs []string
205
206 // Directories rooted at the Android.bp file to pass to aidl tool
207 Local_include_dirs []string
208
209 // directories that should be added as include directories for any aidl sources of modules
210 // that depend on this module, as well as to aidl for this module.
211 Export_include_dirs []string
212
213 // whether to generate traces (for systrace) for this interface
214 Generate_traces *bool
215
216 // whether to generate Binder#GetTransaction name method.
217 Generate_get_transaction_name *bool
218
219 // list of flags that will be passed to the AIDL compiler
220 Flags []string
221 }
222
223 // If true, export a copy of the module as a -hostdex module for host testing.
224 Hostdex *bool
225
226 Target struct {
227 Hostdex struct {
228 // Additional required dependencies to add to -hostdex modules.
229 Required []string
230 }
231 }
232
233 // When targeting 1.9 and above, override the modules to use with --system,
234 // otherwise provides defaults libraries to add to the bootclasspath.
235 System_modules *string
236
Jaewoong Jung26342642021-03-17 15:56:23 -0700237 // set the name of the output
238 Stem *string
239
240 IsSDKLibrary bool `blueprint:"mutated"`
241
242 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
243 // Defaults to false.
244 V4_signature *bool
245
246 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
247 // public stubs library.
248 SyspropPublicStub string `blueprint:"mutated"`
249}
250
251// Functionality common to Module and Import
252//
253// It is embedded in Module so its functionality can be used by methods in Module
254// but it is currently only initialized by Import and Library.
255type embeddableInModuleAndImport struct {
256
257 // Functionality related to this being used as a component of a java_sdk_library.
258 EmbeddableSdkLibraryComponent
259}
260
261func (e *embeddableInModuleAndImport) initModuleAndImport(moduleBase *android.ModuleBase) {
262 e.initSdkLibraryComponent(moduleBase)
263}
264
265// Module/Import's DepIsInSameApex(...) delegates to this method.
266//
267// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
268// the one provided by ApexModuleBase.
269func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
270 // dependencies other than the static linkage are all considered crossing APEX boundary
271 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
272 return true
273 }
274 return false
275}
276
277// Module contains the properties and members used by all java module types
278type Module struct {
279 android.ModuleBase
280 android.DefaultableModuleBase
281 android.ApexModuleBase
282 android.SdkBase
283
284 // Functionality common to Module and Import.
285 embeddableInModuleAndImport
286
287 properties CommonProperties
288 protoProperties android.ProtoProperties
289 deviceProperties DeviceProperties
290
291 // jar file containing header classes including static library dependencies, suitable for
292 // inserting into the bootclasspath/classpath of another compile
293 headerJarFile android.Path
294
295 // jar file containing implementation classes including static library dependencies but no
296 // resources
297 implementationJarFile android.Path
298
299 // jar file containing only resources including from static library dependencies
300 resourceJar android.Path
301
302 // args and dependencies to package source files into a srcjar
303 srcJarArgs []string
304 srcJarDeps android.Paths
305
306 // jar file containing implementation classes and resources including static library
307 // dependencies
308 implementationAndResourcesJar android.Path
309
310 // output file containing classes.dex and resources
311 dexJarFile android.Path
312
313 // output file containing uninstrumented classes that will be instrumented by jacoco
314 jacocoReportClassesFile android.Path
315
316 // output file of the module, which may be a classes jar or a dex jar
317 outputFile android.Path
318 extraOutputFiles android.Paths
319
320 exportAidlIncludeDirs android.Paths
321
322 logtagsSrcs android.Paths
323
324 // installed file for binary dependency
325 installFile android.Path
326
327 // list of .java files and srcjars that was passed to javac
328 compiledJavaSrcs android.Paths
329 compiledSrcJars android.Paths
330
331 // manifest file to use instead of properties.Manifest
332 overrideManifest android.OptionalPath
333
334 // map of SDK version to class loader context
335 classLoaderContexts dexpreopt.ClassLoaderContextMap
336
337 // list of plugins that this java module is exporting
338 exportedPluginJars android.Paths
339
340 // list of plugins that this java module is exporting
341 exportedPluginClasses []string
342
343 // if true, the exported plugins generate API and require disabling turbine.
344 exportedDisableTurbine bool
345
346 // list of source files, collected from srcFiles with unique java and all kt files,
347 // will be used by android.IDEInfo struct
348 expandIDEInfoCompiledSrcs []string
349
350 // expanded Jarjar_rules
351 expandJarjarRules android.Path
352
353 // list of additional targets for checkbuild
354 additionalCheckedModules android.Paths
355
356 // Extra files generated by the module type to be added as java resources.
357 extraResources android.Paths
358
359 hiddenAPI
360 dexer
361 dexpreopter
362 usesLibrary
363 linter
364
365 // list of the xref extraction files
366 kytheFiles android.Paths
367
368 // Collect the module directory for IDE info in java/jdeps.go.
369 modulePaths []string
370
371 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900372
373 sdkVersion android.SdkSpec
374 minSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700375}
376
Jiyong Park92315372021-04-02 08:45:46 +0900377func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
378 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900379 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700380 return nil
381 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900382 if sdkVersion.Kind == android.SdkCorePlatform {
Jaewoong Jung26342642021-03-17 15:56:23 -0700383 if useLegacyCorePlatformApiByName(j.BaseModuleName()) {
384 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
385 } else {
386 // Treat stable core platform as stable.
387 return nil
388 }
389 } else {
390 return fmt.Errorf("non stable SDK %v", sdkVersion)
391 }
392}
393
394// checkSdkVersions enforces restrictions around SDK dependencies.
395func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
396 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900397 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900398 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700399 ctx.PropertyErrorf("sdk_version",
400 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
401 }
402 }
403 }
404
405 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
406 // See rank() for details.
407 ctx.VisitDirectDeps(func(module android.Module) {
408 tag := ctx.OtherModuleDependencyTag(module)
409 switch module.(type) {
410 // TODO(satayev): cover other types as well, e.g. imports
411 case *Library, *AndroidLibrary:
412 switch tag {
413 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
414 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
415 }
416 }
417 })
418}
419
420func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900421 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700422 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900423 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700424 if usePlatformAPI && sdkVersionSpecified {
425 ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
426 } else if !usePlatformAPI && !sdkVersionSpecified {
427 ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
428 }
429
430 }
431}
432
433func (j *Module) addHostProperties() {
434 j.AddProperties(
435 &j.properties,
436 &j.protoProperties,
437 &j.usesLibraryProperties,
438 )
439}
440
441func (j *Module) addHostAndDeviceProperties() {
442 j.addHostProperties()
443 j.AddProperties(
444 &j.deviceProperties,
445 &j.dexer.dexProperties,
446 &j.dexpreoptProperties,
447 &j.linter.properties,
448 )
449}
450
451func (j *Module) OutputFiles(tag string) (android.Paths, error) {
452 switch tag {
453 case "":
454 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
455 case android.DefaultDistTag:
456 return android.Paths{j.outputFile}, nil
457 case ".jar":
458 return android.Paths{j.implementationAndResourcesJar}, nil
459 case ".proguard_map":
460 if j.dexer.proguardDictionary.Valid() {
461 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
462 }
463 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
464 default:
465 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
466 }
467}
468
469var _ android.OutputFileProducer = (*Module)(nil)
470
471func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
472 initJavaModule(module, hod, false)
473}
474
475func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
476 initJavaModule(module, hod, true)
477}
478
479func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
480 multilib := android.MultilibCommon
481 if multiTargets {
482 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
483 } else {
484 android.InitAndroidArchModule(module, hod, multilib)
485 }
486 android.InitDefaultableModule(module)
487}
488
489func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
490 return j.properties.Instrument &&
491 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
492 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
493}
494
495func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
496 return j.shouldInstrument(ctx) &&
497 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
498 ctx.Config().UnbundledBuild())
499}
500
501func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
502 // Force enable the instrumentation for java code that is built for APEXes ...
503 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
504 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
505 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
506 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
507 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
508 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
509 return true
510 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
511 return true
512 }
513 }
514 return false
515}
516
Jiyong Park92315372021-04-02 08:45:46 +0900517func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
518 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700519}
520
Jiyong Parkf1691d22021-03-29 20:11:58 +0900521func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700522 return proptools.String(j.deviceProperties.System_modules)
523}
524
Jiyong Park92315372021-04-02 08:45:46 +0900525func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700526 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900527 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700528 }
Jiyong Park92315372021-04-02 08:45:46 +0900529 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700530}
531
Jiyong Parkf1691d22021-03-29 20:11:58 +0900532func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900533 return j.minSdkVersion.Raw
534}
535
536func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
537 if j.deviceProperties.Target_sdk_version != nil {
538 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
539 }
540 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700541}
542
543func (j *Module) AvailableFor(what string) bool {
544 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
545 // Exception: for hostdex: true libraries, the platform variant is created
546 // even if it's not marked as available to platform. In that case, the platform
547 // variant is used only for the hostdex and not installed to the device.
548 return true
549 }
550 return j.ApexModuleBase.AvailableFor(what)
551}
552
553func (j *Module) deps(ctx android.BottomUpMutatorContext) {
554 if ctx.Device() {
555 j.linter.deps(ctx)
556
Jiyong Parkf1691d22021-03-29 20:11:58 +0900557 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700558
559 if j.deviceProperties.SyspropPublicStub != "" {
560 // This is a sysprop implementation library that has a corresponding sysprop public
561 // stubs library, and a dependency on it so that dependencies on the implementation can
562 // be forwarded to the public stubs library when necessary.
563 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
564 }
565 }
566
567 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
568 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
569
570 // Add dependency on libraries that provide additional hidden api annotations.
571 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
572
573 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
574 // Require java_sdk_library at inter-partition java dependency to ensure stable
575 // interface between partitions. If inter-partition java_library dependency is detected,
576 // raise build error because java_library doesn't have a stable interface.
577 //
578 // Inputs:
579 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
580 // if true, enable enforcement
581 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
582 // exception list of java_library names to allow inter-partition dependency
583 for idx := range j.properties.Libs {
584 if libDeps[idx] == nil {
585 continue
586 }
587
588 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
589 // java_sdk_library is always allowed at inter-partition dependency.
590 // So, skip check.
591 if _, ok := javaDep.(*SdkLibrary); ok {
592 continue
593 }
594
595 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
596 }
597 }
598 }
599
600 // For library dependencies that are component libraries (like stubs), add the implementation
601 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
602 for _, dep := range libDeps {
603 if dep != nil {
604 if component, ok := dep.(SdkLibraryComponentDependency); ok {
605 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
606 ctx.AddVariationDependencies(nil, usesLibTag, *lib)
607 }
608 }
609 }
610 }
611
612 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
613 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
614 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
615
616 android.ProtoDeps(ctx, &j.protoProperties)
617 if j.hasSrcExt(".proto") {
618 protoDeps(ctx, &j.protoProperties)
619 }
620
621 if j.hasSrcExt(".kt") {
622 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
623 // Kotlin files
624 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
625 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
626 if len(j.properties.Plugins) > 0 {
627 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
628 }
629 }
630
631 // Framework libraries need special handling in static coverage builds: they should not have
632 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
633 // the same jacoco classes coming from different bootclasspath jars.
634 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
635 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
636 j.properties.Instrument = true
637 }
638 } else if j.shouldInstrumentStatic(ctx) {
639 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
640 }
641}
642
643func hasSrcExt(srcs []string, ext string) bool {
644 for _, src := range srcs {
645 if filepath.Ext(src) == ext {
646 return true
647 }
648 }
649
650 return false
651}
652
653func (j *Module) hasSrcExt(ext string) bool {
654 return hasSrcExt(j.properties.Srcs, ext)
655}
656
657func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
658 aidlIncludeDirs android.Paths) (string, android.Paths) {
659
660 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
661 aidlIncludes = append(aidlIncludes,
662 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
663 aidlIncludes = append(aidlIncludes,
664 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
665
666 var flags []string
667 var deps android.Paths
668
669 flags = append(flags, j.deviceProperties.Aidl.Flags...)
670
671 if aidlPreprocess.Valid() {
672 flags = append(flags, "-p"+aidlPreprocess.String())
673 deps = append(deps, aidlPreprocess.Path())
674 } else if len(aidlIncludeDirs) > 0 {
675 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
676 }
677
678 if len(j.exportAidlIncludeDirs) > 0 {
679 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
680 }
681
682 if len(aidlIncludes) > 0 {
683 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
684 }
685
686 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
687 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
688 flags = append(flags, "-I"+src.String())
689 }
690
691 if Bool(j.deviceProperties.Aidl.Generate_traces) {
692 flags = append(flags, "-t")
693 }
694
695 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
696 flags = append(flags, "--transaction_names")
697 }
698
699 return strings.Join(flags, " "), deps
700}
701
702func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
703
704 var flags javaBuilderFlags
705
706 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900707 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700708
Cole Faust75fffb12021-06-13 15:23:16 -0700709 if ctx.Config().RunErrorProne() || Bool(j.properties.Errorprone.Enabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700710 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
711 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
712 }
713
714 errorProneFlags := []string{
715 "-Xplugin:ErrorProne",
716 "${config.ErrorProneChecks}",
717 }
718 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
719
720 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
721 "'" + strings.Join(errorProneFlags, " ") + "'"
722 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
723 }
724
725 // classpath
726 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
727 flags.classpath = append(flags.classpath, deps.classpath...)
728 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
729 flags.processorPath = append(flags.processorPath, deps.processorPath...)
730 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
731
732 flags.processors = append(flags.processors, deps.processorClasses...)
733 flags.processors = android.FirstUniqueStrings(flags.processors)
734
735 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900736 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700737 // Give host-side tools a version of OpenJDK's standard libraries
738 // close to what they're targeting. As of Dec 2017, AOSP is only
739 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
740 //
741 // When building with OpenJDK 8, the following should have no
742 // effect since those jars would be available by default.
743 //
744 // When building with OpenJDK 9 but targeting a version < 1.8,
745 // putting them on the bootclasspath means that:
746 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
747 // b) references to existing APIs are not reinterpreted in an
748 // OpenJDK 9-specific way, eg. calls to subclasses of
749 // java.nio.Buffer as in http://b/70862583
750 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
751 flags.bootClasspath = append(flags.bootClasspath,
752 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
753 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
754 if Bool(j.properties.Use_tools_jar) {
755 flags.bootClasspath = append(flags.bootClasspath,
756 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
757 }
758 }
759
760 // systemModules
761 flags.systemModules = deps.systemModules
762
763 // aidl flags.
764 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
765
766 return flags
767}
768
769func (j *Module) collectJavacFlags(
770 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
771 // javac flags.
772 javacFlags := j.properties.Javacflags
773
774 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
775 // For non-host binaries, override the -g flag passed globally to remove
776 // local variable debug info to reduce disk and memory usage.
777 javacFlags = append(javacFlags, "-g:source,lines")
778 }
779 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
780
781 if flags.javaVersion.usesJavaModules() {
782 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
783
784 if j.properties.Patch_module != nil {
785 // Manually specify build directory in case it is not under the repo root.
786 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
787 // just adding a symlink under the root doesn't help.)
788 patchPaths := []string{".", ctx.Config().BuildDir()}
789
790 // b/150878007
791 //
792 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
793 // execution root for --patch-module. If this javac command line is
794 // invoked within Bazel's execution root working directory, the top
795 // level directories (e.g. libcore/, tools/, frameworks/) are all
796 // symlinks. JDK9 javac does not traverse into symlinks, which causes
797 // --patch-module to fail source file lookups when invoked in the
798 // execution root.
799 //
800 // Short of patching javac or enumerating *all* directories as possible
801 // input dirs, manually add the top level dir of the source files to be
802 // compiled.
803 topLevelDirs := map[string]bool{}
804 for _, srcFilePath := range srcFiles {
805 srcFileParts := strings.Split(srcFilePath.String(), "/")
806 // Ignore source files that are already in the top level directory
807 // as well as generated files in the out directory. The out
808 // directory may be an absolute path, which means srcFileParts[0] is the
809 // empty string, so check that as well. Note that "out" in Bazel's execution
810 // root is *not* a symlink, which doesn't cause problems for --patch-modules
811 // anyway, so it's fine to not apply this workaround for generated
812 // source files.
813 if len(srcFileParts) > 1 &&
814 srcFileParts[0] != "" &&
815 srcFileParts[0] != "out" {
816 topLevelDirs[srcFileParts[0]] = true
817 }
818 }
819 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
820
821 classPath := flags.classpath.FormJavaClassPath("")
822 if classPath != "" {
823 patchPaths = append(patchPaths, classPath)
824 }
825 javacFlags = append(
826 javacFlags,
827 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
828 }
829 }
830
831 if len(javacFlags) > 0 {
832 // optimization.
833 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
834 flags.javacFlags = "$javacFlags"
835 }
836
837 return flags
838}
839
840func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
841 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
842
843 deps := j.collectDeps(ctx)
844 flags := j.collectBuilderFlags(ctx, deps)
845
846 if flags.javaVersion.usesJavaModules() {
847 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
848 }
849 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
850 if hasSrcExt(srcFiles.Strings(), ".proto") {
851 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
852 }
853
854 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
855 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
856 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
857 }
858
859 srcFiles = j.genSources(ctx, srcFiles, flags)
860
861 // Collect javac flags only after computing the full set of srcFiles to
862 // ensure that the --patch-module lookup paths are complete.
863 flags = j.collectJavacFlags(ctx, flags, srcFiles)
864
865 srcJars := srcFiles.FilterByExt(".srcjar")
866 srcJars = append(srcJars, deps.srcJars...)
867 if aaptSrcJar != nil {
868 srcJars = append(srcJars, aaptSrcJar)
869 }
870
871 if j.properties.Jarjar_rules != nil {
872 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
873 }
874
875 jarName := ctx.ModuleName() + ".jar"
876
877 javaSrcFiles := srcFiles.FilterByExt(".java")
878 var uniqueSrcFiles android.Paths
879 set := make(map[string]bool)
880 for _, v := range javaSrcFiles {
881 if _, found := set[v.String()]; !found {
882 set[v.String()] = true
883 uniqueSrcFiles = append(uniqueSrcFiles, v)
884 }
885 }
886
887 // Collect .java files for AIDEGen
888 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
889
890 var kotlinJars android.Paths
891
892 if srcFiles.HasExt(".kt") {
893 // user defined kotlin flags.
894 kotlincFlags := j.properties.Kotlincflags
895 CheckKotlincFlags(ctx, kotlincFlags)
896
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000897 // Workaround for KT-46512
898 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700899
900 // If there are kotlin files, compile them first but pass all the kotlin and java files
901 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
902 // won't emit any classes for them.
903 kotlincFlags = append(kotlincFlags, "-no-stdlib")
904 if ctx.Device() {
905 kotlincFlags = append(kotlincFlags, "-no-jdk")
906 }
907 if len(kotlincFlags) > 0 {
908 // optimization.
909 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
910 flags.kotlincFlags += "$kotlincFlags"
911 }
912
913 var kotlinSrcFiles android.Paths
914 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
915 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
916
917 // Collect .kt files for AIDEGen
918 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
919 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
920
921 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
922 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
923
924 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
925 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
926
927 if len(flags.processorPath) > 0 {
928 // Use kapt for annotation processing
929 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
930 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
931 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
932 srcJars = append(srcJars, kaptSrcJar)
933 kotlinJars = append(kotlinJars, kaptResJar)
934 // Disable annotation processing in javac, it's already been handled by kapt
935 flags.processorPath = nil
936 flags.processors = nil
937 }
938
939 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
940 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
941 if ctx.Failed() {
942 return
943 }
944
945 // Make javac rule depend on the kotlinc rule
946 flags.classpath = append(flags.classpath, kotlinJar)
947
948 kotlinJars = append(kotlinJars, kotlinJar)
949 // Jar kotlin classes into the final jar after javac
950 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
951 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
952 }
953 }
954
955 jars := append(android.Paths(nil), kotlinJars...)
956
957 // Store the list of .java files that was passed to javac
958 j.compiledJavaSrcs = uniqueSrcFiles
959 j.compiledSrcJars = srcJars
960
961 enableSharding := false
962 var headerJarFileWithoutJarjar android.Path
963 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
964 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
965 enableSharding = true
966 // Formerly, there was a check here that prevented annotation processors
967 // from being used when sharding was enabled, as some annotation processors
968 // do not function correctly in sharded environments. It was removed to
969 // allow for the use of annotation processors that do function correctly
970 // with sharding enabled. See: b/77284273.
971 }
972 headerJarFileWithoutJarjar, j.headerJarFile =
973 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
974 if ctx.Failed() {
975 return
976 }
977 }
978 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
979 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -0700980 if Bool(j.properties.Errorprone.Enabled) {
981 // If error-prone is enabled, enable errorprone flags on the regular
982 // build.
983 flags = enableErrorproneFlags(flags)
984 } else if ctx.Config().RunErrorProne() {
985 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
986 // a new jar file just for compiling with the errorprone compiler to.
987 // This is because we don't want to cause the java files to get completely
988 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
989 // We also don't want to run this if errorprone is enabled by default for
990 // this module, or else we could have duplicated errorprone messages.
991 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -0700992 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -0700993
994 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
995 "errorprone", "errorprone")
996
Jaewoong Jung26342642021-03-17 15:56:23 -0700997 extraJarDeps = append(extraJarDeps, errorprone)
998 }
999
1000 if enableSharding {
1001 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
1002 shardSize := int(*(j.properties.Javac_shard_size))
1003 var shardSrcs []android.Paths
1004 if len(uniqueSrcFiles) > 0 {
1005 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1006 for idx, shardSrc := range shardSrcs {
1007 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1008 nil, flags, extraJarDeps)
1009 jars = append(jars, classes)
1010 }
1011 }
1012 if len(srcJars) > 0 {
1013 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1014 nil, srcJars, flags, extraJarDeps)
1015 jars = append(jars, classes)
1016 }
1017 } else {
1018 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1019 jars = append(jars, classes)
1020 }
1021 if ctx.Failed() {
1022 return
1023 }
1024 }
1025
1026 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1027
1028 var includeSrcJar android.WritablePath
1029 if Bool(j.properties.Include_srcs) {
1030 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1031 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1032 }
1033
1034 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1035 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1036 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1037 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1038
1039 var resArgs []string
1040 var resDeps android.Paths
1041
1042 resArgs = append(resArgs, dirArgs...)
1043 resDeps = append(resDeps, dirDeps...)
1044
1045 resArgs = append(resArgs, fileArgs...)
1046 resDeps = append(resDeps, fileDeps...)
1047
1048 resArgs = append(resArgs, extraArgs...)
1049 resDeps = append(resDeps, extraDeps...)
1050
1051 if len(resArgs) > 0 {
1052 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1053 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1054 j.resourceJar = resourceJar
1055 if ctx.Failed() {
1056 return
1057 }
1058 }
1059
1060 var resourceJars android.Paths
1061 if j.resourceJar != nil {
1062 resourceJars = append(resourceJars, j.resourceJar)
1063 }
1064 if Bool(j.properties.Include_srcs) {
1065 resourceJars = append(resourceJars, includeSrcJar)
1066 }
1067 resourceJars = append(resourceJars, deps.staticResourceJars...)
1068
1069 if len(resourceJars) > 1 {
1070 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1071 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1072 false, nil, nil)
1073 j.resourceJar = combinedJar
1074 } else if len(resourceJars) == 1 {
1075 j.resourceJar = resourceJars[0]
1076 }
1077
1078 if len(deps.staticJars) > 0 {
1079 jars = append(jars, deps.staticJars...)
1080 }
1081
1082 manifest := j.overrideManifest
1083 if !manifest.Valid() && j.properties.Manifest != nil {
1084 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1085 }
1086
1087 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1088 if len(services) > 0 {
1089 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1090 var zipargs []string
1091 for _, file := range services {
1092 serviceFile := file.String()
1093 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1094 }
1095 rule := zip
1096 args := map[string]string{
1097 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1098 }
1099 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1100 rule = zipRE
1101 args["implicits"] = strings.Join(services.Strings(), ",")
1102 }
1103 ctx.Build(pctx, android.BuildParams{
1104 Rule: rule,
1105 Output: servicesJar,
1106 Implicits: services,
1107 Args: args,
1108 })
1109 jars = append(jars, servicesJar)
1110 }
1111
1112 // Combine the classes built from sources, any manifests, and any static libraries into
1113 // classes.jar. If there is only one input jar this step will be skipped.
1114 var outputFile android.OutputPath
1115
1116 if len(jars) == 1 && !manifest.Valid() {
1117 // Optimization: skip the combine step as there is nothing to do
1118 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1119 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1120 // any if len(jars) == 1.
1121
1122 // Transform the single path to the jar into an OutputPath as that is required by the following
1123 // code.
1124 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1125 // The path contains an embedded OutputPath so reuse that.
1126 outputFile = moduleOutPath.OutputPath
1127 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1128 // The path is an OutputPath so reuse it directly.
1129 outputFile = outputPath
1130 } else {
1131 // The file is not in the out directory so create an OutputPath into which it can be copied
1132 // and which the following code can use to refer to it.
1133 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1134 ctx.Build(pctx, android.BuildParams{
1135 Rule: android.Cp,
1136 Input: jars[0],
1137 Output: combinedJar,
1138 })
1139 outputFile = combinedJar.OutputPath
1140 }
1141 } else {
1142 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1143 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1144 false, nil, nil)
1145 outputFile = combinedJar.OutputPath
1146 }
1147
1148 // jarjar implementation jar if necessary
1149 if j.expandJarjarRules != nil {
1150 // Transform classes.jar into classes-jarjar.jar
1151 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1152 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1153 outputFile = jarjarFile
1154
1155 // jarjar resource jar if necessary
1156 if j.resourceJar != nil {
1157 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1158 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1159 j.resourceJar = resourceJarJarFile
1160 }
1161
1162 if ctx.Failed() {
1163 return
1164 }
1165 }
1166
1167 // Check package restrictions if necessary.
1168 if len(j.properties.Permitted_packages) > 0 {
1169 // Check packages and copy to package-checked file.
1170 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1171 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1172 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1173
1174 if ctx.Failed() {
1175 return
1176 }
1177 }
1178
1179 j.implementationJarFile = outputFile
1180 if j.headerJarFile == nil {
1181 j.headerJarFile = j.implementationJarFile
1182 }
1183
1184 if j.shouldInstrumentInApex(ctx) {
1185 j.properties.Instrument = true
1186 }
1187
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001188 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1189 specs := j.jacocoModuleToZipCommand(ctx)
1190 if ctx.Failed() {
1191 return
1192 }
1193
Jaewoong Jung26342642021-03-17 15:56:23 -07001194 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001195 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001196 }
1197
1198 // merge implementation jar with resources if necessary
1199 implementationAndResourcesJar := outputFile
1200 if j.resourceJar != nil {
1201 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1202 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1203 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1204 false, nil, nil)
1205 implementationAndResourcesJar = combinedJar
1206 }
1207
1208 j.implementationAndResourcesJar = implementationAndResourcesJar
1209
1210 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1211 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1212 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1213 if j.dexProperties.Compile_dex == nil {
1214 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1215 }
1216 if j.deviceProperties.Hostdex == nil {
1217 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1218 }
1219 }
1220
1221 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1222 if j.hasCode(ctx) {
1223 if j.shouldInstrumentStatic(ctx) {
1224 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1225 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1226 }
1227 // Dex compilation
1228 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001229 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001230 if ctx.Failed() {
1231 return
1232 }
1233
Jaewoong Jung26342642021-03-17 15:56:23 -07001234 // merge dex jar with resources if necessary
1235 if j.resourceJar != nil {
1236 jars := android.Paths{dexOutputFile, j.resourceJar}
1237 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1238 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1239 false, nil, nil)
1240 if *j.dexProperties.Uncompress_dex {
1241 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1242 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1243 dexOutputFile = combinedAlignedJar
1244 } else {
1245 dexOutputFile = combinedJar
1246 }
1247 }
1248
Paul Duffin4de94502021-05-16 05:21:16 +01001249 // Initialize the hiddenapi structure.
1250 j.initHiddenAPI(ctx, dexOutputFile, j.implementationJarFile, j.dexProperties.Uncompress_dex)
1251
1252 // Encode hidden API flags in dex file, if needed.
1253 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1254
Jaewoong Jung26342642021-03-17 15:56:23 -07001255 j.dexJarFile = dexOutputFile
1256
1257 // Dexpreopting
1258 j.dexpreopt(ctx, dexOutputFile)
1259
1260 outputFile = dexOutputFile
1261 } else {
1262 // There is no code to compile into a dex jar, make sure the resources are propagated
1263 // to the APK if this is an app.
1264 outputFile = implementationAndResourcesJar
1265 j.dexJarFile = j.resourceJar
1266 }
1267
1268 if ctx.Failed() {
1269 return
1270 }
1271 } else {
1272 outputFile = implementationAndResourcesJar
1273 }
1274
1275 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001276 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001277 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001278 return v.String()
1279 } else {
1280 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1281 }
1282 }
1283
1284 j.linter.name = ctx.ModuleName()
1285 j.linter.srcs = srcFiles
1286 j.linter.srcJars = srcJars
1287 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1288 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001289 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1290 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1291 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Jaewoong Jung26342642021-03-17 15:56:23 -07001292 j.linter.javaLanguageLevel = flags.javaVersion.String()
1293 j.linter.kotlinLanguageLevel = "1.3"
1294 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1295 j.linter.buildModuleReportZip = true
1296 }
1297 j.linter.lint(ctx)
1298 }
1299
1300 ctx.CheckbuildFile(outputFile)
1301
1302 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1303 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1304 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1305 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1306 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1307 AidlIncludeDirs: j.exportAidlIncludeDirs,
1308 SrcJarArgs: j.srcJarArgs,
1309 SrcJarDeps: j.srcJarDeps,
1310 ExportedPlugins: j.exportedPluginJars,
1311 ExportedPluginClasses: j.exportedPluginClasses,
1312 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1313 JacocoReportClassesFile: j.jacocoReportClassesFile,
1314 })
1315
1316 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1317 j.outputFile = outputFile.WithoutRel()
1318}
1319
Cole Faust75fffb12021-06-13 15:23:16 -07001320// Returns a copy of the supplied flags, but with all the errorprone-related
1321// fields copied to the regular build's fields.
1322func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1323 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1324
1325 if len(flags.errorProneExtraJavacFlags) > 0 {
1326 if len(flags.javacFlags) > 0 {
1327 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1328 } else {
1329 flags.javacFlags = flags.errorProneExtraJavacFlags
1330 }
1331 }
1332 return flags
1333}
1334
Jaewoong Jung26342642021-03-17 15:56:23 -07001335func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1336 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1337
1338 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1339 if idx >= 0 {
1340 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1341 jarName += strconv.Itoa(idx)
1342 }
1343
1344 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1345 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1346
1347 if ctx.Config().EmitXrefRules() {
1348 extractionFile := android.PathForModuleOut(ctx, kzipName)
1349 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1350 j.kytheFiles = append(j.kytheFiles, extractionFile)
1351 }
1352
1353 return classes
1354}
1355
1356// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1357// since some of these flags may be used internally.
1358func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1359 for _, flag := range flags {
1360 flag = strings.TrimSpace(flag)
1361
1362 if !strings.HasPrefix(flag, "-") {
1363 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1364 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1365 ctx.PropertyErrorf("kotlincflags",
1366 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1367 } else if inList(flag, config.KotlincIllegalFlags) {
1368 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1369 } else if flag == "-include-runtime" {
1370 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1371 } else {
1372 args := strings.Split(flag, " ")
1373 if args[0] == "-kotlin-home" {
1374 ctx.PropertyErrorf("kotlincflags",
1375 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1376 }
1377 }
1378 }
1379}
1380
1381func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1382 deps deps, flags javaBuilderFlags, jarName string,
1383 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1384
1385 var jars android.Paths
1386 if len(srcFiles) > 0 || len(srcJars) > 0 {
1387 // Compile java sources into turbine.jar.
1388 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1389 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1390 if ctx.Failed() {
1391 return nil, nil
1392 }
1393 jars = append(jars, turbineJar)
1394 }
1395
1396 jars = append(jars, extraJars...)
1397
1398 // Combine any static header libraries into classes-header.jar. If there is only
1399 // one input jar this step will be skipped.
1400 jars = append(jars, deps.staticHeaderJars...)
1401
1402 // we cannot skip the combine step for now if there is only one jar
1403 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1404 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1405 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1406 false, nil, []string{"META-INF/TRANSITIVE"})
1407 headerJar = combinedJar
1408 jarjarHeaderJar = combinedJar
1409
1410 if j.expandJarjarRules != nil {
1411 // Transform classes.jar into classes-jarjar.jar
1412 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1413 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1414 jarjarHeaderJar = jarjarFile
1415 if ctx.Failed() {
1416 return nil, nil
1417 }
1418 }
1419
1420 return headerJar, jarjarHeaderJar
1421}
1422
1423func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001424 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001425
1426 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1427 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1428
1429 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1430
1431 j.jacocoReportClassesFile = jacocoReportClassesFile
1432
1433 return instrumentedJar
1434}
1435
1436func (j *Module) HeaderJars() android.Paths {
1437 if j.headerJarFile == nil {
1438 return nil
1439 }
1440 return android.Paths{j.headerJarFile}
1441}
1442
1443func (j *Module) ImplementationJars() android.Paths {
1444 if j.implementationJarFile == nil {
1445 return nil
1446 }
1447 return android.Paths{j.implementationJarFile}
1448}
1449
1450func (j *Module) DexJarBuildPath() android.Path {
1451 return j.dexJarFile
1452}
1453
1454func (j *Module) DexJarInstallPath() android.Path {
1455 return j.installFile
1456}
1457
1458func (j *Module) ImplementationAndResourcesJars() android.Paths {
1459 if j.implementationAndResourcesJar == nil {
1460 return nil
1461 }
1462 return android.Paths{j.implementationAndResourcesJar}
1463}
1464
1465func (j *Module) AidlIncludeDirs() android.Paths {
1466 // exportAidlIncludeDirs is type android.Paths already
1467 return j.exportAidlIncludeDirs
1468}
1469
1470func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1471 return j.classLoaderContexts
1472}
1473
1474// Collect information for opening IDE project files in java/jdeps.go.
1475func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1476 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1477 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1478 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1479 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1480 if j.expandJarjarRules != nil {
1481 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1482 }
1483 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1484}
1485
1486func (j *Module) CompilerDeps() []string {
1487 jdeps := []string{}
1488 jdeps = append(jdeps, j.properties.Libs...)
1489 jdeps = append(jdeps, j.properties.Static_libs...)
1490 return jdeps
1491}
1492
1493func (j *Module) hasCode(ctx android.ModuleContext) bool {
1494 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1495 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1496}
1497
1498// Implements android.ApexModule
1499func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1500 return j.depIsInSameApex(ctx, dep)
1501}
1502
1503// Implements android.ApexModule
1504func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1505 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001506 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001507 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001508 return fmt.Errorf("min_sdk_version is not specified")
1509 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001510 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001511 return nil
1512 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001513 ver, err := sdkSpec.EffectiveVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -07001514 if err != nil {
1515 return err
1516 }
Jiyong Park54105c42021-03-31 18:17:53 +09001517 if ver.GreaterThan(sdkVersion) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001518 return fmt.Errorf("newer SDK(%v)", ver)
1519 }
1520 return nil
1521}
1522
1523func (j *Module) Stem() string {
1524 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1525}
1526
Jaewoong Jung26342642021-03-17 15:56:23 -07001527func (j *Module) JacocoReportClassesFile() android.Path {
1528 return j.jacocoReportClassesFile
1529}
1530
1531func (j *Module) IsInstallable() bool {
1532 return Bool(j.properties.Installable)
1533}
1534
1535type sdkLinkType int
1536
1537const (
1538 // TODO(jiyong) rename these for better readability. Make the allowed
1539 // and disallowed link types explicit
1540 // order is important here. See rank()
1541 javaCore sdkLinkType = iota
1542 javaSdk
1543 javaSystem
1544 javaModule
1545 javaSystemServer
1546 javaPlatform
1547)
1548
1549func (lt sdkLinkType) String() string {
1550 switch lt {
1551 case javaCore:
1552 return "core Java API"
1553 case javaSdk:
1554 return "Android API"
1555 case javaSystem:
1556 return "system API"
1557 case javaModule:
1558 return "module API"
1559 case javaSystemServer:
1560 return "system server API"
1561 case javaPlatform:
1562 return "private API"
1563 default:
1564 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1565 }
1566}
1567
1568// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1569// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1570// can't statically depend on modules that use Platform API.
1571func (lt sdkLinkType) rank() int {
1572 return int(lt)
1573}
1574
1575type moduleWithSdkDep interface {
1576 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001577 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001578}
1579
Jiyong Park92315372021-04-02 08:45:46 +09001580func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001581 switch name {
1582 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1583 "stub-annotations", "private-stub-annotations-jar",
1584 "core-lambda-stubs", "core-generated-annotation-stubs":
1585 return javaCore, true
1586 case "android_stubs_current":
1587 return javaSdk, true
1588 case "android_system_stubs_current":
1589 return javaSystem, true
1590 case "android_module_lib_stubs_current":
1591 return javaModule, true
1592 case "android_system_server_stubs_current":
1593 return javaSystemServer, true
1594 case "android_test_stubs_current":
1595 return javaSystem, true
1596 }
1597
1598 if stub, linkType := moduleStubLinkType(name); stub {
1599 return linkType, true
1600 }
1601
Jiyong Park92315372021-04-02 08:45:46 +09001602 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001603 switch ver.Kind {
1604 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001605 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001606 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001607 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001608 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001609 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001610 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001611 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001612 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001613 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001614 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001615 return javaPlatform, false
1616 }
1617
Jiyong Parkf1691d22021-03-29 20:11:58 +09001618 if !ver.Valid() {
1619 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001620 }
1621 return javaSdk, false
1622}
1623
1624// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1625// this module's. See the comment on rank() for details and an example.
1626func (j *Module) checkSdkLinkType(
1627 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1628 if ctx.Host() {
1629 return
1630 }
1631
Jiyong Park92315372021-04-02 08:45:46 +09001632 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001633 if stubs {
1634 return
1635 }
Jiyong Park92315372021-04-02 08:45:46 +09001636 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001637
1638 if myLinkType.rank() < depLinkType.rank() {
1639 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1640 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1641 "property of the source or target module so that target module is built "+
1642 "with the same or smaller API set when compared to the source.",
1643 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1644 }
1645}
1646
1647func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1648 var deps deps
1649
1650 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001651 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001652 if sdkDep.invalidVersion {
1653 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1654 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1655 } else if sdkDep.useFiles {
1656 // sdkDep.jar is actually equivalent to turbine header.jar.
1657 deps.classpath = append(deps.classpath, sdkDep.jars...)
1658 deps.aidlPreprocess = sdkDep.aidl
1659 } else {
1660 deps.aidlPreprocess = sdkDep.aidl
1661 }
1662 }
1663
Jiyong Park92315372021-04-02 08:45:46 +09001664 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001665
1666 ctx.VisitDirectDeps(func(module android.Module) {
1667 otherName := ctx.OtherModuleName(module)
1668 tag := ctx.OtherModuleDependencyTag(module)
1669
1670 if IsJniDepTag(tag) {
1671 // Handled by AndroidApp.collectAppDeps
1672 return
1673 }
1674 if tag == certificateTag {
1675 // Handled by AndroidApp.collectAppDeps
1676 return
1677 }
1678
1679 if dep, ok := module.(SdkLibraryDependency); ok {
1680 switch tag {
1681 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001682 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001683 case staticLibTag:
1684 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1685 }
1686 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1687 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1688 if sdkLinkType != javaPlatform &&
1689 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1690 // dep is a sysprop implementation library, but this module is not linking against
1691 // the platform, so it gets the sysprop public stubs library instead. Replace
1692 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1693 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1694 dep = syspropDep.JavaInfo
1695 }
1696 switch tag {
1697 case bootClasspathTag:
1698 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1699 case libTag, instrumentationForTag:
1700 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1701 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1702 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1703 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1704 case java9LibTag:
1705 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1706 case staticLibTag:
1707 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1708 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1709 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1710 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1711 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1712 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1713 // Turbine doesn't run annotation processors, so any module that uses an
1714 // annotation processor that generates API is incompatible with the turbine
1715 // optimization.
1716 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1717 case pluginTag:
1718 if plugin, ok := module.(*Plugin); ok {
1719 if plugin.pluginProperties.Processor_class != nil {
1720 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1721 } else {
1722 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1723 }
1724 // Turbine doesn't run annotation processors, so any module that uses an
1725 // annotation processor that generates API is incompatible with the turbine
1726 // optimization.
1727 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1728 } else {
1729 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1730 }
1731 case errorpronePluginTag:
1732 if _, ok := module.(*Plugin); ok {
1733 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1734 } else {
1735 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1736 }
1737 case exportedPluginTag:
1738 if plugin, ok := module.(*Plugin); ok {
1739 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1740 if plugin.pluginProperties.Processor_class != nil {
1741 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1742 }
1743 // Turbine doesn't run annotation processors, so any module that uses an
1744 // annotation processor that generates API is incompatible with the turbine
1745 // optimization.
1746 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1747 } else {
1748 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1749 }
1750 case kotlinStdlibTag:
1751 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1752 case kotlinAnnotationsTag:
1753 deps.kotlinAnnotations = dep.HeaderJars
1754 case syspropPublicStubDepTag:
1755 // This is a sysprop implementation library, forward the JavaInfoProvider from
1756 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1757 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1758 JavaInfo: dep,
1759 })
1760 }
1761 } else if dep, ok := module.(android.SourceFileProducer); ok {
1762 switch tag {
1763 case libTag:
1764 checkProducesJars(ctx, dep)
1765 deps.classpath = append(deps.classpath, dep.Srcs()...)
1766 case staticLibTag:
1767 checkProducesJars(ctx, dep)
1768 deps.classpath = append(deps.classpath, dep.Srcs()...)
1769 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1770 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1771 }
1772 } else {
1773 switch tag {
1774 case bootClasspathTag:
1775 // If a system modules dependency has been added to the bootclasspath
1776 // then add its libs to the bootclasspath.
1777 sm := module.(SystemModulesProvider)
1778 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1779
1780 case systemModulesTag:
1781 if deps.systemModules != nil {
1782 panic("Found two system module dependencies")
1783 }
1784 sm := module.(SystemModulesProvider)
1785 outputDir, outputDeps := sm.OutputDirAndDeps()
1786 deps.systemModules = &systemModules{outputDir, outputDeps}
1787 }
1788 }
1789
1790 addCLCFromDep(ctx, module, j.classLoaderContexts)
1791 })
1792
1793 return deps
1794}
1795
1796func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1797 deps.processorPath = append(deps.processorPath, pluginJars...)
1798 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1799}
1800
1801// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1802// this interface.
1803type ProvidesUsesLib interface {
1804 ProvidesUsesLib() *string
1805}
1806
1807func (j *Module) ProvidesUsesLib() *string {
1808 return j.usesLibraryProperties.Provides_uses_lib
1809}
satayev1c564cc2021-05-25 19:50:30 +01001810
1811type ModuleWithStem interface {
1812 Stem() string
1813}
1814
1815var _ ModuleWithStem = (*Module)(nil)