blob: 6b8119619ce1c378237c9e8684ef3e0fca99b254 [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
Paul Duffin71b33cc2021-06-23 11:39:47 +0100263func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
264 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700265}
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 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700873 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700874
875 if j.properties.Jarjar_rules != nil {
876 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
877 }
878
879 jarName := ctx.ModuleName() + ".jar"
880
881 javaSrcFiles := srcFiles.FilterByExt(".java")
882 var uniqueSrcFiles android.Paths
883 set := make(map[string]bool)
884 for _, v := range javaSrcFiles {
885 if _, found := set[v.String()]; !found {
886 set[v.String()] = true
887 uniqueSrcFiles = append(uniqueSrcFiles, v)
888 }
889 }
890
891 // Collect .java files for AIDEGen
892 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
893
894 var kotlinJars android.Paths
895
896 if srcFiles.HasExt(".kt") {
897 // user defined kotlin flags.
898 kotlincFlags := j.properties.Kotlincflags
899 CheckKotlincFlags(ctx, kotlincFlags)
900
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000901 // Workaround for KT-46512
902 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700903
904 // If there are kotlin files, compile them first but pass all the kotlin and java files
905 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
906 // won't emit any classes for them.
907 kotlincFlags = append(kotlincFlags, "-no-stdlib")
908 if ctx.Device() {
909 kotlincFlags = append(kotlincFlags, "-no-jdk")
910 }
911 if len(kotlincFlags) > 0 {
912 // optimization.
913 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
914 flags.kotlincFlags += "$kotlincFlags"
915 }
916
917 var kotlinSrcFiles android.Paths
918 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
919 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
920
921 // Collect .kt files for AIDEGen
922 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
923 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
924
925 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
926 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
927
928 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
929 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
930
931 if len(flags.processorPath) > 0 {
932 // Use kapt for annotation processing
933 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
934 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
935 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
936 srcJars = append(srcJars, kaptSrcJar)
937 kotlinJars = append(kotlinJars, kaptResJar)
938 // Disable annotation processing in javac, it's already been handled by kapt
939 flags.processorPath = nil
940 flags.processors = nil
941 }
942
943 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
944 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
945 if ctx.Failed() {
946 return
947 }
948
949 // Make javac rule depend on the kotlinc rule
950 flags.classpath = append(flags.classpath, kotlinJar)
951
952 kotlinJars = append(kotlinJars, kotlinJar)
953 // Jar kotlin classes into the final jar after javac
954 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
955 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
956 }
957 }
958
959 jars := append(android.Paths(nil), kotlinJars...)
960
961 // Store the list of .java files that was passed to javac
962 j.compiledJavaSrcs = uniqueSrcFiles
963 j.compiledSrcJars = srcJars
964
965 enableSharding := false
966 var headerJarFileWithoutJarjar android.Path
967 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
968 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
969 enableSharding = true
970 // Formerly, there was a check here that prevented annotation processors
971 // from being used when sharding was enabled, as some annotation processors
972 // do not function correctly in sharded environments. It was removed to
973 // allow for the use of annotation processors that do function correctly
974 // with sharding enabled. See: b/77284273.
975 }
976 headerJarFileWithoutJarjar, j.headerJarFile =
977 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
978 if ctx.Failed() {
979 return
980 }
981 }
982 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
983 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -0700984 if Bool(j.properties.Errorprone.Enabled) {
985 // If error-prone is enabled, enable errorprone flags on the regular
986 // build.
987 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -0700988 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -0700989 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
990 // a new jar file just for compiling with the errorprone compiler to.
991 // This is because we don't want to cause the java files to get completely
992 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
993 // We also don't want to run this if errorprone is enabled by default for
994 // this module, or else we could have duplicated errorprone messages.
995 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -0700996 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -0700997
998 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
999 "errorprone", "errorprone")
1000
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 extraJarDeps = append(extraJarDeps, errorprone)
1002 }
1003
1004 if enableSharding {
1005 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
1006 shardSize := int(*(j.properties.Javac_shard_size))
1007 var shardSrcs []android.Paths
1008 if len(uniqueSrcFiles) > 0 {
1009 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1010 for idx, shardSrc := range shardSrcs {
1011 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1012 nil, flags, extraJarDeps)
1013 jars = append(jars, classes)
1014 }
1015 }
1016 if len(srcJars) > 0 {
1017 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1018 nil, srcJars, flags, extraJarDeps)
1019 jars = append(jars, classes)
1020 }
1021 } else {
1022 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1023 jars = append(jars, classes)
1024 }
1025 if ctx.Failed() {
1026 return
1027 }
1028 }
1029
1030 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1031
1032 var includeSrcJar android.WritablePath
1033 if Bool(j.properties.Include_srcs) {
1034 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1035 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1036 }
1037
1038 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1039 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1040 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1041 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1042
1043 var resArgs []string
1044 var resDeps android.Paths
1045
1046 resArgs = append(resArgs, dirArgs...)
1047 resDeps = append(resDeps, dirDeps...)
1048
1049 resArgs = append(resArgs, fileArgs...)
1050 resDeps = append(resDeps, fileDeps...)
1051
1052 resArgs = append(resArgs, extraArgs...)
1053 resDeps = append(resDeps, extraDeps...)
1054
1055 if len(resArgs) > 0 {
1056 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1057 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1058 j.resourceJar = resourceJar
1059 if ctx.Failed() {
1060 return
1061 }
1062 }
1063
1064 var resourceJars android.Paths
1065 if j.resourceJar != nil {
1066 resourceJars = append(resourceJars, j.resourceJar)
1067 }
1068 if Bool(j.properties.Include_srcs) {
1069 resourceJars = append(resourceJars, includeSrcJar)
1070 }
1071 resourceJars = append(resourceJars, deps.staticResourceJars...)
1072
1073 if len(resourceJars) > 1 {
1074 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1075 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1076 false, nil, nil)
1077 j.resourceJar = combinedJar
1078 } else if len(resourceJars) == 1 {
1079 j.resourceJar = resourceJars[0]
1080 }
1081
1082 if len(deps.staticJars) > 0 {
1083 jars = append(jars, deps.staticJars...)
1084 }
1085
1086 manifest := j.overrideManifest
1087 if !manifest.Valid() && j.properties.Manifest != nil {
1088 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1089 }
1090
1091 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1092 if len(services) > 0 {
1093 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1094 var zipargs []string
1095 for _, file := range services {
1096 serviceFile := file.String()
1097 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1098 }
1099 rule := zip
1100 args := map[string]string{
1101 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1102 }
1103 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1104 rule = zipRE
1105 args["implicits"] = strings.Join(services.Strings(), ",")
1106 }
1107 ctx.Build(pctx, android.BuildParams{
1108 Rule: rule,
1109 Output: servicesJar,
1110 Implicits: services,
1111 Args: args,
1112 })
1113 jars = append(jars, servicesJar)
1114 }
1115
1116 // Combine the classes built from sources, any manifests, and any static libraries into
1117 // classes.jar. If there is only one input jar this step will be skipped.
1118 var outputFile android.OutputPath
1119
1120 if len(jars) == 1 && !manifest.Valid() {
1121 // Optimization: skip the combine step as there is nothing to do
1122 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1123 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1124 // any if len(jars) == 1.
1125
1126 // Transform the single path to the jar into an OutputPath as that is required by the following
1127 // code.
1128 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1129 // The path contains an embedded OutputPath so reuse that.
1130 outputFile = moduleOutPath.OutputPath
1131 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1132 // The path is an OutputPath so reuse it directly.
1133 outputFile = outputPath
1134 } else {
1135 // The file is not in the out directory so create an OutputPath into which it can be copied
1136 // and which the following code can use to refer to it.
1137 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1138 ctx.Build(pctx, android.BuildParams{
1139 Rule: android.Cp,
1140 Input: jars[0],
1141 Output: combinedJar,
1142 })
1143 outputFile = combinedJar.OutputPath
1144 }
1145 } else {
1146 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1147 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1148 false, nil, nil)
1149 outputFile = combinedJar.OutputPath
1150 }
1151
1152 // jarjar implementation jar if necessary
1153 if j.expandJarjarRules != nil {
1154 // Transform classes.jar into classes-jarjar.jar
1155 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1156 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1157 outputFile = jarjarFile
1158
1159 // jarjar resource jar if necessary
1160 if j.resourceJar != nil {
1161 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1162 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1163 j.resourceJar = resourceJarJarFile
1164 }
1165
1166 if ctx.Failed() {
1167 return
1168 }
1169 }
1170
1171 // Check package restrictions if necessary.
1172 if len(j.properties.Permitted_packages) > 0 {
1173 // Check packages and copy to package-checked file.
1174 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1175 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1176 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1177
1178 if ctx.Failed() {
1179 return
1180 }
1181 }
1182
1183 j.implementationJarFile = outputFile
1184 if j.headerJarFile == nil {
1185 j.headerJarFile = j.implementationJarFile
1186 }
1187
1188 if j.shouldInstrumentInApex(ctx) {
1189 j.properties.Instrument = true
1190 }
1191
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001192 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1193 specs := j.jacocoModuleToZipCommand(ctx)
1194 if ctx.Failed() {
1195 return
1196 }
1197
Jaewoong Jung26342642021-03-17 15:56:23 -07001198 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001199 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001200 }
1201
1202 // merge implementation jar with resources if necessary
1203 implementationAndResourcesJar := outputFile
1204 if j.resourceJar != nil {
1205 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1206 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1207 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1208 false, nil, nil)
1209 implementationAndResourcesJar = combinedJar
1210 }
1211
1212 j.implementationAndResourcesJar = implementationAndResourcesJar
1213
1214 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1215 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1216 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1217 if j.dexProperties.Compile_dex == nil {
1218 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1219 }
1220 if j.deviceProperties.Hostdex == nil {
1221 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1222 }
1223 }
1224
1225 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1226 if j.hasCode(ctx) {
1227 if j.shouldInstrumentStatic(ctx) {
1228 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1229 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1230 }
1231 // Dex compilation
1232 var dexOutputFile android.OutputPath
Jiyong Park92315372021-04-02 08:45:46 +09001233 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), outputFile, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001234 if ctx.Failed() {
1235 return
1236 }
1237
Jaewoong Jung26342642021-03-17 15:56:23 -07001238 // merge dex jar with resources if necessary
1239 if j.resourceJar != nil {
1240 jars := android.Paths{dexOutputFile, j.resourceJar}
1241 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1242 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1243 false, nil, nil)
1244 if *j.dexProperties.Uncompress_dex {
1245 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1246 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1247 dexOutputFile = combinedAlignedJar
1248 } else {
1249 dexOutputFile = combinedJar
1250 }
1251 }
1252
Paul Duffin4de94502021-05-16 05:21:16 +01001253 // Initialize the hiddenapi structure.
1254 j.initHiddenAPI(ctx, dexOutputFile, j.implementationJarFile, j.dexProperties.Uncompress_dex)
1255
1256 // Encode hidden API flags in dex file, if needed.
1257 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1258
Jaewoong Jung26342642021-03-17 15:56:23 -07001259 j.dexJarFile = dexOutputFile
1260
1261 // Dexpreopting
1262 j.dexpreopt(ctx, dexOutputFile)
1263
1264 outputFile = dexOutputFile
1265 } else {
1266 // There is no code to compile into a dex jar, make sure the resources are propagated
1267 // to the APK if this is an app.
1268 outputFile = implementationAndResourcesJar
1269 j.dexJarFile = j.resourceJar
1270 }
1271
1272 if ctx.Failed() {
1273 return
1274 }
1275 } else {
1276 outputFile = implementationAndResourcesJar
1277 }
1278
1279 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001280 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001281 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001282 return v.String()
1283 } else {
1284 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1285 }
1286 }
1287
1288 j.linter.name = ctx.ModuleName()
1289 j.linter.srcs = srcFiles
1290 j.linter.srcJars = srcJars
1291 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1292 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001293 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1294 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1295 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001296 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001297 j.linter.javaLanguageLevel = flags.javaVersion.String()
1298 j.linter.kotlinLanguageLevel = "1.3"
1299 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1300 j.linter.buildModuleReportZip = true
1301 }
1302 j.linter.lint(ctx)
1303 }
1304
1305 ctx.CheckbuildFile(outputFile)
1306
1307 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1308 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1309 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1310 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1311 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1312 AidlIncludeDirs: j.exportAidlIncludeDirs,
1313 SrcJarArgs: j.srcJarArgs,
1314 SrcJarDeps: j.srcJarDeps,
1315 ExportedPlugins: j.exportedPluginJars,
1316 ExportedPluginClasses: j.exportedPluginClasses,
1317 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1318 JacocoReportClassesFile: j.jacocoReportClassesFile,
1319 })
1320
1321 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1322 j.outputFile = outputFile.WithoutRel()
1323}
1324
Cole Faust75fffb12021-06-13 15:23:16 -07001325// Returns a copy of the supplied flags, but with all the errorprone-related
1326// fields copied to the regular build's fields.
1327func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1328 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1329
1330 if len(flags.errorProneExtraJavacFlags) > 0 {
1331 if len(flags.javacFlags) > 0 {
1332 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1333 } else {
1334 flags.javacFlags = flags.errorProneExtraJavacFlags
1335 }
1336 }
1337 return flags
1338}
1339
Jaewoong Jung26342642021-03-17 15:56:23 -07001340func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1341 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1342
1343 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1344 if idx >= 0 {
1345 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1346 jarName += strconv.Itoa(idx)
1347 }
1348
1349 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1350 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1351
1352 if ctx.Config().EmitXrefRules() {
1353 extractionFile := android.PathForModuleOut(ctx, kzipName)
1354 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1355 j.kytheFiles = append(j.kytheFiles, extractionFile)
1356 }
1357
1358 return classes
1359}
1360
1361// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1362// since some of these flags may be used internally.
1363func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1364 for _, flag := range flags {
1365 flag = strings.TrimSpace(flag)
1366
1367 if !strings.HasPrefix(flag, "-") {
1368 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1369 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1370 ctx.PropertyErrorf("kotlincflags",
1371 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1372 } else if inList(flag, config.KotlincIllegalFlags) {
1373 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1374 } else if flag == "-include-runtime" {
1375 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1376 } else {
1377 args := strings.Split(flag, " ")
1378 if args[0] == "-kotlin-home" {
1379 ctx.PropertyErrorf("kotlincflags",
1380 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1381 }
1382 }
1383 }
1384}
1385
1386func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1387 deps deps, flags javaBuilderFlags, jarName string,
1388 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1389
1390 var jars android.Paths
1391 if len(srcFiles) > 0 || len(srcJars) > 0 {
1392 // Compile java sources into turbine.jar.
1393 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1394 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1395 if ctx.Failed() {
1396 return nil, nil
1397 }
1398 jars = append(jars, turbineJar)
1399 }
1400
1401 jars = append(jars, extraJars...)
1402
1403 // Combine any static header libraries into classes-header.jar. If there is only
1404 // one input jar this step will be skipped.
1405 jars = append(jars, deps.staticHeaderJars...)
1406
1407 // we cannot skip the combine step for now if there is only one jar
1408 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1409 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1410 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1411 false, nil, []string{"META-INF/TRANSITIVE"})
1412 headerJar = combinedJar
1413 jarjarHeaderJar = combinedJar
1414
1415 if j.expandJarjarRules != nil {
1416 // Transform classes.jar into classes-jarjar.jar
1417 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1418 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1419 jarjarHeaderJar = jarjarFile
1420 if ctx.Failed() {
1421 return nil, nil
1422 }
1423 }
1424
1425 return headerJar, jarjarHeaderJar
1426}
1427
1428func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001429 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001430
1431 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1432 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1433
1434 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1435
1436 j.jacocoReportClassesFile = jacocoReportClassesFile
1437
1438 return instrumentedJar
1439}
1440
1441func (j *Module) HeaderJars() android.Paths {
1442 if j.headerJarFile == nil {
1443 return nil
1444 }
1445 return android.Paths{j.headerJarFile}
1446}
1447
1448func (j *Module) ImplementationJars() android.Paths {
1449 if j.implementationJarFile == nil {
1450 return nil
1451 }
1452 return android.Paths{j.implementationJarFile}
1453}
1454
1455func (j *Module) DexJarBuildPath() android.Path {
1456 return j.dexJarFile
1457}
1458
1459func (j *Module) DexJarInstallPath() android.Path {
1460 return j.installFile
1461}
1462
1463func (j *Module) ImplementationAndResourcesJars() android.Paths {
1464 if j.implementationAndResourcesJar == nil {
1465 return nil
1466 }
1467 return android.Paths{j.implementationAndResourcesJar}
1468}
1469
1470func (j *Module) AidlIncludeDirs() android.Paths {
1471 // exportAidlIncludeDirs is type android.Paths already
1472 return j.exportAidlIncludeDirs
1473}
1474
1475func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1476 return j.classLoaderContexts
1477}
1478
1479// Collect information for opening IDE project files in java/jdeps.go.
1480func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1481 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1482 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1483 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1484 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1485 if j.expandJarjarRules != nil {
1486 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1487 }
1488 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1489}
1490
1491func (j *Module) CompilerDeps() []string {
1492 jdeps := []string{}
1493 jdeps = append(jdeps, j.properties.Libs...)
1494 jdeps = append(jdeps, j.properties.Static_libs...)
1495 return jdeps
1496}
1497
1498func (j *Module) hasCode(ctx android.ModuleContext) bool {
1499 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1500 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1501}
1502
1503// Implements android.ApexModule
1504func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1505 return j.depIsInSameApex(ctx, dep)
1506}
1507
1508// Implements android.ApexModule
1509func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1510 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001511 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001512 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001513 return fmt.Errorf("min_sdk_version is not specified")
1514 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001515 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001516 return nil
1517 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001518 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1519 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001520 }
1521 return nil
1522}
1523
1524func (j *Module) Stem() string {
1525 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1526}
1527
Jaewoong Jung26342642021-03-17 15:56:23 -07001528func (j *Module) JacocoReportClassesFile() android.Path {
1529 return j.jacocoReportClassesFile
1530}
1531
1532func (j *Module) IsInstallable() bool {
1533 return Bool(j.properties.Installable)
1534}
1535
1536type sdkLinkType int
1537
1538const (
1539 // TODO(jiyong) rename these for better readability. Make the allowed
1540 // and disallowed link types explicit
1541 // order is important here. See rank()
1542 javaCore sdkLinkType = iota
1543 javaSdk
1544 javaSystem
1545 javaModule
1546 javaSystemServer
1547 javaPlatform
1548)
1549
1550func (lt sdkLinkType) String() string {
1551 switch lt {
1552 case javaCore:
1553 return "core Java API"
1554 case javaSdk:
1555 return "Android API"
1556 case javaSystem:
1557 return "system API"
1558 case javaModule:
1559 return "module API"
1560 case javaSystemServer:
1561 return "system server API"
1562 case javaPlatform:
1563 return "private API"
1564 default:
1565 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1566 }
1567}
1568
1569// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1570// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1571// can't statically depend on modules that use Platform API.
1572func (lt sdkLinkType) rank() int {
1573 return int(lt)
1574}
1575
1576type moduleWithSdkDep interface {
1577 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001578 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001579}
1580
Jiyong Park92315372021-04-02 08:45:46 +09001581func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001582 switch name {
1583 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1584 "stub-annotations", "private-stub-annotations-jar",
1585 "core-lambda-stubs", "core-generated-annotation-stubs":
1586 return javaCore, true
1587 case "android_stubs_current":
1588 return javaSdk, true
1589 case "android_system_stubs_current":
1590 return javaSystem, true
1591 case "android_module_lib_stubs_current":
1592 return javaModule, true
1593 case "android_system_server_stubs_current":
1594 return javaSystemServer, true
1595 case "android_test_stubs_current":
1596 return javaSystem, true
1597 }
1598
1599 if stub, linkType := moduleStubLinkType(name); stub {
1600 return linkType, true
1601 }
1602
Jiyong Park92315372021-04-02 08:45:46 +09001603 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001604 switch ver.Kind {
1605 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001606 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001607 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001608 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001609 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001610 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001611 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001612 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001613 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001614 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001615 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001616 return javaPlatform, false
1617 }
1618
Jiyong Parkf1691d22021-03-29 20:11:58 +09001619 if !ver.Valid() {
1620 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001621 }
1622 return javaSdk, false
1623}
1624
1625// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1626// this module's. See the comment on rank() for details and an example.
1627func (j *Module) checkSdkLinkType(
1628 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1629 if ctx.Host() {
1630 return
1631 }
1632
Jiyong Park92315372021-04-02 08:45:46 +09001633 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001634 if stubs {
1635 return
1636 }
Jiyong Park92315372021-04-02 08:45:46 +09001637 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001638
1639 if myLinkType.rank() < depLinkType.rank() {
1640 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1641 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1642 "property of the source or target module so that target module is built "+
1643 "with the same or smaller API set when compared to the source.",
1644 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1645 }
1646}
1647
1648func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1649 var deps deps
1650
1651 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001652 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001653 if sdkDep.invalidVersion {
1654 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1655 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1656 } else if sdkDep.useFiles {
1657 // sdkDep.jar is actually equivalent to turbine header.jar.
1658 deps.classpath = append(deps.classpath, sdkDep.jars...)
1659 deps.aidlPreprocess = sdkDep.aidl
1660 } else {
1661 deps.aidlPreprocess = sdkDep.aidl
1662 }
1663 }
1664
Jiyong Park92315372021-04-02 08:45:46 +09001665 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001666
1667 ctx.VisitDirectDeps(func(module android.Module) {
1668 otherName := ctx.OtherModuleName(module)
1669 tag := ctx.OtherModuleDependencyTag(module)
1670
1671 if IsJniDepTag(tag) {
1672 // Handled by AndroidApp.collectAppDeps
1673 return
1674 }
1675 if tag == certificateTag {
1676 // Handled by AndroidApp.collectAppDeps
1677 return
1678 }
1679
1680 if dep, ok := module.(SdkLibraryDependency); ok {
1681 switch tag {
1682 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001683 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001684 case staticLibTag:
1685 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1686 }
1687 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1688 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1689 if sdkLinkType != javaPlatform &&
1690 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1691 // dep is a sysprop implementation library, but this module is not linking against
1692 // the platform, so it gets the sysprop public stubs library instead. Replace
1693 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1694 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1695 dep = syspropDep.JavaInfo
1696 }
1697 switch tag {
1698 case bootClasspathTag:
1699 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1700 case libTag, instrumentationForTag:
1701 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1702 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1703 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1704 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1705 case java9LibTag:
1706 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1707 case staticLibTag:
1708 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1709 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1710 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1711 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1712 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1713 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1714 // Turbine doesn't run annotation processors, so any module that uses an
1715 // annotation processor that generates API is incompatible with the turbine
1716 // optimization.
1717 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1718 case pluginTag:
1719 if plugin, ok := module.(*Plugin); ok {
1720 if plugin.pluginProperties.Processor_class != nil {
1721 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1722 } else {
1723 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1724 }
1725 // Turbine doesn't run annotation processors, so any module that uses an
1726 // annotation processor that generates API is incompatible with the turbine
1727 // optimization.
1728 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1729 } else {
1730 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1731 }
1732 case errorpronePluginTag:
1733 if _, ok := module.(*Plugin); ok {
1734 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1735 } else {
1736 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1737 }
1738 case exportedPluginTag:
1739 if plugin, ok := module.(*Plugin); ok {
1740 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1741 if plugin.pluginProperties.Processor_class != nil {
1742 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1743 }
1744 // Turbine doesn't run annotation processors, so any module that uses an
1745 // annotation processor that generates API is incompatible with the turbine
1746 // optimization.
1747 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1748 } else {
1749 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1750 }
1751 case kotlinStdlibTag:
1752 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1753 case kotlinAnnotationsTag:
1754 deps.kotlinAnnotations = dep.HeaderJars
1755 case syspropPublicStubDepTag:
1756 // This is a sysprop implementation library, forward the JavaInfoProvider from
1757 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1758 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1759 JavaInfo: dep,
1760 })
1761 }
1762 } else if dep, ok := module.(android.SourceFileProducer); ok {
1763 switch tag {
1764 case libTag:
1765 checkProducesJars(ctx, dep)
1766 deps.classpath = append(deps.classpath, dep.Srcs()...)
1767 case staticLibTag:
1768 checkProducesJars(ctx, dep)
1769 deps.classpath = append(deps.classpath, dep.Srcs()...)
1770 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1771 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1772 }
1773 } else {
1774 switch tag {
1775 case bootClasspathTag:
1776 // If a system modules dependency has been added to the bootclasspath
1777 // then add its libs to the bootclasspath.
1778 sm := module.(SystemModulesProvider)
1779 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1780
1781 case systemModulesTag:
1782 if deps.systemModules != nil {
1783 panic("Found two system module dependencies")
1784 }
1785 sm := module.(SystemModulesProvider)
1786 outputDir, outputDeps := sm.OutputDirAndDeps()
1787 deps.systemModules = &systemModules{outputDir, outputDeps}
1788 }
1789 }
1790
1791 addCLCFromDep(ctx, module, j.classLoaderContexts)
1792 })
1793
1794 return deps
1795}
1796
1797func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1798 deps.processorPath = append(deps.processorPath, pluginJars...)
1799 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1800}
1801
1802// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1803// this interface.
1804type ProvidesUsesLib interface {
1805 ProvidesUsesLib() *string
1806}
1807
1808func (j *Module) ProvidesUsesLib() *string {
1809 return j.usesLibraryProperties.Provides_uses_lib
1810}
satayev1c564cc2021-05-25 19:50:30 +01001811
1812type ModuleWithStem interface {
1813 Stem() string
1814}
1815
1816var _ ModuleWithStem = (*Module)(nil)