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