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