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