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