blob: 579085b8a5eb3847184aa0bed0318100212248bd [file] [log] [blame]
Jaewoong Jung26342642021-03-17 15:56:23 -07001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package java
16
17import (
18 "fmt"
19 "path/filepath"
20 "strconv"
21 "strings"
22
23 "github.com/google/blueprint/pathtools"
24 "github.com/google/blueprint/proptools"
25
26 "android/soong/android"
27 "android/soong/dexpreopt"
28 "android/soong/java/config"
29)
30
31// This file contains the definition and the implementation of the base module that most
32// source-based Java module structs embed.
33
34// TODO:
35// Autogenerated files:
36// Renderscript
37// Post-jar passes:
38// Proguard
39// Rmtypedefs
40// DroidDoc
41// Findbugs
42
43// Properties that are common to most Java modules, i.e. whether it's a host or device module.
44type CommonProperties struct {
45 // list of source files used to compile the Java module. May be .java, .kt, .logtags, .proto,
46 // or .aidl files.
47 Srcs []string `android:"path,arch_variant"`
48
49 // list Kotlin of source files containing Kotlin code that should be treated as common code in
50 // a codebase that supports Kotlin multiplatform. See
51 // https://kotlinlang.org/docs/reference/multiplatform.html. May be only be .kt files.
52 Common_srcs []string `android:"path,arch_variant"`
53
54 // list of source files that should not be used to build the Java module.
55 // This is most useful in the arch/multilib variants to remove non-common files
56 Exclude_srcs []string `android:"path,arch_variant"`
57
58 // list of directories containing Java resources
59 Java_resource_dirs []string `android:"arch_variant"`
60
61 // list of directories that should be excluded from java_resource_dirs
62 Exclude_java_resource_dirs []string `android:"arch_variant"`
63
64 // list of files to use as Java resources
65 Java_resources []string `android:"path,arch_variant"`
66
67 // list of files that should be excluded from java_resources and java_resource_dirs
68 Exclude_java_resources []string `android:"path,arch_variant"`
69
70 // list of module-specific flags that will be used for javac compiles
71 Javacflags []string `android:"arch_variant"`
72
73 // list of module-specific flags that will be used for kotlinc compiles
74 Kotlincflags []string `android:"arch_variant"`
75
76 // list of java libraries that will be in the classpath
77 Libs []string `android:"arch_variant"`
78
79 // list of java libraries that will be compiled into the resulting jar
80 Static_libs []string `android:"arch_variant"`
81
82 // manifest file to be included in resulting jar
83 Manifest *string `android:"path"`
84
85 // if not blank, run jarjar using the specified rules file
86 Jarjar_rules *string `android:"path,arch_variant"`
87
88 // If not blank, set the java version passed to javac as -source and -target
89 Java_version *string
90
91 // If set to true, allow this module to be dexed and installed on devices. Has no
92 // effect on host modules, which are always considered installable.
93 Installable *bool
94
95 // If set to true, include sources used to compile the module in to the final jar
96 Include_srcs *bool
97
98 // If not empty, classes are restricted to the specified packages and their sub-packages.
99 // This restriction is checked after applying jarjar rules and including static libs.
100 Permitted_packages []string
101
102 // List of modules to use as annotation processors
103 Plugins []string
104
105 // List of modules to export to libraries that directly depend on this library as annotation
106 // processors. Note that if the plugins set generates_api: true this will disable the turbine
107 // optimization on modules that depend on this module, which will reduce parallelism and cause
108 // more recompilation.
109 Exported_plugins []string
110
111 // The number of Java source entries each Javac instance can process
112 Javac_shard_size *int64
113
114 // Add host jdk tools.jar to bootclasspath
115 Use_tools_jar *bool
116
117 Openjdk9 struct {
118 // List of source files that should only be used when passing -source 1.9 or higher
119 Srcs []string `android:"path"`
120
121 // List of javac flags that should only be used when passing -source 1.9 or higher
122 Javacflags []string
123 }
124
125 // When compiling language level 9+ .java code in packages that are part of
126 // a system module, patch_module names the module that your sources and
127 // dependencies should be patched into. The Android runtime currently
128 // doesn't implement the JEP 261 module system so this option is only
129 // supported at compile time. It should only be needed to compile tests in
130 // packages that exist in libcore and which are inconvenient to move
131 // elsewhere.
132 Patch_module *string `android:"arch_variant"`
133
134 Jacoco struct {
135 // List of classes to include for instrumentation with jacoco to collect coverage
136 // information at runtime when building with coverage enabled. If unset defaults to all
137 // classes.
138 // Supports '*' as the last character of an entry in the list as a wildcard match.
139 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
140 // it matches classes in the package that have the class name as a prefix.
141 Include_filter []string
142
143 // List of classes to exclude from instrumentation with jacoco to collect coverage
144 // information at runtime when building with coverage enabled. Overrides classes selected
145 // by the include_filter property.
146 // Supports '*' as the last character of an entry in the list as a wildcard match.
147 // If preceded by '.' it matches all classes in the package and subpackages, otherwise
148 // it matches classes in the package that have the class name as a prefix.
149 Exclude_filter []string
150 }
151
152 Errorprone struct {
153 // List of javac flags that should only be used when running errorprone.
154 Javacflags []string
155
156 // List of java_plugin modules that provide extra errorprone checks.
157 Extra_check_modules []string
Cole Faust75fffb12021-06-13 15:23:16 -0700158
Cole Faust2b1536e2021-06-18 12:25:54 -0700159 // This property can be in 3 states. When set to true, errorprone will
160 // be run during the regular build. When set to false, errorprone will
161 // never be run. When unset, errorprone will be run when the RUN_ERROR_PRONE
162 // environment variable is true. Setting this to false will improve build
163 // performance more than adding -XepDisableAllChecks in javacflags.
Cole Faust75fffb12021-06-13 15:23:16 -0700164 Enabled *bool
Jaewoong Jung26342642021-03-17 15:56:23 -0700165 }
166
167 Proto struct {
168 // List of extra options that will be passed to the proto generator.
169 Output_params []string
170 }
171
172 Instrument bool `blueprint:"mutated"`
173
174 // List of files to include in the META-INF/services folder of the resulting jar.
175 Services []string `android:"path,arch_variant"`
176
177 // If true, package the kotlin stdlib into the jar. Defaults to true.
178 Static_kotlin_stdlib *bool `android:"arch_variant"`
179
180 // A list of java_library instances that provide additional hiddenapi annotations for the library.
181 Hiddenapi_additional_annotations []string
182}
183
184// Properties that are specific to device modules. Host module factories should not add these when
185// constructing a new module.
186type DeviceProperties struct {
187 // if not blank, set to the version of the sdk to compile against.
188 // Defaults to compiling against the current platform.
189 Sdk_version *string
190
191 // if not blank, set the minimum version of the sdk that the compiled artifacts will run against.
192 // Defaults to sdk_version if not set.
193 Min_sdk_version *string
194
195 // if not blank, set the targetSdkVersion in the AndroidManifest.xml.
196 // Defaults to sdk_version if not set.
197 Target_sdk_version *string
198
199 // Whether to compile against the platform APIs instead of an SDK.
200 // If true, then sdk_version must be empty. The value of this field
201 // is ignored when module's type isn't android_app.
202 Platform_apis *bool
203
204 Aidl struct {
205 // Top level directories to pass to aidl tool
206 Include_dirs []string
207
208 // Directories rooted at the Android.bp file to pass to aidl tool
209 Local_include_dirs []string
210
211 // directories that should be added as include directories for any aidl sources of modules
212 // that depend on this module, as well as to aidl for this module.
213 Export_include_dirs []string
214
215 // whether to generate traces (for systrace) for this interface
216 Generate_traces *bool
217
218 // whether to generate Binder#GetTransaction name method.
219 Generate_get_transaction_name *bool
220
221 // list of flags that will be passed to the AIDL compiler
222 Flags []string
223 }
224
225 // If true, export a copy of the module as a -hostdex module for host testing.
226 Hostdex *bool
227
228 Target struct {
229 Hostdex struct {
230 // Additional required dependencies to add to -hostdex modules.
231 Required []string
232 }
233 }
234
235 // When targeting 1.9 and above, override the modules to use with --system,
236 // otherwise provides defaults libraries to add to the bootclasspath.
237 System_modules *string
238
Jaewoong Jung26342642021-03-17 15:56:23 -0700239 // set the name of the output
240 Stem *string
241
242 IsSDKLibrary bool `blueprint:"mutated"`
243
244 // If true, generate the signature file of APK Signing Scheme V4, along side the signed APK file.
245 // Defaults to false.
246 V4_signature *bool
247
248 // Only for libraries created by a sysprop_library module, SyspropPublicStub is the name of the
249 // public stubs library.
250 SyspropPublicStub string `blueprint:"mutated"`
251}
252
253// Functionality common to Module and Import
254//
255// It is embedded in Module so its functionality can be used by methods in Module
256// but it is currently only initialized by Import and Library.
257type embeddableInModuleAndImport struct {
258
259 // Functionality related to this being used as a component of a java_sdk_library.
260 EmbeddableSdkLibraryComponent
261}
262
Paul Duffin71b33cc2021-06-23 11:39:47 +0100263func (e *embeddableInModuleAndImport) initModuleAndImport(module android.Module) {
264 e.initSdkLibraryComponent(module)
Jaewoong Jung26342642021-03-17 15:56:23 -0700265}
266
267// Module/Import's DepIsInSameApex(...) delegates to this method.
268//
269// This cannot implement DepIsInSameApex(...) directly as that leads to ambiguity with
270// the one provided by ApexModuleBase.
271func (e *embeddableInModuleAndImport) depIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
272 // dependencies other than the static linkage are all considered crossing APEX boundary
273 if staticLibTag == ctx.OtherModuleDependencyTag(dep) {
274 return true
275 }
276 return false
277}
278
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100279// OptionalDexJarPath can be either unset, hold a valid path to a dex jar file,
280// or an invalid path describing the reason it is invalid.
281//
282// It is unset if a dex jar isn't applicable, i.e. no build rule has been
283// requested to create one.
284//
285// If a dex jar has been requested to be built then it is set, and it may be
286// either a valid android.Path, or invalid with a reason message. The latter
287// happens if the source that should produce the dex file isn't able to.
288//
289// E.g. it is invalid with a reason message if there is a prebuilt APEX that
290// could produce the dex jar through a deapexer module, but the APEX isn't
291// installable so doing so wouldn't be safe.
292type OptionalDexJarPath struct {
293 isSet bool
294 path android.OptionalPath
295}
296
297// IsSet returns true if a path has been set, either invalid or valid.
298func (o OptionalDexJarPath) IsSet() bool {
299 return o.isSet
300}
301
302// Valid returns true if there is a path that is valid.
303func (o OptionalDexJarPath) Valid() bool {
304 return o.isSet && o.path.Valid()
305}
306
307// Path returns the valid path, or panics if it's either not set or is invalid.
308func (o OptionalDexJarPath) Path() android.Path {
309 if !o.isSet {
310 panic("path isn't set")
311 }
312 return o.path.Path()
313}
314
315// PathOrNil returns the path if it's set and valid, or else nil.
316func (o OptionalDexJarPath) PathOrNil() android.Path {
317 if o.Valid() {
318 return o.Path()
319 }
320 return nil
321}
322
323// InvalidReason returns the reason for an invalid path, which is never "". It
324// returns "" for an unset or valid path.
325func (o OptionalDexJarPath) InvalidReason() string {
326 if !o.isSet {
327 return ""
328 }
329 return o.path.InvalidReason()
330}
331
332func (o OptionalDexJarPath) String() string {
333 if !o.isSet {
334 return "<unset>"
335 }
336 return o.path.String()
337}
338
339// makeUnsetDexJarPath returns an unset OptionalDexJarPath.
340func makeUnsetDexJarPath() OptionalDexJarPath {
341 return OptionalDexJarPath{isSet: false}
342}
343
344// makeDexJarPathFromOptionalPath returns an OptionalDexJarPath that is set with
345// the given OptionalPath, which may be valid or invalid.
346func makeDexJarPathFromOptionalPath(path android.OptionalPath) OptionalDexJarPath {
347 return OptionalDexJarPath{isSet: true, path: path}
348}
349
350// makeDexJarPathFromPath returns an OptionalDexJarPath that is set with the
351// valid given path. It returns an unset OptionalDexJarPath if the given path is
352// nil.
353func makeDexJarPathFromPath(path android.Path) OptionalDexJarPath {
354 if path == nil {
355 return makeUnsetDexJarPath()
356 }
357 return makeDexJarPathFromOptionalPath(android.OptionalPathForPath(path))
358}
359
Jaewoong Jung26342642021-03-17 15:56:23 -0700360// Module contains the properties and members used by all java module types
361type Module struct {
362 android.ModuleBase
363 android.DefaultableModuleBase
364 android.ApexModuleBase
365 android.SdkBase
366
367 // Functionality common to Module and Import.
368 embeddableInModuleAndImport
369
370 properties CommonProperties
371 protoProperties android.ProtoProperties
372 deviceProperties DeviceProperties
373
374 // jar file containing header classes including static library dependencies, suitable for
375 // inserting into the bootclasspath/classpath of another compile
376 headerJarFile android.Path
377
378 // jar file containing implementation classes including static library dependencies but no
379 // resources
380 implementationJarFile android.Path
381
382 // jar file containing only resources including from static library dependencies
383 resourceJar android.Path
384
385 // args and dependencies to package source files into a srcjar
386 srcJarArgs []string
387 srcJarDeps android.Paths
388
389 // jar file containing implementation classes and resources including static library
390 // dependencies
391 implementationAndResourcesJar android.Path
392
393 // output file containing classes.dex and resources
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +0100394 dexJarFile OptionalDexJarPath
Jaewoong Jung26342642021-03-17 15:56:23 -0700395
396 // output file containing uninstrumented classes that will be instrumented by jacoco
397 jacocoReportClassesFile android.Path
398
399 // output file of the module, which may be a classes jar or a dex jar
400 outputFile android.Path
401 extraOutputFiles android.Paths
402
403 exportAidlIncludeDirs android.Paths
404
405 logtagsSrcs android.Paths
406
407 // installed file for binary dependency
408 installFile android.Path
409
410 // list of .java files and srcjars that was passed to javac
411 compiledJavaSrcs android.Paths
412 compiledSrcJars android.Paths
413
414 // manifest file to use instead of properties.Manifest
415 overrideManifest android.OptionalPath
416
417 // map of SDK version to class loader context
418 classLoaderContexts dexpreopt.ClassLoaderContextMap
419
420 // list of plugins that this java module is exporting
421 exportedPluginJars android.Paths
422
423 // list of plugins that this java module is exporting
424 exportedPluginClasses []string
425
426 // if true, the exported plugins generate API and require disabling turbine.
427 exportedDisableTurbine bool
428
429 // list of source files, collected from srcFiles with unique java and all kt files,
430 // will be used by android.IDEInfo struct
431 expandIDEInfoCompiledSrcs []string
432
433 // expanded Jarjar_rules
434 expandJarjarRules android.Path
435
436 // list of additional targets for checkbuild
437 additionalCheckedModules android.Paths
438
439 // Extra files generated by the module type to be added as java resources.
440 extraResources android.Paths
441
442 hiddenAPI
443 dexer
444 dexpreopter
445 usesLibrary
446 linter
447
448 // list of the xref extraction files
449 kytheFiles android.Paths
450
451 // Collect the module directory for IDE info in java/jdeps.go.
452 modulePaths []string
453
454 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900455
456 sdkVersion android.SdkSpec
457 minSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700458}
459
Jiyong Park92315372021-04-02 08:45:46 +0900460func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
461 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900462 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700463 return nil
464 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900465 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000466 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700467 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
468 } else {
469 // Treat stable core platform as stable.
470 return nil
471 }
472 } else {
473 return fmt.Errorf("non stable SDK %v", sdkVersion)
474 }
475}
476
477// checkSdkVersions enforces restrictions around SDK dependencies.
478func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
479 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900480 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900481 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700482 ctx.PropertyErrorf("sdk_version",
483 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
484 }
485 }
486 }
487
488 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
489 // See rank() for details.
490 ctx.VisitDirectDeps(func(module android.Module) {
491 tag := ctx.OtherModuleDependencyTag(module)
492 switch module.(type) {
493 // TODO(satayev): cover other types as well, e.g. imports
494 case *Library, *AndroidLibrary:
495 switch tag {
496 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
497 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
498 }
499 }
500 })
501}
502
503func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900504 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700505 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900506 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700507 if usePlatformAPI && sdkVersionSpecified {
508 ctx.PropertyErrorf("platform_apis", "platform_apis must be false when sdk_version is not empty.")
509 } else if !usePlatformAPI && !sdkVersionSpecified {
510 ctx.PropertyErrorf("platform_apis", "platform_apis must be true when sdk_version is empty.")
511 }
512
513 }
514}
515
516func (j *Module) addHostProperties() {
517 j.AddProperties(
518 &j.properties,
519 &j.protoProperties,
520 &j.usesLibraryProperties,
521 )
522}
523
524func (j *Module) addHostAndDeviceProperties() {
525 j.addHostProperties()
526 j.AddProperties(
527 &j.deviceProperties,
528 &j.dexer.dexProperties,
529 &j.dexpreoptProperties,
530 &j.linter.properties,
531 )
532}
533
534func (j *Module) OutputFiles(tag string) (android.Paths, error) {
535 switch tag {
536 case "":
537 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
538 case android.DefaultDistTag:
539 return android.Paths{j.outputFile}, nil
540 case ".jar":
541 return android.Paths{j.implementationAndResourcesJar}, nil
542 case ".proguard_map":
543 if j.dexer.proguardDictionary.Valid() {
544 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
545 }
546 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
547 default:
548 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
549 }
550}
551
552var _ android.OutputFileProducer = (*Module)(nil)
553
554func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
555 initJavaModule(module, hod, false)
556}
557
558func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
559 initJavaModule(module, hod, true)
560}
561
562func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
563 multilib := android.MultilibCommon
564 if multiTargets {
565 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
566 } else {
567 android.InitAndroidArchModule(module, hod, multilib)
568 }
569 android.InitDefaultableModule(module)
570}
571
572func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
573 return j.properties.Instrument &&
574 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
575 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
576}
577
578func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
579 return j.shouldInstrument(ctx) &&
580 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
581 ctx.Config().UnbundledBuild())
582}
583
584func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
585 // Force enable the instrumentation for java code that is built for APEXes ...
586 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
587 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
588 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
589 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
590 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
591 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
592 return true
593 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
594 return true
595 }
596 }
597 return false
598}
599
Jiyong Park92315372021-04-02 08:45:46 +0900600func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
601 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700602}
603
Jiyong Parkf1691d22021-03-29 20:11:58 +0900604func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700605 return proptools.String(j.deviceProperties.System_modules)
606}
607
Jiyong Park92315372021-04-02 08:45:46 +0900608func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700609 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900610 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700611 }
Jiyong Park92315372021-04-02 08:45:46 +0900612 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700613}
614
Jiyong Parkf1691d22021-03-29 20:11:58 +0900615func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900616 return j.minSdkVersion.Raw
617}
618
619func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
620 if j.deviceProperties.Target_sdk_version != nil {
621 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
622 }
623 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700624}
625
626func (j *Module) AvailableFor(what string) bool {
627 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
628 // Exception: for hostdex: true libraries, the platform variant is created
629 // even if it's not marked as available to platform. In that case, the platform
630 // variant is used only for the hostdex and not installed to the device.
631 return true
632 }
633 return j.ApexModuleBase.AvailableFor(what)
634}
635
636func (j *Module) deps(ctx android.BottomUpMutatorContext) {
637 if ctx.Device() {
638 j.linter.deps(ctx)
639
Jiyong Parkf1691d22021-03-29 20:11:58 +0900640 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700641
642 if j.deviceProperties.SyspropPublicStub != "" {
643 // This is a sysprop implementation library that has a corresponding sysprop public
644 // stubs library, and a dependency on it so that dependencies on the implementation can
645 // be forwarded to the public stubs library when necessary.
646 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
647 }
648 }
649
650 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
651 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
652
653 // Add dependency on libraries that provide additional hidden api annotations.
654 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
655
656 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
657 // Require java_sdk_library at inter-partition java dependency to ensure stable
658 // interface between partitions. If inter-partition java_library dependency is detected,
659 // raise build error because java_library doesn't have a stable interface.
660 //
661 // Inputs:
662 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
663 // if true, enable enforcement
664 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
665 // exception list of java_library names to allow inter-partition dependency
666 for idx := range j.properties.Libs {
667 if libDeps[idx] == nil {
668 continue
669 }
670
671 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
672 // java_sdk_library is always allowed at inter-partition dependency.
673 // So, skip check.
674 if _, ok := javaDep.(*SdkLibrary); ok {
675 continue
676 }
677
678 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
679 }
680 }
681 }
682
683 // For library dependencies that are component libraries (like stubs), add the implementation
684 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
685 for _, dep := range libDeps {
686 if dep != nil {
687 if component, ok := dep.(SdkLibraryComponentDependency); ok {
688 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100689 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100690 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
691 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100692 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700693 }
694 }
695 }
696 }
697
698 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
699 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
700 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
701
702 android.ProtoDeps(ctx, &j.protoProperties)
703 if j.hasSrcExt(".proto") {
704 protoDeps(ctx, &j.protoProperties)
705 }
706
707 if j.hasSrcExt(".kt") {
708 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
709 // Kotlin files
710 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
711 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
712 if len(j.properties.Plugins) > 0 {
713 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
714 }
715 }
716
717 // Framework libraries need special handling in static coverage builds: they should not have
718 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
719 // the same jacoco classes coming from different bootclasspath jars.
720 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
721 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
722 j.properties.Instrument = true
723 }
724 } else if j.shouldInstrumentStatic(ctx) {
725 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
726 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700727
728 if j.useCompose() {
729 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
730 "androidx.compose.compiler_compiler-hosted")
731 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700732}
733
734func hasSrcExt(srcs []string, ext string) bool {
735 for _, src := range srcs {
736 if filepath.Ext(src) == ext {
737 return true
738 }
739 }
740
741 return false
742}
743
744func (j *Module) hasSrcExt(ext string) bool {
745 return hasSrcExt(j.properties.Srcs, ext)
746}
747
748func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
749 aidlIncludeDirs android.Paths) (string, android.Paths) {
750
751 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
752 aidlIncludes = append(aidlIncludes,
753 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
754 aidlIncludes = append(aidlIncludes,
755 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
756
757 var flags []string
758 var deps android.Paths
759
760 flags = append(flags, j.deviceProperties.Aidl.Flags...)
761
762 if aidlPreprocess.Valid() {
763 flags = append(flags, "-p"+aidlPreprocess.String())
764 deps = append(deps, aidlPreprocess.Path())
765 } else if len(aidlIncludeDirs) > 0 {
766 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
767 }
768
769 if len(j.exportAidlIncludeDirs) > 0 {
770 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
771 }
772
773 if len(aidlIncludes) > 0 {
774 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
775 }
776
777 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
778 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
779 flags = append(flags, "-I"+src.String())
780 }
781
782 if Bool(j.deviceProperties.Aidl.Generate_traces) {
783 flags = append(flags, "-t")
784 }
785
786 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
787 flags = append(flags, "--transaction_names")
788 }
789
790 return strings.Join(flags, " "), deps
791}
792
793func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
794
795 var flags javaBuilderFlags
796
797 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900798 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700799
Cole Faust2b1536e2021-06-18 12:25:54 -0700800 epEnabled := j.properties.Errorprone.Enabled
801 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700802 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
803 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
804 }
805
806 errorProneFlags := []string{
807 "-Xplugin:ErrorProne",
808 "${config.ErrorProneChecks}",
809 }
810 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
811
812 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
813 "'" + strings.Join(errorProneFlags, " ") + "'"
814 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
815 }
816
817 // classpath
818 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
819 flags.classpath = append(flags.classpath, deps.classpath...)
820 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
821 flags.processorPath = append(flags.processorPath, deps.processorPath...)
822 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
823
824 flags.processors = append(flags.processors, deps.processorClasses...)
825 flags.processors = android.FirstUniqueStrings(flags.processors)
826
827 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900828 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700829 // Give host-side tools a version of OpenJDK's standard libraries
830 // close to what they're targeting. As of Dec 2017, AOSP is only
831 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
832 //
833 // When building with OpenJDK 8, the following should have no
834 // effect since those jars would be available by default.
835 //
836 // When building with OpenJDK 9 but targeting a version < 1.8,
837 // putting them on the bootclasspath means that:
838 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
839 // b) references to existing APIs are not reinterpreted in an
840 // OpenJDK 9-specific way, eg. calls to subclasses of
841 // java.nio.Buffer as in http://b/70862583
842 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
843 flags.bootClasspath = append(flags.bootClasspath,
844 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
845 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
846 if Bool(j.properties.Use_tools_jar) {
847 flags.bootClasspath = append(flags.bootClasspath,
848 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
849 }
850 }
851
852 // systemModules
853 flags.systemModules = deps.systemModules
854
855 // aidl flags.
856 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
857
858 return flags
859}
860
861func (j *Module) collectJavacFlags(
862 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
863 // javac flags.
864 javacFlags := j.properties.Javacflags
865
866 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
867 // For non-host binaries, override the -g flag passed globally to remove
868 // local variable debug info to reduce disk and memory usage.
869 javacFlags = append(javacFlags, "-g:source,lines")
870 }
871 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
872
873 if flags.javaVersion.usesJavaModules() {
874 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
875
876 if j.properties.Patch_module != nil {
877 // Manually specify build directory in case it is not under the repo root.
878 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
879 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200880 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700881
882 // b/150878007
883 //
884 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
885 // execution root for --patch-module. If this javac command line is
886 // invoked within Bazel's execution root working directory, the top
887 // level directories (e.g. libcore/, tools/, frameworks/) are all
888 // symlinks. JDK9 javac does not traverse into symlinks, which causes
889 // --patch-module to fail source file lookups when invoked in the
890 // execution root.
891 //
892 // Short of patching javac or enumerating *all* directories as possible
893 // input dirs, manually add the top level dir of the source files to be
894 // compiled.
895 topLevelDirs := map[string]bool{}
896 for _, srcFilePath := range srcFiles {
897 srcFileParts := strings.Split(srcFilePath.String(), "/")
898 // Ignore source files that are already in the top level directory
899 // as well as generated files in the out directory. The out
900 // directory may be an absolute path, which means srcFileParts[0] is the
901 // empty string, so check that as well. Note that "out" in Bazel's execution
902 // root is *not* a symlink, which doesn't cause problems for --patch-modules
903 // anyway, so it's fine to not apply this workaround for generated
904 // source files.
905 if len(srcFileParts) > 1 &&
906 srcFileParts[0] != "" &&
907 srcFileParts[0] != "out" {
908 topLevelDirs[srcFileParts[0]] = true
909 }
910 }
911 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
912
913 classPath := flags.classpath.FormJavaClassPath("")
914 if classPath != "" {
915 patchPaths = append(patchPaths, classPath)
916 }
917 javacFlags = append(
918 javacFlags,
919 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
920 }
921 }
922
923 if len(javacFlags) > 0 {
924 // optimization.
925 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
926 flags.javacFlags = "$javacFlags"
927 }
928
929 return flags
930}
931
932func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
933 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
934
935 deps := j.collectDeps(ctx)
936 flags := j.collectBuilderFlags(ctx, deps)
937
938 if flags.javaVersion.usesJavaModules() {
939 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
940 }
941 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
942 if hasSrcExt(srcFiles.Strings(), ".proto") {
943 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
944 }
945
946 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
947 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
948 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
949 }
950
951 srcFiles = j.genSources(ctx, srcFiles, flags)
952
953 // Collect javac flags only after computing the full set of srcFiles to
954 // ensure that the --patch-module lookup paths are complete.
955 flags = j.collectJavacFlags(ctx, flags, srcFiles)
956
957 srcJars := srcFiles.FilterByExt(".srcjar")
958 srcJars = append(srcJars, deps.srcJars...)
959 if aaptSrcJar != nil {
960 srcJars = append(srcJars, aaptSrcJar)
961 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700962 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700963
964 if j.properties.Jarjar_rules != nil {
965 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
966 }
967
968 jarName := ctx.ModuleName() + ".jar"
969
970 javaSrcFiles := srcFiles.FilterByExt(".java")
971 var uniqueSrcFiles android.Paths
972 set := make(map[string]bool)
973 for _, v := range javaSrcFiles {
974 if _, found := set[v.String()]; !found {
975 set[v.String()] = true
976 uniqueSrcFiles = append(uniqueSrcFiles, v)
977 }
978 }
979
980 // Collect .java files for AIDEGen
981 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
982
983 var kotlinJars android.Paths
984
985 if srcFiles.HasExt(".kt") {
986 // user defined kotlin flags.
987 kotlincFlags := j.properties.Kotlincflags
988 CheckKotlincFlags(ctx, kotlincFlags)
989
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000990 // Workaround for KT-46512
991 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700992
993 // If there are kotlin files, compile them first but pass all the kotlin and java files
994 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
995 // won't emit any classes for them.
996 kotlincFlags = append(kotlincFlags, "-no-stdlib")
997 if ctx.Device() {
998 kotlincFlags = append(kotlincFlags, "-no-jdk")
999 }
Colin Crossa1ff7c62021-09-17 14:11:52 -07001000
1001 for _, plugin := range deps.kotlinPlugins {
1002 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1003 }
1004 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1005
Jaewoong Jung26342642021-03-17 15:56:23 -07001006 if len(kotlincFlags) > 0 {
1007 // optimization.
1008 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1009 flags.kotlincFlags += "$kotlincFlags"
1010 }
1011
1012 var kotlinSrcFiles android.Paths
1013 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1014 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1015
1016 // Collect .kt files for AIDEGen
1017 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1018 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1019
1020 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1021 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1022
1023 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1024 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1025
1026 if len(flags.processorPath) > 0 {
1027 // Use kapt for annotation processing
1028 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1029 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1030 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1031 srcJars = append(srcJars, kaptSrcJar)
1032 kotlinJars = append(kotlinJars, kaptResJar)
1033 // Disable annotation processing in javac, it's already been handled by kapt
1034 flags.processorPath = nil
1035 flags.processors = nil
1036 }
1037
1038 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
1039 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1040 if ctx.Failed() {
1041 return
1042 }
1043
1044 // Make javac rule depend on the kotlinc rule
1045 flags.classpath = append(flags.classpath, kotlinJar)
1046
1047 kotlinJars = append(kotlinJars, kotlinJar)
1048 // Jar kotlin classes into the final jar after javac
1049 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1050 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
1051 }
1052 }
1053
1054 jars := append(android.Paths(nil), kotlinJars...)
1055
1056 // Store the list of .java files that was passed to javac
1057 j.compiledJavaSrcs = uniqueSrcFiles
1058 j.compiledSrcJars = srcJars
1059
1060 enableSharding := false
1061 var headerJarFileWithoutJarjar android.Path
1062 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
1063 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1064 enableSharding = true
1065 // Formerly, there was a check here that prevented annotation processors
1066 // from being used when sharding was enabled, as some annotation processors
1067 // do not function correctly in sharded environments. It was removed to
1068 // allow for the use of annotation processors that do function correctly
1069 // with sharding enabled. See: b/77284273.
1070 }
1071 headerJarFileWithoutJarjar, j.headerJarFile =
1072 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
1073 if ctx.Failed() {
1074 return
1075 }
1076 }
1077 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1078 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001079 if Bool(j.properties.Errorprone.Enabled) {
1080 // If error-prone is enabled, enable errorprone flags on the regular
1081 // build.
1082 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001083 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001084 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1085 // a new jar file just for compiling with the errorprone compiler to.
1086 // This is because we don't want to cause the java files to get completely
1087 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1088 // We also don't want to run this if errorprone is enabled by default for
1089 // this module, or else we could have duplicated errorprone messages.
1090 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001091 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001092
1093 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1094 "errorprone", "errorprone")
1095
Jaewoong Jung26342642021-03-17 15:56:23 -07001096 extraJarDeps = append(extraJarDeps, errorprone)
1097 }
1098
1099 if enableSharding {
1100 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
1101 shardSize := int(*(j.properties.Javac_shard_size))
1102 var shardSrcs []android.Paths
1103 if len(uniqueSrcFiles) > 0 {
1104 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1105 for idx, shardSrc := range shardSrcs {
1106 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1107 nil, flags, extraJarDeps)
1108 jars = append(jars, classes)
1109 }
1110 }
1111 if len(srcJars) > 0 {
1112 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1113 nil, srcJars, flags, extraJarDeps)
1114 jars = append(jars, classes)
1115 }
1116 } else {
1117 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1118 jars = append(jars, classes)
1119 }
1120 if ctx.Failed() {
1121 return
1122 }
1123 }
1124
1125 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1126
1127 var includeSrcJar android.WritablePath
1128 if Bool(j.properties.Include_srcs) {
1129 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1130 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1131 }
1132
1133 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1134 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1135 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1136 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1137
1138 var resArgs []string
1139 var resDeps android.Paths
1140
1141 resArgs = append(resArgs, dirArgs...)
1142 resDeps = append(resDeps, dirDeps...)
1143
1144 resArgs = append(resArgs, fileArgs...)
1145 resDeps = append(resDeps, fileDeps...)
1146
1147 resArgs = append(resArgs, extraArgs...)
1148 resDeps = append(resDeps, extraDeps...)
1149
1150 if len(resArgs) > 0 {
1151 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1152 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1153 j.resourceJar = resourceJar
1154 if ctx.Failed() {
1155 return
1156 }
1157 }
1158
1159 var resourceJars android.Paths
1160 if j.resourceJar != nil {
1161 resourceJars = append(resourceJars, j.resourceJar)
1162 }
1163 if Bool(j.properties.Include_srcs) {
1164 resourceJars = append(resourceJars, includeSrcJar)
1165 }
1166 resourceJars = append(resourceJars, deps.staticResourceJars...)
1167
1168 if len(resourceJars) > 1 {
1169 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1170 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1171 false, nil, nil)
1172 j.resourceJar = combinedJar
1173 } else if len(resourceJars) == 1 {
1174 j.resourceJar = resourceJars[0]
1175 }
1176
1177 if len(deps.staticJars) > 0 {
1178 jars = append(jars, deps.staticJars...)
1179 }
1180
1181 manifest := j.overrideManifest
1182 if !manifest.Valid() && j.properties.Manifest != nil {
1183 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1184 }
1185
1186 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1187 if len(services) > 0 {
1188 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1189 var zipargs []string
1190 for _, file := range services {
1191 serviceFile := file.String()
1192 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1193 }
1194 rule := zip
1195 args := map[string]string{
1196 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1197 }
1198 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1199 rule = zipRE
1200 args["implicits"] = strings.Join(services.Strings(), ",")
1201 }
1202 ctx.Build(pctx, android.BuildParams{
1203 Rule: rule,
1204 Output: servicesJar,
1205 Implicits: services,
1206 Args: args,
1207 })
1208 jars = append(jars, servicesJar)
1209 }
1210
1211 // Combine the classes built from sources, any manifests, and any static libraries into
1212 // classes.jar. If there is only one input jar this step will be skipped.
1213 var outputFile android.OutputPath
1214
1215 if len(jars) == 1 && !manifest.Valid() {
1216 // Optimization: skip the combine step as there is nothing to do
1217 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1218 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1219 // any if len(jars) == 1.
1220
1221 // Transform the single path to the jar into an OutputPath as that is required by the following
1222 // code.
1223 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1224 // The path contains an embedded OutputPath so reuse that.
1225 outputFile = moduleOutPath.OutputPath
1226 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1227 // The path is an OutputPath so reuse it directly.
1228 outputFile = outputPath
1229 } else {
1230 // The file is not in the out directory so create an OutputPath into which it can be copied
1231 // and which the following code can use to refer to it.
1232 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1233 ctx.Build(pctx, android.BuildParams{
1234 Rule: android.Cp,
1235 Input: jars[0],
1236 Output: combinedJar,
1237 })
1238 outputFile = combinedJar.OutputPath
1239 }
1240 } else {
1241 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1242 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1243 false, nil, nil)
1244 outputFile = combinedJar.OutputPath
1245 }
1246
1247 // jarjar implementation jar if necessary
1248 if j.expandJarjarRules != nil {
1249 // Transform classes.jar into classes-jarjar.jar
1250 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1251 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1252 outputFile = jarjarFile
1253
1254 // jarjar resource jar if necessary
1255 if j.resourceJar != nil {
1256 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1257 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1258 j.resourceJar = resourceJarJarFile
1259 }
1260
1261 if ctx.Failed() {
1262 return
1263 }
1264 }
1265
1266 // Check package restrictions if necessary.
1267 if len(j.properties.Permitted_packages) > 0 {
1268 // Check packages and copy to package-checked file.
1269 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
1270 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
1271 j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
1272
1273 if ctx.Failed() {
1274 return
1275 }
1276 }
1277
1278 j.implementationJarFile = outputFile
1279 if j.headerJarFile == nil {
1280 j.headerJarFile = j.implementationJarFile
1281 }
1282
1283 if j.shouldInstrumentInApex(ctx) {
1284 j.properties.Instrument = true
1285 }
1286
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001287 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1288 specs := j.jacocoModuleToZipCommand(ctx)
1289 if ctx.Failed() {
1290 return
1291 }
1292
Jaewoong Jung26342642021-03-17 15:56:23 -07001293 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001294 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001295 }
1296
1297 // merge implementation jar with resources if necessary
1298 implementationAndResourcesJar := outputFile
1299 if j.resourceJar != nil {
1300 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1301 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1302 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1303 false, nil, nil)
1304 implementationAndResourcesJar = combinedJar
1305 }
1306
1307 j.implementationAndResourcesJar = implementationAndResourcesJar
1308
1309 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1310 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1311 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1312 if j.dexProperties.Compile_dex == nil {
1313 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1314 }
1315 if j.deviceProperties.Hostdex == nil {
1316 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1317 }
1318 }
1319
1320 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1321 if j.hasCode(ctx) {
1322 if j.shouldInstrumentStatic(ctx) {
1323 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1324 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1325 }
1326 // Dex compilation
1327 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001328 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001329 if ctx.Failed() {
1330 return
1331 }
1332
Jaewoong Jung26342642021-03-17 15:56:23 -07001333 // merge dex jar with resources if necessary
1334 if j.resourceJar != nil {
1335 jars := android.Paths{dexOutputFile, j.resourceJar}
1336 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1337 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1338 false, nil, nil)
1339 if *j.dexProperties.Uncompress_dex {
1340 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1341 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1342 dexOutputFile = combinedAlignedJar
1343 } else {
1344 dexOutputFile = combinedJar
1345 }
1346 }
1347
Paul Duffin4de94502021-05-16 05:21:16 +01001348 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001349
1350 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001351
1352 // Encode hidden API flags in dex file, if needed.
1353 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1354
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001355 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001356
1357 // Dexpreopting
1358 j.dexpreopt(ctx, dexOutputFile)
1359
1360 outputFile = dexOutputFile
1361 } else {
1362 // There is no code to compile into a dex jar, make sure the resources are propagated
1363 // to the APK if this is an app.
1364 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001365 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001366 }
1367
1368 if ctx.Failed() {
1369 return
1370 }
1371 } else {
1372 outputFile = implementationAndResourcesJar
1373 }
1374
1375 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001376 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001377 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001378 return v.String()
1379 } else {
1380 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1381 }
1382 }
1383
1384 j.linter.name = ctx.ModuleName()
1385 j.linter.srcs = srcFiles
1386 j.linter.srcJars = srcJars
1387 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1388 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001389 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1390 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1391 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001392 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001393 j.linter.javaLanguageLevel = flags.javaVersion.String()
1394 j.linter.kotlinLanguageLevel = "1.3"
1395 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1396 j.linter.buildModuleReportZip = true
1397 }
1398 j.linter.lint(ctx)
1399 }
1400
1401 ctx.CheckbuildFile(outputFile)
1402
1403 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1404 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1405 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1406 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1407 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1408 AidlIncludeDirs: j.exportAidlIncludeDirs,
1409 SrcJarArgs: j.srcJarArgs,
1410 SrcJarDeps: j.srcJarDeps,
1411 ExportedPlugins: j.exportedPluginJars,
1412 ExportedPluginClasses: j.exportedPluginClasses,
1413 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1414 JacocoReportClassesFile: j.jacocoReportClassesFile,
1415 })
1416
1417 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1418 j.outputFile = outputFile.WithoutRel()
1419}
1420
Colin Crossa1ff7c62021-09-17 14:11:52 -07001421func (j *Module) useCompose() bool {
1422 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1423}
1424
Cole Faust75fffb12021-06-13 15:23:16 -07001425// Returns a copy of the supplied flags, but with all the errorprone-related
1426// fields copied to the regular build's fields.
1427func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1428 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1429
1430 if len(flags.errorProneExtraJavacFlags) > 0 {
1431 if len(flags.javacFlags) > 0 {
1432 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1433 } else {
1434 flags.javacFlags = flags.errorProneExtraJavacFlags
1435 }
1436 }
1437 return flags
1438}
1439
Jaewoong Jung26342642021-03-17 15:56:23 -07001440func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1441 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1442
1443 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1444 if idx >= 0 {
1445 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1446 jarName += strconv.Itoa(idx)
1447 }
1448
1449 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1450 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1451
1452 if ctx.Config().EmitXrefRules() {
1453 extractionFile := android.PathForModuleOut(ctx, kzipName)
1454 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1455 j.kytheFiles = append(j.kytheFiles, extractionFile)
1456 }
1457
1458 return classes
1459}
1460
1461// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1462// since some of these flags may be used internally.
1463func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1464 for _, flag := range flags {
1465 flag = strings.TrimSpace(flag)
1466
1467 if !strings.HasPrefix(flag, "-") {
1468 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1469 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1470 ctx.PropertyErrorf("kotlincflags",
1471 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1472 } else if inList(flag, config.KotlincIllegalFlags) {
1473 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1474 } else if flag == "-include-runtime" {
1475 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1476 } else {
1477 args := strings.Split(flag, " ")
1478 if args[0] == "-kotlin-home" {
1479 ctx.PropertyErrorf("kotlincflags",
1480 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1481 }
1482 }
1483 }
1484}
1485
1486func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1487 deps deps, flags javaBuilderFlags, jarName string,
1488 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1489
1490 var jars android.Paths
1491 if len(srcFiles) > 0 || len(srcJars) > 0 {
1492 // Compile java sources into turbine.jar.
1493 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1494 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1495 if ctx.Failed() {
1496 return nil, nil
1497 }
1498 jars = append(jars, turbineJar)
1499 }
1500
1501 jars = append(jars, extraJars...)
1502
1503 // Combine any static header libraries into classes-header.jar. If there is only
1504 // one input jar this step will be skipped.
1505 jars = append(jars, deps.staticHeaderJars...)
1506
1507 // we cannot skip the combine step for now if there is only one jar
1508 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1509 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1510 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1511 false, nil, []string{"META-INF/TRANSITIVE"})
1512 headerJar = combinedJar
1513 jarjarHeaderJar = combinedJar
1514
1515 if j.expandJarjarRules != nil {
1516 // Transform classes.jar into classes-jarjar.jar
1517 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1518 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1519 jarjarHeaderJar = jarjarFile
1520 if ctx.Failed() {
1521 return nil, nil
1522 }
1523 }
1524
1525 return headerJar, jarjarHeaderJar
1526}
1527
1528func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001529 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001530
1531 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1532 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1533
1534 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1535
1536 j.jacocoReportClassesFile = jacocoReportClassesFile
1537
1538 return instrumentedJar
1539}
1540
1541func (j *Module) HeaderJars() android.Paths {
1542 if j.headerJarFile == nil {
1543 return nil
1544 }
1545 return android.Paths{j.headerJarFile}
1546}
1547
1548func (j *Module) ImplementationJars() android.Paths {
1549 if j.implementationJarFile == nil {
1550 return nil
1551 }
1552 return android.Paths{j.implementationJarFile}
1553}
1554
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001555func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001556 return j.dexJarFile
1557}
1558
1559func (j *Module) DexJarInstallPath() android.Path {
1560 return j.installFile
1561}
1562
1563func (j *Module) ImplementationAndResourcesJars() android.Paths {
1564 if j.implementationAndResourcesJar == nil {
1565 return nil
1566 }
1567 return android.Paths{j.implementationAndResourcesJar}
1568}
1569
1570func (j *Module) AidlIncludeDirs() android.Paths {
1571 // exportAidlIncludeDirs is type android.Paths already
1572 return j.exportAidlIncludeDirs
1573}
1574
1575func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1576 return j.classLoaderContexts
1577}
1578
1579// Collect information for opening IDE project files in java/jdeps.go.
1580func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1581 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1582 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1583 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1584 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1585 if j.expandJarjarRules != nil {
1586 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1587 }
1588 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1589}
1590
1591func (j *Module) CompilerDeps() []string {
1592 jdeps := []string{}
1593 jdeps = append(jdeps, j.properties.Libs...)
1594 jdeps = append(jdeps, j.properties.Static_libs...)
1595 return jdeps
1596}
1597
1598func (j *Module) hasCode(ctx android.ModuleContext) bool {
1599 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1600 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1601}
1602
1603// Implements android.ApexModule
1604func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1605 return j.depIsInSameApex(ctx, dep)
1606}
1607
1608// Implements android.ApexModule
1609func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1610 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001611 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001612 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001613 return fmt.Errorf("min_sdk_version is not specified")
1614 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001615 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001616 return nil
1617 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001618 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1619 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001620 }
1621 return nil
1622}
1623
1624func (j *Module) Stem() string {
1625 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1626}
1627
Jaewoong Jung26342642021-03-17 15:56:23 -07001628func (j *Module) JacocoReportClassesFile() android.Path {
1629 return j.jacocoReportClassesFile
1630}
1631
1632func (j *Module) IsInstallable() bool {
1633 return Bool(j.properties.Installable)
1634}
1635
1636type sdkLinkType int
1637
1638const (
1639 // TODO(jiyong) rename these for better readability. Make the allowed
1640 // and disallowed link types explicit
1641 // order is important here. See rank()
1642 javaCore sdkLinkType = iota
1643 javaSdk
1644 javaSystem
1645 javaModule
1646 javaSystemServer
1647 javaPlatform
1648)
1649
1650func (lt sdkLinkType) String() string {
1651 switch lt {
1652 case javaCore:
1653 return "core Java API"
1654 case javaSdk:
1655 return "Android API"
1656 case javaSystem:
1657 return "system API"
1658 case javaModule:
1659 return "module API"
1660 case javaSystemServer:
1661 return "system server API"
1662 case javaPlatform:
1663 return "private API"
1664 default:
1665 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1666 }
1667}
1668
1669// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1670// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1671// can't statically depend on modules that use Platform API.
1672func (lt sdkLinkType) rank() int {
1673 return int(lt)
1674}
1675
1676type moduleWithSdkDep interface {
1677 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001678 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001679}
1680
Jiyong Park92315372021-04-02 08:45:46 +09001681func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001682 switch name {
1683 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1684 "stub-annotations", "private-stub-annotations-jar",
1685 "core-lambda-stubs", "core-generated-annotation-stubs":
1686 return javaCore, true
1687 case "android_stubs_current":
1688 return javaSdk, true
1689 case "android_system_stubs_current":
1690 return javaSystem, true
1691 case "android_module_lib_stubs_current":
1692 return javaModule, true
1693 case "android_system_server_stubs_current":
1694 return javaSystemServer, true
1695 case "android_test_stubs_current":
1696 return javaSystem, true
1697 }
1698
1699 if stub, linkType := moduleStubLinkType(name); stub {
1700 return linkType, true
1701 }
1702
Jiyong Park92315372021-04-02 08:45:46 +09001703 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001704 switch ver.Kind {
1705 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001706 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001707 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001708 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001709 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001710 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001711 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001712 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001713 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001714 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001715 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001716 return javaPlatform, false
1717 }
1718
Jiyong Parkf1691d22021-03-29 20:11:58 +09001719 if !ver.Valid() {
1720 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001721 }
1722 return javaSdk, false
1723}
1724
1725// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1726// this module's. See the comment on rank() for details and an example.
1727func (j *Module) checkSdkLinkType(
1728 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1729 if ctx.Host() {
1730 return
1731 }
1732
Jiyong Park92315372021-04-02 08:45:46 +09001733 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001734 if stubs {
1735 return
1736 }
Jiyong Park92315372021-04-02 08:45:46 +09001737 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001738
1739 if myLinkType.rank() < depLinkType.rank() {
1740 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1741 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1742 "property of the source or target module so that target module is built "+
1743 "with the same or smaller API set when compared to the source.",
1744 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1745 }
1746}
1747
1748func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1749 var deps deps
1750
1751 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001752 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001753 if sdkDep.invalidVersion {
1754 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1755 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1756 } else if sdkDep.useFiles {
1757 // sdkDep.jar is actually equivalent to turbine header.jar.
1758 deps.classpath = append(deps.classpath, sdkDep.jars...)
1759 deps.aidlPreprocess = sdkDep.aidl
1760 } else {
1761 deps.aidlPreprocess = sdkDep.aidl
1762 }
1763 }
1764
Jiyong Park92315372021-04-02 08:45:46 +09001765 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001766
1767 ctx.VisitDirectDeps(func(module android.Module) {
1768 otherName := ctx.OtherModuleName(module)
1769 tag := ctx.OtherModuleDependencyTag(module)
1770
1771 if IsJniDepTag(tag) {
1772 // Handled by AndroidApp.collectAppDeps
1773 return
1774 }
1775 if tag == certificateTag {
1776 // Handled by AndroidApp.collectAppDeps
1777 return
1778 }
1779
1780 if dep, ok := module.(SdkLibraryDependency); ok {
1781 switch tag {
1782 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001783 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001784 case staticLibTag:
1785 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1786 }
1787 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1788 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1789 if sdkLinkType != javaPlatform &&
1790 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1791 // dep is a sysprop implementation library, but this module is not linking against
1792 // the platform, so it gets the sysprop public stubs library instead. Replace
1793 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1794 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1795 dep = syspropDep.JavaInfo
1796 }
1797 switch tag {
1798 case bootClasspathTag:
1799 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1800 case libTag, instrumentationForTag:
1801 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1802 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1803 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1804 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1805 case java9LibTag:
1806 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1807 case staticLibTag:
1808 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1809 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1810 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1811 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1812 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1813 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1814 // Turbine doesn't run annotation processors, so any module that uses an
1815 // annotation processor that generates API is incompatible with the turbine
1816 // optimization.
1817 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1818 case pluginTag:
1819 if plugin, ok := module.(*Plugin); ok {
1820 if plugin.pluginProperties.Processor_class != nil {
1821 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1822 } else {
1823 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1824 }
1825 // Turbine doesn't run annotation processors, so any module that uses an
1826 // annotation processor that generates API is incompatible with the turbine
1827 // optimization.
1828 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1829 } else {
1830 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1831 }
1832 case errorpronePluginTag:
1833 if _, ok := module.(*Plugin); ok {
1834 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1835 } else {
1836 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1837 }
1838 case exportedPluginTag:
1839 if plugin, ok := module.(*Plugin); ok {
1840 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1841 if plugin.pluginProperties.Processor_class != nil {
1842 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1843 }
1844 // Turbine doesn't run annotation processors, so any module that uses an
1845 // annotation processor that generates API is incompatible with the turbine
1846 // optimization.
1847 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1848 } else {
1849 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1850 }
1851 case kotlinStdlibTag:
1852 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1853 case kotlinAnnotationsTag:
1854 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001855 case kotlinPluginTag:
1856 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001857 case syspropPublicStubDepTag:
1858 // This is a sysprop implementation library, forward the JavaInfoProvider from
1859 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1860 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1861 JavaInfo: dep,
1862 })
1863 }
1864 } else if dep, ok := module.(android.SourceFileProducer); ok {
1865 switch tag {
1866 case libTag:
1867 checkProducesJars(ctx, dep)
1868 deps.classpath = append(deps.classpath, dep.Srcs()...)
1869 case staticLibTag:
1870 checkProducesJars(ctx, dep)
1871 deps.classpath = append(deps.classpath, dep.Srcs()...)
1872 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1873 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1874 }
1875 } else {
1876 switch tag {
1877 case bootClasspathTag:
1878 // If a system modules dependency has been added to the bootclasspath
1879 // then add its libs to the bootclasspath.
1880 sm := module.(SystemModulesProvider)
1881 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1882
1883 case systemModulesTag:
1884 if deps.systemModules != nil {
1885 panic("Found two system module dependencies")
1886 }
1887 sm := module.(SystemModulesProvider)
1888 outputDir, outputDeps := sm.OutputDirAndDeps()
1889 deps.systemModules = &systemModules{outputDir, outputDeps}
1890 }
1891 }
1892
1893 addCLCFromDep(ctx, module, j.classLoaderContexts)
1894 })
1895
1896 return deps
1897}
1898
1899func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1900 deps.processorPath = append(deps.processorPath, pluginJars...)
1901 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1902}
1903
1904// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1905// this interface.
1906type ProvidesUsesLib interface {
1907 ProvidesUsesLib() *string
1908}
1909
1910func (j *Module) ProvidesUsesLib() *string {
1911 return j.usesLibraryProperties.Provides_uses_lib
1912}
satayev1c564cc2021-05-25 19:50:30 +01001913
1914type ModuleWithStem interface {
1915 Stem() string
1916}
1917
1918var _ ModuleWithStem = (*Module)(nil)