blob: ea5b1372127902187d9672825f376950fc1df565 [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 {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100608 // Add library as optional if it's one of the optional compatibility libs.
609 tag := usesLibReqTag
610 if android.InList(*lib, dexpreopt.OptionalCompatUsesLibs) {
611 tag = usesLibOptTag
612 }
613 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700614 }
615 }
616 }
617 }
618
619 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
620 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
621 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
622
623 android.ProtoDeps(ctx, &j.protoProperties)
624 if j.hasSrcExt(".proto") {
625 protoDeps(ctx, &j.protoProperties)
626 }
627
628 if j.hasSrcExt(".kt") {
629 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
630 // Kotlin files
631 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
632 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
633 if len(j.properties.Plugins) > 0 {
634 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
635 }
636 }
637
638 // Framework libraries need special handling in static coverage builds: they should not have
639 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
640 // the same jacoco classes coming from different bootclasspath jars.
641 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
642 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
643 j.properties.Instrument = true
644 }
645 } else if j.shouldInstrumentStatic(ctx) {
646 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
647 }
648}
649
650func hasSrcExt(srcs []string, ext string) bool {
651 for _, src := range srcs {
652 if filepath.Ext(src) == ext {
653 return true
654 }
655 }
656
657 return false
658}
659
660func (j *Module) hasSrcExt(ext string) bool {
661 return hasSrcExt(j.properties.Srcs, ext)
662}
663
664func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
665 aidlIncludeDirs android.Paths) (string, android.Paths) {
666
667 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
668 aidlIncludes = append(aidlIncludes,
669 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
670 aidlIncludes = append(aidlIncludes,
671 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
672
673 var flags []string
674 var deps android.Paths
675
676 flags = append(flags, j.deviceProperties.Aidl.Flags...)
677
678 if aidlPreprocess.Valid() {
679 flags = append(flags, "-p"+aidlPreprocess.String())
680 deps = append(deps, aidlPreprocess.Path())
681 } else if len(aidlIncludeDirs) > 0 {
682 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
683 }
684
685 if len(j.exportAidlIncludeDirs) > 0 {
686 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
687 }
688
689 if len(aidlIncludes) > 0 {
690 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
691 }
692
693 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
694 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
695 flags = append(flags, "-I"+src.String())
696 }
697
698 if Bool(j.deviceProperties.Aidl.Generate_traces) {
699 flags = append(flags, "-t")
700 }
701
702 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
703 flags = append(flags, "--transaction_names")
704 }
705
706 return strings.Join(flags, " "), deps
707}
708
709func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
710
711 var flags javaBuilderFlags
712
713 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900714 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700715
Cole Faust2b1536e2021-06-18 12:25:54 -0700716 epEnabled := j.properties.Errorprone.Enabled
717 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700718 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
719 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
720 }
721
722 errorProneFlags := []string{
723 "-Xplugin:ErrorProne",
724 "${config.ErrorProneChecks}",
725 }
726 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
727
728 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
729 "'" + strings.Join(errorProneFlags, " ") + "'"
730 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
731 }
732
733 // classpath
734 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
735 flags.classpath = append(flags.classpath, deps.classpath...)
736 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
737 flags.processorPath = append(flags.processorPath, deps.processorPath...)
738 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
739
740 flags.processors = append(flags.processors, deps.processorClasses...)
741 flags.processors = android.FirstUniqueStrings(flags.processors)
742
743 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900744 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700745 // Give host-side tools a version of OpenJDK's standard libraries
746 // close to what they're targeting. As of Dec 2017, AOSP is only
747 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
748 //
749 // When building with OpenJDK 8, the following should have no
750 // effect since those jars would be available by default.
751 //
752 // When building with OpenJDK 9 but targeting a version < 1.8,
753 // putting them on the bootclasspath means that:
754 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
755 // b) references to existing APIs are not reinterpreted in an
756 // OpenJDK 9-specific way, eg. calls to subclasses of
757 // java.nio.Buffer as in http://b/70862583
758 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
759 flags.bootClasspath = append(flags.bootClasspath,
760 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
761 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
762 if Bool(j.properties.Use_tools_jar) {
763 flags.bootClasspath = append(flags.bootClasspath,
764 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
765 }
766 }
767
768 // systemModules
769 flags.systemModules = deps.systemModules
770
771 // aidl flags.
772 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
773
774 return flags
775}
776
777func (j *Module) collectJavacFlags(
778 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
779 // javac flags.
780 javacFlags := j.properties.Javacflags
781
782 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
783 // For non-host binaries, override the -g flag passed globally to remove
784 // local variable debug info to reduce disk and memory usage.
785 javacFlags = append(javacFlags, "-g:source,lines")
786 }
787 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
788
789 if flags.javaVersion.usesJavaModules() {
790 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
791
792 if j.properties.Patch_module != nil {
793 // Manually specify build directory in case it is not under the repo root.
794 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
795 // just adding a symlink under the root doesn't help.)
796 patchPaths := []string{".", ctx.Config().BuildDir()}
797
798 // b/150878007
799 //
800 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
801 // execution root for --patch-module. If this javac command line is
802 // invoked within Bazel's execution root working directory, the top
803 // level directories (e.g. libcore/, tools/, frameworks/) are all
804 // symlinks. JDK9 javac does not traverse into symlinks, which causes
805 // --patch-module to fail source file lookups when invoked in the
806 // execution root.
807 //
808 // Short of patching javac or enumerating *all* directories as possible
809 // input dirs, manually add the top level dir of the source files to be
810 // compiled.
811 topLevelDirs := map[string]bool{}
812 for _, srcFilePath := range srcFiles {
813 srcFileParts := strings.Split(srcFilePath.String(), "/")
814 // Ignore source files that are already in the top level directory
815 // as well as generated files in the out directory. The out
816 // directory may be an absolute path, which means srcFileParts[0] is the
817 // empty string, so check that as well. Note that "out" in Bazel's execution
818 // root is *not* a symlink, which doesn't cause problems for --patch-modules
819 // anyway, so it's fine to not apply this workaround for generated
820 // source files.
821 if len(srcFileParts) > 1 &&
822 srcFileParts[0] != "" &&
823 srcFileParts[0] != "out" {
824 topLevelDirs[srcFileParts[0]] = true
825 }
826 }
827 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
828
829 classPath := flags.classpath.FormJavaClassPath("")
830 if classPath != "" {
831 patchPaths = append(patchPaths, classPath)
832 }
833 javacFlags = append(
834 javacFlags,
835 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
836 }
837 }
838
839 if len(javacFlags) > 0 {
840 // optimization.
841 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
842 flags.javacFlags = "$javacFlags"
843 }
844
845 return flags
846}
847
848func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
849 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
850
851 deps := j.collectDeps(ctx)
852 flags := j.collectBuilderFlags(ctx, deps)
853
854 if flags.javaVersion.usesJavaModules() {
855 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
856 }
857 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
858 if hasSrcExt(srcFiles.Strings(), ".proto") {
859 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
860 }
861
862 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
863 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
864 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
865 }
866
867 srcFiles = j.genSources(ctx, srcFiles, flags)
868
869 // Collect javac flags only after computing the full set of srcFiles to
870 // ensure that the --patch-module lookup paths are complete.
871 flags = j.collectJavacFlags(ctx, flags, srcFiles)
872
873 srcJars := srcFiles.FilterByExt(".srcjar")
874 srcJars = append(srcJars, deps.srcJars...)
875 if aaptSrcJar != nil {
876 srcJars = append(srcJars, aaptSrcJar)
877 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700878 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700879
880 if j.properties.Jarjar_rules != nil {
881 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
882 }
883
884 jarName := ctx.ModuleName() + ".jar"
885
886 javaSrcFiles := srcFiles.FilterByExt(".java")
887 var uniqueSrcFiles android.Paths
888 set := make(map[string]bool)
889 for _, v := range javaSrcFiles {
890 if _, found := set[v.String()]; !found {
891 set[v.String()] = true
892 uniqueSrcFiles = append(uniqueSrcFiles, v)
893 }
894 }
895
896 // Collect .java files for AIDEGen
897 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
898
899 var kotlinJars android.Paths
900
901 if srcFiles.HasExt(".kt") {
902 // user defined kotlin flags.
903 kotlincFlags := j.properties.Kotlincflags
904 CheckKotlincFlags(ctx, kotlincFlags)
905
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000906 // Workaround for KT-46512
907 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700908
909 // If there are kotlin files, compile them first but pass all the kotlin and java files
910 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
911 // won't emit any classes for them.
912 kotlincFlags = append(kotlincFlags, "-no-stdlib")
913 if ctx.Device() {
914 kotlincFlags = append(kotlincFlags, "-no-jdk")
915 }
916 if len(kotlincFlags) > 0 {
917 // optimization.
918 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
919 flags.kotlincFlags += "$kotlincFlags"
920 }
921
922 var kotlinSrcFiles android.Paths
923 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
924 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
925
926 // Collect .kt files for AIDEGen
927 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
928 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
929
930 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
931 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
932
933 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
934 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
935
936 if len(flags.processorPath) > 0 {
937 // Use kapt for annotation processing
938 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
939 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
940 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
941 srcJars = append(srcJars, kaptSrcJar)
942 kotlinJars = append(kotlinJars, kaptResJar)
943 // Disable annotation processing in javac, it's already been handled by kapt
944 flags.processorPath = nil
945 flags.processors = nil
946 }
947
948 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
949 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
950 if ctx.Failed() {
951 return
952 }
953
954 // Make javac rule depend on the kotlinc rule
955 flags.classpath = append(flags.classpath, kotlinJar)
956
957 kotlinJars = append(kotlinJars, kotlinJar)
958 // Jar kotlin classes into the final jar after javac
959 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
960 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
961 }
962 }
963
964 jars := append(android.Paths(nil), kotlinJars...)
965
966 // Store the list of .java files that was passed to javac
967 j.compiledJavaSrcs = uniqueSrcFiles
968 j.compiledSrcJars = srcJars
969
970 enableSharding := false
971 var headerJarFileWithoutJarjar android.Path
972 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
973 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
974 enableSharding = true
975 // Formerly, there was a check here that prevented annotation processors
976 // from being used when sharding was enabled, as some annotation processors
977 // do not function correctly in sharded environments. It was removed to
978 // allow for the use of annotation processors that do function correctly
979 // with sharding enabled. See: b/77284273.
980 }
981 headerJarFileWithoutJarjar, j.headerJarFile =
982 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
983 if ctx.Failed() {
984 return
985 }
986 }
987 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
988 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -0700989 if Bool(j.properties.Errorprone.Enabled) {
990 // If error-prone is enabled, enable errorprone flags on the regular
991 // build.
992 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -0700993 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -0700994 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
995 // a new jar file just for compiling with the errorprone compiler to.
996 // This is because we don't want to cause the java files to get completely
997 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
998 // We also don't want to run this if errorprone is enabled by default for
999 // this module, or else we could have duplicated errorprone messages.
1000 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001001 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001002
1003 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1004 "errorprone", "errorprone")
1005
Jaewoong Jung26342642021-03-17 15:56:23 -07001006 extraJarDeps = append(extraJarDeps, errorprone)
1007 }
1008
1009 if enableSharding {
1010 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
1011 shardSize := int(*(j.properties.Javac_shard_size))
1012 var shardSrcs []android.Paths
1013 if len(uniqueSrcFiles) > 0 {
1014 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1015 for idx, shardSrc := range shardSrcs {
1016 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1017 nil, flags, extraJarDeps)
1018 jars = append(jars, classes)
1019 }
1020 }
1021 if len(srcJars) > 0 {
1022 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1023 nil, srcJars, flags, extraJarDeps)
1024 jars = append(jars, classes)
1025 }
1026 } else {
1027 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1028 jars = append(jars, classes)
1029 }
1030 if ctx.Failed() {
1031 return
1032 }
1033 }
1034
1035 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1036
1037 var includeSrcJar android.WritablePath
1038 if Bool(j.properties.Include_srcs) {
1039 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1040 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1041 }
1042
1043 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1044 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1045 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1046 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1047
1048 var resArgs []string
1049 var resDeps android.Paths
1050
1051 resArgs = append(resArgs, dirArgs...)
1052 resDeps = append(resDeps, dirDeps...)
1053
1054 resArgs = append(resArgs, fileArgs...)
1055 resDeps = append(resDeps, fileDeps...)
1056
1057 resArgs = append(resArgs, extraArgs...)
1058 resDeps = append(resDeps, extraDeps...)
1059
1060 if len(resArgs) > 0 {
1061 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1062 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1063 j.resourceJar = resourceJar
1064 if ctx.Failed() {
1065 return
1066 }
1067 }
1068
1069 var resourceJars android.Paths
1070 if j.resourceJar != nil {
1071 resourceJars = append(resourceJars, j.resourceJar)
1072 }
1073 if Bool(j.properties.Include_srcs) {
1074 resourceJars = append(resourceJars, includeSrcJar)
1075 }
1076 resourceJars = append(resourceJars, deps.staticResourceJars...)
1077
1078 if len(resourceJars) > 1 {
1079 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1080 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1081 false, nil, nil)
1082 j.resourceJar = combinedJar
1083 } else if len(resourceJars) == 1 {
1084 j.resourceJar = resourceJars[0]
1085 }
1086
1087 if len(deps.staticJars) > 0 {
1088 jars = append(jars, deps.staticJars...)
1089 }
1090
1091 manifest := j.overrideManifest
1092 if !manifest.Valid() && j.properties.Manifest != nil {
1093 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1094 }
1095
1096 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1097 if len(services) > 0 {
1098 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1099 var zipargs []string
1100 for _, file := range services {
1101 serviceFile := file.String()
1102 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1103 }
1104 rule := zip
1105 args := map[string]string{
1106 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1107 }
1108 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1109 rule = zipRE
1110 args["implicits"] = strings.Join(services.Strings(), ",")
1111 }
1112 ctx.Build(pctx, android.BuildParams{
1113 Rule: rule,
1114 Output: servicesJar,
1115 Implicits: services,
1116 Args: args,
1117 })
1118 jars = append(jars, servicesJar)
1119 }
1120
1121 // Combine the classes built from sources, any manifests, and any static libraries into
1122 // classes.jar. If there is only one input jar this step will be skipped.
1123 var outputFile android.OutputPath
1124
1125 if len(jars) == 1 && !manifest.Valid() {
1126 // Optimization: skip the combine step as there is nothing to do
1127 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1128 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1129 // any if len(jars) == 1.
1130
1131 // Transform the single path to the jar into an OutputPath as that is required by the following
1132 // code.
1133 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1134 // The path contains an embedded OutputPath so reuse that.
1135 outputFile = moduleOutPath.OutputPath
1136 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1137 // The path is an OutputPath so reuse it directly.
1138 outputFile = outputPath
1139 } else {
1140 // The file is not in the out directory so create an OutputPath into which it can be copied
1141 // and which the following code can use to refer to it.
1142 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1143 ctx.Build(pctx, android.BuildParams{
1144 Rule: android.Cp,
1145 Input: jars[0],
1146 Output: combinedJar,
1147 })
1148 outputFile = combinedJar.OutputPath
1149 }
1150 } else {
1151 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1152 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1153 false, nil, nil)
1154 outputFile = combinedJar.OutputPath
1155 }
1156
1157 // jarjar implementation jar if necessary
1158 if j.expandJarjarRules != nil {
1159 // Transform classes.jar into classes-jarjar.jar
1160 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1161 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1162 outputFile = jarjarFile
1163
1164 // jarjar resource jar if necessary
1165 if j.resourceJar != nil {
1166 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1167 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1168 j.resourceJar = resourceJarJarFile
1169 }
1170
1171 if ctx.Failed() {
1172 return
1173 }
1174 }
1175
1176 // Check package restrictions if necessary.
1177 if len(j.properties.Permitted_packages) > 0 {
1178 // Check packages and copy to package-checked file.
1179 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1180 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1181 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1182
1183 if ctx.Failed() {
1184 return
1185 }
1186 }
1187
1188 j.implementationJarFile = outputFile
1189 if j.headerJarFile == nil {
1190 j.headerJarFile = j.implementationJarFile
1191 }
1192
1193 if j.shouldInstrumentInApex(ctx) {
1194 j.properties.Instrument = true
1195 }
1196
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001197 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1198 specs := j.jacocoModuleToZipCommand(ctx)
1199 if ctx.Failed() {
1200 return
1201 }
1202
Jaewoong Jung26342642021-03-17 15:56:23 -07001203 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001204 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001205 }
1206
1207 // merge implementation jar with resources if necessary
1208 implementationAndResourcesJar := outputFile
1209 if j.resourceJar != nil {
1210 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1211 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1212 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1213 false, nil, nil)
1214 implementationAndResourcesJar = combinedJar
1215 }
1216
1217 j.implementationAndResourcesJar = implementationAndResourcesJar
1218
1219 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1220 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1221 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1222 if j.dexProperties.Compile_dex == nil {
1223 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1224 }
1225 if j.deviceProperties.Hostdex == nil {
1226 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1227 }
1228 }
1229
1230 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1231 if j.hasCode(ctx) {
1232 if j.shouldInstrumentStatic(ctx) {
1233 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1234 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1235 }
1236 // Dex compilation
1237 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001238 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001239 if ctx.Failed() {
1240 return
1241 }
1242
Jaewoong Jung26342642021-03-17 15:56:23 -07001243 // merge dex jar with resources if necessary
1244 if j.resourceJar != nil {
1245 jars := android.Paths{dexOutputFile, j.resourceJar}
1246 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1247 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1248 false, nil, nil)
1249 if *j.dexProperties.Uncompress_dex {
1250 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1251 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1252 dexOutputFile = combinedAlignedJar
1253 } else {
1254 dexOutputFile = combinedJar
1255 }
1256 }
1257
Paul Duffin4de94502021-05-16 05:21:16 +01001258 // Initialize the hiddenapi structure.
1259 j.initHiddenAPI(ctx, dexOutputFile, j.implementationJarFile, j.dexProperties.Uncompress_dex)
1260
1261 // Encode hidden API flags in dex file, if needed.
1262 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1263
Jaewoong Jung26342642021-03-17 15:56:23 -07001264 j.dexJarFile = dexOutputFile
1265
1266 // Dexpreopting
1267 j.dexpreopt(ctx, dexOutputFile)
1268
1269 outputFile = dexOutputFile
1270 } else {
1271 // There is no code to compile into a dex jar, make sure the resources are propagated
1272 // to the APK if this is an app.
1273 outputFile = implementationAndResourcesJar
1274 j.dexJarFile = j.resourceJar
1275 }
1276
1277 if ctx.Failed() {
1278 return
1279 }
1280 } else {
1281 outputFile = implementationAndResourcesJar
1282 }
1283
1284 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001285 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001286 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001287 return v.String()
1288 } else {
1289 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1290 }
1291 }
1292
1293 j.linter.name = ctx.ModuleName()
1294 j.linter.srcs = srcFiles
1295 j.linter.srcJars = srcJars
1296 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1297 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001298 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1299 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1300 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001301 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001302 j.linter.javaLanguageLevel = flags.javaVersion.String()
1303 j.linter.kotlinLanguageLevel = "1.3"
1304 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1305 j.linter.buildModuleReportZip = true
1306 }
1307 j.linter.lint(ctx)
1308 }
1309
1310 ctx.CheckbuildFile(outputFile)
1311
1312 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1313 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1314 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1315 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1316 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1317 AidlIncludeDirs: j.exportAidlIncludeDirs,
1318 SrcJarArgs: j.srcJarArgs,
1319 SrcJarDeps: j.srcJarDeps,
1320 ExportedPlugins: j.exportedPluginJars,
1321 ExportedPluginClasses: j.exportedPluginClasses,
1322 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1323 JacocoReportClassesFile: j.jacocoReportClassesFile,
1324 })
1325
1326 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1327 j.outputFile = outputFile.WithoutRel()
1328}
1329
Cole Faust75fffb12021-06-13 15:23:16 -07001330// Returns a copy of the supplied flags, but with all the errorprone-related
1331// fields copied to the regular build's fields.
1332func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1333 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1334
1335 if len(flags.errorProneExtraJavacFlags) > 0 {
1336 if len(flags.javacFlags) > 0 {
1337 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1338 } else {
1339 flags.javacFlags = flags.errorProneExtraJavacFlags
1340 }
1341 }
1342 return flags
1343}
1344
Jaewoong Jung26342642021-03-17 15:56:23 -07001345func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1346 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1347
1348 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1349 if idx >= 0 {
1350 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1351 jarName += strconv.Itoa(idx)
1352 }
1353
1354 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1355 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1356
1357 if ctx.Config().EmitXrefRules() {
1358 extractionFile := android.PathForModuleOut(ctx, kzipName)
1359 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1360 j.kytheFiles = append(j.kytheFiles, extractionFile)
1361 }
1362
1363 return classes
1364}
1365
1366// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1367// since some of these flags may be used internally.
1368func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1369 for _, flag := range flags {
1370 flag = strings.TrimSpace(flag)
1371
1372 if !strings.HasPrefix(flag, "-") {
1373 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1374 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1375 ctx.PropertyErrorf("kotlincflags",
1376 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1377 } else if inList(flag, config.KotlincIllegalFlags) {
1378 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1379 } else if flag == "-include-runtime" {
1380 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1381 } else {
1382 args := strings.Split(flag, " ")
1383 if args[0] == "-kotlin-home" {
1384 ctx.PropertyErrorf("kotlincflags",
1385 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1386 }
1387 }
1388 }
1389}
1390
1391func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1392 deps deps, flags javaBuilderFlags, jarName string,
1393 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1394
1395 var jars android.Paths
1396 if len(srcFiles) > 0 || len(srcJars) > 0 {
1397 // Compile java sources into turbine.jar.
1398 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1399 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1400 if ctx.Failed() {
1401 return nil, nil
1402 }
1403 jars = append(jars, turbineJar)
1404 }
1405
1406 jars = append(jars, extraJars...)
1407
1408 // Combine any static header libraries into classes-header.jar. If there is only
1409 // one input jar this step will be skipped.
1410 jars = append(jars, deps.staticHeaderJars...)
1411
1412 // we cannot skip the combine step for now if there is only one jar
1413 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1414 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1415 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1416 false, nil, []string{"META-INF/TRANSITIVE"})
1417 headerJar = combinedJar
1418 jarjarHeaderJar = combinedJar
1419
1420 if j.expandJarjarRules != nil {
1421 // Transform classes.jar into classes-jarjar.jar
1422 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1423 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1424 jarjarHeaderJar = jarjarFile
1425 if ctx.Failed() {
1426 return nil, nil
1427 }
1428 }
1429
1430 return headerJar, jarjarHeaderJar
1431}
1432
1433func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001434 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001435
1436 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1437 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1438
1439 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1440
1441 j.jacocoReportClassesFile = jacocoReportClassesFile
1442
1443 return instrumentedJar
1444}
1445
1446func (j *Module) HeaderJars() android.Paths {
1447 if j.headerJarFile == nil {
1448 return nil
1449 }
1450 return android.Paths{j.headerJarFile}
1451}
1452
1453func (j *Module) ImplementationJars() android.Paths {
1454 if j.implementationJarFile == nil {
1455 return nil
1456 }
1457 return android.Paths{j.implementationJarFile}
1458}
1459
1460func (j *Module) DexJarBuildPath() android.Path {
1461 return j.dexJarFile
1462}
1463
1464func (j *Module) DexJarInstallPath() android.Path {
1465 return j.installFile
1466}
1467
1468func (j *Module) ImplementationAndResourcesJars() android.Paths {
1469 if j.implementationAndResourcesJar == nil {
1470 return nil
1471 }
1472 return android.Paths{j.implementationAndResourcesJar}
1473}
1474
1475func (j *Module) AidlIncludeDirs() android.Paths {
1476 // exportAidlIncludeDirs is type android.Paths already
1477 return j.exportAidlIncludeDirs
1478}
1479
1480func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1481 return j.classLoaderContexts
1482}
1483
1484// Collect information for opening IDE project files in java/jdeps.go.
1485func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1486 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1487 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1488 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1489 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1490 if j.expandJarjarRules != nil {
1491 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1492 }
1493 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1494}
1495
1496func (j *Module) CompilerDeps() []string {
1497 jdeps := []string{}
1498 jdeps = append(jdeps, j.properties.Libs...)
1499 jdeps = append(jdeps, j.properties.Static_libs...)
1500 return jdeps
1501}
1502
1503func (j *Module) hasCode(ctx android.ModuleContext) bool {
1504 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1505 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1506}
1507
1508// Implements android.ApexModule
1509func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1510 return j.depIsInSameApex(ctx, dep)
1511}
1512
1513// Implements android.ApexModule
1514func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1515 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001516 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001517 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001518 return fmt.Errorf("min_sdk_version is not specified")
1519 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001520 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001521 return nil
1522 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001523 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1524 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001525 }
1526 return nil
1527}
1528
1529func (j *Module) Stem() string {
1530 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1531}
1532
Jaewoong Jung26342642021-03-17 15:56:23 -07001533func (j *Module) JacocoReportClassesFile() android.Path {
1534 return j.jacocoReportClassesFile
1535}
1536
1537func (j *Module) IsInstallable() bool {
1538 return Bool(j.properties.Installable)
1539}
1540
1541type sdkLinkType int
1542
1543const (
1544 // TODO(jiyong) rename these for better readability. Make the allowed
1545 // and disallowed link types explicit
1546 // order is important here. See rank()
1547 javaCore sdkLinkType = iota
1548 javaSdk
1549 javaSystem
1550 javaModule
1551 javaSystemServer
1552 javaPlatform
1553)
1554
1555func (lt sdkLinkType) String() string {
1556 switch lt {
1557 case javaCore:
1558 return "core Java API"
1559 case javaSdk:
1560 return "Android API"
1561 case javaSystem:
1562 return "system API"
1563 case javaModule:
1564 return "module API"
1565 case javaSystemServer:
1566 return "system server API"
1567 case javaPlatform:
1568 return "private API"
1569 default:
1570 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1571 }
1572}
1573
1574// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1575// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1576// can't statically depend on modules that use Platform API.
1577func (lt sdkLinkType) rank() int {
1578 return int(lt)
1579}
1580
1581type moduleWithSdkDep interface {
1582 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001583 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001584}
1585
Jiyong Park92315372021-04-02 08:45:46 +09001586func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001587 switch name {
1588 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1589 "stub-annotations", "private-stub-annotations-jar",
1590 "core-lambda-stubs", "core-generated-annotation-stubs":
1591 return javaCore, true
1592 case "android_stubs_current":
1593 return javaSdk, true
1594 case "android_system_stubs_current":
1595 return javaSystem, true
1596 case "android_module_lib_stubs_current":
1597 return javaModule, true
1598 case "android_system_server_stubs_current":
1599 return javaSystemServer, true
1600 case "android_test_stubs_current":
1601 return javaSystem, true
1602 }
1603
1604 if stub, linkType := moduleStubLinkType(name); stub {
1605 return linkType, true
1606 }
1607
Jiyong Park92315372021-04-02 08:45:46 +09001608 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001609 switch ver.Kind {
1610 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001611 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001612 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001613 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001614 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001615 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001616 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001617 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001618 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001619 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001620 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001621 return javaPlatform, false
1622 }
1623
Jiyong Parkf1691d22021-03-29 20:11:58 +09001624 if !ver.Valid() {
1625 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001626 }
1627 return javaSdk, false
1628}
1629
1630// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1631// this module's. See the comment on rank() for details and an example.
1632func (j *Module) checkSdkLinkType(
1633 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1634 if ctx.Host() {
1635 return
1636 }
1637
Jiyong Park92315372021-04-02 08:45:46 +09001638 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001639 if stubs {
1640 return
1641 }
Jiyong Park92315372021-04-02 08:45:46 +09001642 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001643
1644 if myLinkType.rank() < depLinkType.rank() {
1645 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1646 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1647 "property of the source or target module so that target module is built "+
1648 "with the same or smaller API set when compared to the source.",
1649 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1650 }
1651}
1652
1653func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1654 var deps deps
1655
1656 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001657 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001658 if sdkDep.invalidVersion {
1659 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1660 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1661 } else if sdkDep.useFiles {
1662 // sdkDep.jar is actually equivalent to turbine header.jar.
1663 deps.classpath = append(deps.classpath, sdkDep.jars...)
1664 deps.aidlPreprocess = sdkDep.aidl
1665 } else {
1666 deps.aidlPreprocess = sdkDep.aidl
1667 }
1668 }
1669
Jiyong Park92315372021-04-02 08:45:46 +09001670 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001671
1672 ctx.VisitDirectDeps(func(module android.Module) {
1673 otherName := ctx.OtherModuleName(module)
1674 tag := ctx.OtherModuleDependencyTag(module)
1675
1676 if IsJniDepTag(tag) {
1677 // Handled by AndroidApp.collectAppDeps
1678 return
1679 }
1680 if tag == certificateTag {
1681 // Handled by AndroidApp.collectAppDeps
1682 return
1683 }
1684
1685 if dep, ok := module.(SdkLibraryDependency); ok {
1686 switch tag {
1687 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001688 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001689 case staticLibTag:
1690 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1691 }
1692 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1693 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1694 if sdkLinkType != javaPlatform &&
1695 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1696 // dep is a sysprop implementation library, but this module is not linking against
1697 // the platform, so it gets the sysprop public stubs library instead. Replace
1698 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1699 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1700 dep = syspropDep.JavaInfo
1701 }
1702 switch tag {
1703 case bootClasspathTag:
1704 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1705 case libTag, instrumentationForTag:
1706 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1707 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1708 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1709 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1710 case java9LibTag:
1711 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1712 case staticLibTag:
1713 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1714 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1715 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1716 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1717 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1718 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1719 // Turbine doesn't run annotation processors, so any module that uses an
1720 // annotation processor that generates API is incompatible with the turbine
1721 // optimization.
1722 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1723 case pluginTag:
1724 if plugin, ok := module.(*Plugin); ok {
1725 if plugin.pluginProperties.Processor_class != nil {
1726 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1727 } else {
1728 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1729 }
1730 // Turbine doesn't run annotation processors, so any module that uses an
1731 // annotation processor that generates API is incompatible with the turbine
1732 // optimization.
1733 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1734 } else {
1735 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1736 }
1737 case errorpronePluginTag:
1738 if _, ok := module.(*Plugin); ok {
1739 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1740 } else {
1741 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1742 }
1743 case exportedPluginTag:
1744 if plugin, ok := module.(*Plugin); ok {
1745 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1746 if plugin.pluginProperties.Processor_class != nil {
1747 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1748 }
1749 // Turbine doesn't run annotation processors, so any module that uses an
1750 // annotation processor that generates API is incompatible with the turbine
1751 // optimization.
1752 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1753 } else {
1754 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1755 }
1756 case kotlinStdlibTag:
1757 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1758 case kotlinAnnotationsTag:
1759 deps.kotlinAnnotations = dep.HeaderJars
1760 case syspropPublicStubDepTag:
1761 // This is a sysprop implementation library, forward the JavaInfoProvider from
1762 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1763 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1764 JavaInfo: dep,
1765 })
1766 }
1767 } else if dep, ok := module.(android.SourceFileProducer); ok {
1768 switch tag {
1769 case libTag:
1770 checkProducesJars(ctx, dep)
1771 deps.classpath = append(deps.classpath, dep.Srcs()...)
1772 case staticLibTag:
1773 checkProducesJars(ctx, dep)
1774 deps.classpath = append(deps.classpath, dep.Srcs()...)
1775 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1776 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1777 }
1778 } else {
1779 switch tag {
1780 case bootClasspathTag:
1781 // If a system modules dependency has been added to the bootclasspath
1782 // then add its libs to the bootclasspath.
1783 sm := module.(SystemModulesProvider)
1784 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1785
1786 case systemModulesTag:
1787 if deps.systemModules != nil {
1788 panic("Found two system module dependencies")
1789 }
1790 sm := module.(SystemModulesProvider)
1791 outputDir, outputDeps := sm.OutputDirAndDeps()
1792 deps.systemModules = &systemModules{outputDir, outputDeps}
1793 }
1794 }
1795
1796 addCLCFromDep(ctx, module, j.classLoaderContexts)
1797 })
1798
1799 return deps
1800}
1801
1802func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1803 deps.processorPath = append(deps.processorPath, pluginJars...)
1804 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1805}
1806
1807// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1808// this interface.
1809type ProvidesUsesLib interface {
1810 ProvidesUsesLib() *string
1811}
1812
1813func (j *Module) ProvidesUsesLib() *string {
1814 return j.usesLibraryProperties.Provides_uses_lib
1815}
satayev1c564cc2021-05-25 19:50:30 +01001816
1817type ModuleWithStem interface {
1818 Stem() string
1819}
1820
1821var _ ModuleWithStem = (*Module)(nil)