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