blob: 2ef065036d9175e029e58b6d64e45fe70433d177 [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
Jaewoong Jung26342642021-03-17 15:56:23 -0700436 // Extra files generated by the module type to be added as java resources.
437 extraResources android.Paths
438
439 hiddenAPI
440 dexer
441 dexpreopter
442 usesLibrary
443 linter
444
445 // list of the xref extraction files
446 kytheFiles android.Paths
447
448 // Collect the module directory for IDE info in java/jdeps.go.
449 modulePaths []string
450
451 hideApexVariantFromMake bool
Jiyong Park92315372021-04-02 08:45:46 +0900452
453 sdkVersion android.SdkSpec
454 minSdkVersion android.SdkSpec
Jaewoong Jung26342642021-03-17 15:56:23 -0700455}
456
Jiyong Park92315372021-04-02 08:45:46 +0900457func (j *Module) CheckStableSdkVersion(ctx android.BaseModuleContext) error {
458 sdkVersion := j.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +0900459 if sdkVersion.Stable() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700460 return nil
461 }
Jiyong Parkf1691d22021-03-29 20:11:58 +0900462 if sdkVersion.Kind == android.SdkCorePlatform {
Paul Duffin1ea7c9f2021-03-15 09:39:13 +0000463 if useLegacyCorePlatformApi(ctx, j.BaseModuleName()) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700464 return fmt.Errorf("non stable SDK %v - uses legacy core platform", sdkVersion)
465 } else {
466 // Treat stable core platform as stable.
467 return nil
468 }
469 } else {
470 return fmt.Errorf("non stable SDK %v", sdkVersion)
471 }
472}
473
474// checkSdkVersions enforces restrictions around SDK dependencies.
475func (j *Module) checkSdkVersions(ctx android.ModuleContext) {
476 if j.RequiresStableAPIs(ctx) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900477 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jiyong Park92315372021-04-02 08:45:46 +0900478 if !sc.SdkVersion(ctx).Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700479 ctx.PropertyErrorf("sdk_version",
480 "sdk_version must have a value when the module is located at vendor or product(only if PRODUCT_ENFORCE_PRODUCT_PARTITION_INTERFACE is set).")
481 }
482 }
483 }
484
485 // Make sure this module doesn't statically link to modules with lower-ranked SDK link type.
486 // See rank() for details.
487 ctx.VisitDirectDeps(func(module android.Module) {
488 tag := ctx.OtherModuleDependencyTag(module)
489 switch module.(type) {
490 // TODO(satayev): cover other types as well, e.g. imports
491 case *Library, *AndroidLibrary:
492 switch tag {
493 case bootClasspathTag, libTag, staticLibTag, java9LibTag:
494 j.checkSdkLinkType(ctx, module.(moduleWithSdkDep), tag.(dependencyTag))
495 }
496 }
497 })
498}
499
500func (j *Module) checkPlatformAPI(ctx android.ModuleContext) {
Jiyong Parkf1691d22021-03-29 20:11:58 +0900501 if sc, ok := ctx.Module().(android.SdkContext); ok {
Jaewoong Jung26342642021-03-17 15:56:23 -0700502 usePlatformAPI := proptools.Bool(j.deviceProperties.Platform_apis)
Jiyong Park92315372021-04-02 08:45:46 +0900503 sdkVersionSpecified := sc.SdkVersion(ctx).Specified()
Jaewoong Jung26342642021-03-17 15:56:23 -0700504 if usePlatformAPI && sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000505 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is not empty, which means this module cannot use platform APIs. However platform_apis is set to true.")
Jaewoong Jung26342642021-03-17 15:56:23 -0700506 } else if !usePlatformAPI && !sdkVersionSpecified {
Spandan Das60999342021-11-16 04:15:33 +0000507 ctx.PropertyErrorf("platform_apis", "This module has conflicting settings. sdk_version is empty, which means that this module is build against platform APIs. However platform_apis is not set to true")
Jaewoong Jung26342642021-03-17 15:56:23 -0700508 }
509
510 }
511}
512
513func (j *Module) addHostProperties() {
514 j.AddProperties(
515 &j.properties,
516 &j.protoProperties,
517 &j.usesLibraryProperties,
518 )
519}
520
521func (j *Module) addHostAndDeviceProperties() {
522 j.addHostProperties()
523 j.AddProperties(
524 &j.deviceProperties,
525 &j.dexer.dexProperties,
526 &j.dexpreoptProperties,
527 &j.linter.properties,
528 )
529}
530
531func (j *Module) OutputFiles(tag string) (android.Paths, error) {
532 switch tag {
533 case "":
534 return append(android.Paths{j.outputFile}, j.extraOutputFiles...), nil
535 case android.DefaultDistTag:
536 return android.Paths{j.outputFile}, nil
537 case ".jar":
538 return android.Paths{j.implementationAndResourcesJar}, nil
539 case ".proguard_map":
540 if j.dexer.proguardDictionary.Valid() {
541 return android.Paths{j.dexer.proguardDictionary.Path()}, nil
542 }
543 return nil, fmt.Errorf("%q was requested, but no output file was found.", tag)
544 default:
545 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
546 }
547}
548
549var _ android.OutputFileProducer = (*Module)(nil)
550
551func InitJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
552 initJavaModule(module, hod, false)
553}
554
555func InitJavaModuleMultiTargets(module android.DefaultableModule, hod android.HostOrDeviceSupported) {
556 initJavaModule(module, hod, true)
557}
558
559func initJavaModule(module android.DefaultableModule, hod android.HostOrDeviceSupported, multiTargets bool) {
560 multilib := android.MultilibCommon
561 if multiTargets {
562 android.InitAndroidMultiTargetsArchModule(module, hod, multilib)
563 } else {
564 android.InitAndroidArchModule(module, hod, multilib)
565 }
566 android.InitDefaultableModule(module)
567}
568
569func (j *Module) shouldInstrument(ctx android.BaseModuleContext) bool {
570 return j.properties.Instrument &&
571 ctx.Config().IsEnvTrue("EMMA_INSTRUMENT") &&
572 ctx.DeviceConfig().JavaCoverageEnabledForPath(ctx.ModuleDir())
573}
574
575func (j *Module) shouldInstrumentStatic(ctx android.BaseModuleContext) bool {
576 return j.shouldInstrument(ctx) &&
577 (ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_STATIC") ||
578 ctx.Config().UnbundledBuild())
579}
580
581func (j *Module) shouldInstrumentInApex(ctx android.BaseModuleContext) bool {
582 // Force enable the instrumentation for java code that is built for APEXes ...
583 // except for the jacocoagent itself (because instrumenting jacocoagent using jacocoagent
584 // doesn't make sense) or framework libraries (e.g. libraries found in the InstrumentFrameworkModules list) unless EMMA_INSTRUMENT_FRAMEWORK is true.
585 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
586 isJacocoAgent := ctx.ModuleName() == "jacocoagent"
587 if j.DirectlyInAnyApex() && !isJacocoAgent && !apexInfo.IsForPlatform() {
588 if !inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
589 return true
590 } else if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
591 return true
592 }
593 }
594 return false
595}
596
Jiyong Park92315372021-04-02 08:45:46 +0900597func (j *Module) SdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
598 return android.SdkSpecFrom(ctx, String(j.deviceProperties.Sdk_version))
Jaewoong Jung26342642021-03-17 15:56:23 -0700599}
600
Jiyong Parkf1691d22021-03-29 20:11:58 +0900601func (j *Module) SystemModules() string {
Jaewoong Jung26342642021-03-17 15:56:23 -0700602 return proptools.String(j.deviceProperties.System_modules)
603}
604
Jiyong Park92315372021-04-02 08:45:46 +0900605func (j *Module) MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
Jaewoong Jung26342642021-03-17 15:56:23 -0700606 if j.deviceProperties.Min_sdk_version != nil {
Jiyong Park92315372021-04-02 08:45:46 +0900607 return android.SdkSpecFrom(ctx, *j.deviceProperties.Min_sdk_version)
Jaewoong Jung26342642021-03-17 15:56:23 -0700608 }
Jiyong Park92315372021-04-02 08:45:46 +0900609 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700610}
611
Jiyong Parkf1691d22021-03-29 20:11:58 +0900612func (j *Module) MinSdkVersionString() string {
Jiyong Park92315372021-04-02 08:45:46 +0900613 return j.minSdkVersion.Raw
614}
615
616func (j *Module) TargetSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec {
617 if j.deviceProperties.Target_sdk_version != nil {
618 return android.SdkSpecFrom(ctx, *j.deviceProperties.Target_sdk_version)
619 }
620 return j.SdkVersion(ctx)
Jaewoong Jung26342642021-03-17 15:56:23 -0700621}
622
623func (j *Module) AvailableFor(what string) bool {
624 if what == android.AvailableToPlatform && Bool(j.deviceProperties.Hostdex) {
625 // Exception: for hostdex: true libraries, the platform variant is created
626 // even if it's not marked as available to platform. In that case, the platform
627 // variant is used only for the hostdex and not installed to the device.
628 return true
629 }
630 return j.ApexModuleBase.AvailableFor(what)
631}
632
633func (j *Module) deps(ctx android.BottomUpMutatorContext) {
634 if ctx.Device() {
635 j.linter.deps(ctx)
636
Jiyong Parkf1691d22021-03-29 20:11:58 +0900637 sdkDeps(ctx, android.SdkContext(j), j.dexer)
Jaewoong Jung26342642021-03-17 15:56:23 -0700638
639 if j.deviceProperties.SyspropPublicStub != "" {
640 // This is a sysprop implementation library that has a corresponding sysprop public
641 // stubs library, and a dependency on it so that dependencies on the implementation can
642 // be forwarded to the public stubs library when necessary.
643 ctx.AddVariationDependencies(nil, syspropPublicStubDepTag, j.deviceProperties.SyspropPublicStub)
644 }
645 }
646
647 libDeps := ctx.AddVariationDependencies(nil, libTag, j.properties.Libs...)
648 ctx.AddVariationDependencies(nil, staticLibTag, j.properties.Static_libs...)
649
650 // Add dependency on libraries that provide additional hidden api annotations.
651 ctx.AddVariationDependencies(nil, hiddenApiAnnotationsTag, j.properties.Hiddenapi_additional_annotations...)
652
653 if ctx.DeviceConfig().VndkVersion() != "" && ctx.Config().EnforceInterPartitionJavaSdkLibrary() {
654 // Require java_sdk_library at inter-partition java dependency to ensure stable
655 // interface between partitions. If inter-partition java_library dependency is detected,
656 // raise build error because java_library doesn't have a stable interface.
657 //
658 // Inputs:
659 // PRODUCT_ENFORCE_INTER_PARTITION_JAVA_SDK_LIBRARY
660 // if true, enable enforcement
661 // PRODUCT_INTER_PARTITION_JAVA_LIBRARY_ALLOWLIST
662 // exception list of java_library names to allow inter-partition dependency
663 for idx := range j.properties.Libs {
664 if libDeps[idx] == nil {
665 continue
666 }
667
668 if javaDep, ok := libDeps[idx].(javaSdkLibraryEnforceContext); ok {
669 // java_sdk_library is always allowed at inter-partition dependency.
670 // So, skip check.
671 if _, ok := javaDep.(*SdkLibrary); ok {
672 continue
673 }
674
675 j.checkPartitionsForJavaDependency(ctx, "libs", javaDep)
676 }
677 }
678 }
679
680 // For library dependencies that are component libraries (like stubs), add the implementation
681 // as a dependency (dexpreopt needs to be against the implementation library, not stubs).
682 for _, dep := range libDeps {
683 if dep != nil {
684 if component, ok := dep.(SdkLibraryComponentDependency); ok {
685 if lib := component.OptionalSdkLibraryImplementation(); lib != nil {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100686 // Add library as optional if it's one of the optional compatibility libs.
Ulya Trafimovich0b1c70e2021-08-20 15:39:12 +0100687 optional := android.InList(*lib, dexpreopt.OptionalCompatUsesLibs)
688 tag := makeUsesLibraryDependencyTag(dexpreopt.AnySdkVersion, optional, true)
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100689 ctx.AddVariationDependencies(nil, tag, *lib)
Jaewoong Jung26342642021-03-17 15:56:23 -0700690 }
691 }
692 }
693 }
694
695 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), pluginTag, j.properties.Plugins...)
696 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), errorpronePluginTag, j.properties.Errorprone.Extra_check_modules...)
697 ctx.AddFarVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), exportedPluginTag, j.properties.Exported_plugins...)
698
699 android.ProtoDeps(ctx, &j.protoProperties)
700 if j.hasSrcExt(".proto") {
701 protoDeps(ctx, &j.protoProperties)
702 }
703
704 if j.hasSrcExt(".kt") {
705 // TODO(ccross): move this to a mutator pass that can tell if generated sources contain
706 // Kotlin files
707 ctx.AddVariationDependencies(nil, kotlinStdlibTag,
708 "kotlin-stdlib", "kotlin-stdlib-jdk7", "kotlin-stdlib-jdk8")
709 if len(j.properties.Plugins) > 0 {
710 ctx.AddVariationDependencies(nil, kotlinAnnotationsTag, "kotlin-annotations")
711 }
712 }
713
714 // Framework libraries need special handling in static coverage builds: they should not have
715 // static dependency on jacoco, otherwise there would be multiple conflicting definitions of
716 // the same jacoco classes coming from different bootclasspath jars.
717 if inList(ctx.ModuleName(), config.InstrumentFrameworkModules) {
718 if ctx.Config().IsEnvTrue("EMMA_INSTRUMENT_FRAMEWORK") {
719 j.properties.Instrument = true
720 }
721 } else if j.shouldInstrumentStatic(ctx) {
722 ctx.AddVariationDependencies(nil, staticLibTag, "jacocoagent")
723 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700724
725 if j.useCompose() {
726 ctx.AddVariationDependencies(ctx.Config().BuildOSCommonTarget.Variations(), kotlinPluginTag,
727 "androidx.compose.compiler_compiler-hosted")
728 }
Jaewoong Jung26342642021-03-17 15:56:23 -0700729}
730
731func hasSrcExt(srcs []string, ext string) bool {
732 for _, src := range srcs {
733 if filepath.Ext(src) == ext {
734 return true
735 }
736 }
737
738 return false
739}
740
741func (j *Module) hasSrcExt(ext string) bool {
742 return hasSrcExt(j.properties.Srcs, ext)
743}
744
745func (j *Module) aidlFlags(ctx android.ModuleContext, aidlPreprocess android.OptionalPath,
746 aidlIncludeDirs android.Paths) (string, android.Paths) {
747
748 aidlIncludes := android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Local_include_dirs)
749 aidlIncludes = append(aidlIncludes,
750 android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)...)
751 aidlIncludes = append(aidlIncludes,
752 android.PathsForSource(ctx, j.deviceProperties.Aidl.Include_dirs)...)
753
754 var flags []string
755 var deps android.Paths
756
757 flags = append(flags, j.deviceProperties.Aidl.Flags...)
758
759 if aidlPreprocess.Valid() {
760 flags = append(flags, "-p"+aidlPreprocess.String())
761 deps = append(deps, aidlPreprocess.Path())
762 } else if len(aidlIncludeDirs) > 0 {
763 flags = append(flags, android.JoinWithPrefix(aidlIncludeDirs.Strings(), "-I"))
764 }
765
766 if len(j.exportAidlIncludeDirs) > 0 {
767 flags = append(flags, android.JoinWithPrefix(j.exportAidlIncludeDirs.Strings(), "-I"))
768 }
769
770 if len(aidlIncludes) > 0 {
771 flags = append(flags, android.JoinWithPrefix(aidlIncludes.Strings(), "-I"))
772 }
773
774 flags = append(flags, "-I"+android.PathForModuleSrc(ctx).String())
775 if src := android.ExistentPathForSource(ctx, ctx.ModuleDir(), "src"); src.Valid() {
776 flags = append(flags, "-I"+src.String())
777 }
778
779 if Bool(j.deviceProperties.Aidl.Generate_traces) {
780 flags = append(flags, "-t")
781 }
782
783 if Bool(j.deviceProperties.Aidl.Generate_get_transaction_name) {
784 flags = append(flags, "--transaction_names")
785 }
786
787 return strings.Join(flags, " "), deps
788}
789
790func (j *Module) collectBuilderFlags(ctx android.ModuleContext, deps deps) javaBuilderFlags {
791
792 var flags javaBuilderFlags
793
794 // javaVersion flag.
Jiyong Parkf1691d22021-03-29 20:11:58 +0900795 flags.javaVersion = getJavaVersion(ctx, String(j.properties.Java_version), android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -0700796
Cole Faust2b1536e2021-06-18 12:25:54 -0700797 epEnabled := j.properties.Errorprone.Enabled
798 if (ctx.Config().RunErrorProne() && epEnabled == nil) || Bool(epEnabled) {
Jaewoong Jung26342642021-03-17 15:56:23 -0700799 if config.ErrorProneClasspath == nil && ctx.Config().TestProductVariables == nil {
800 ctx.ModuleErrorf("cannot build with Error Prone, missing external/error_prone?")
801 }
802
803 errorProneFlags := []string{
804 "-Xplugin:ErrorProne",
805 "${config.ErrorProneChecks}",
806 }
807 errorProneFlags = append(errorProneFlags, j.properties.Errorprone.Javacflags...)
808
809 flags.errorProneExtraJavacFlags = "${config.ErrorProneFlags} " +
810 "'" + strings.Join(errorProneFlags, " ") + "'"
811 flags.errorProneProcessorPath = classpath(android.PathsForSource(ctx, config.ErrorProneClasspath))
812 }
813
814 // classpath
815 flags.bootClasspath = append(flags.bootClasspath, deps.bootClasspath...)
816 flags.classpath = append(flags.classpath, deps.classpath...)
817 flags.java9Classpath = append(flags.java9Classpath, deps.java9Classpath...)
818 flags.processorPath = append(flags.processorPath, deps.processorPath...)
819 flags.errorProneProcessorPath = append(flags.errorProneProcessorPath, deps.errorProneProcessorPath...)
820
821 flags.processors = append(flags.processors, deps.processorClasses...)
822 flags.processors = android.FirstUniqueStrings(flags.processors)
823
824 if len(flags.bootClasspath) == 0 && ctx.Host() && !flags.javaVersion.usesJavaModules() &&
Jiyong Parkf1691d22021-03-29 20:11:58 +0900825 decodeSdkDep(ctx, android.SdkContext(j)).hasStandardLibs() {
Jaewoong Jung26342642021-03-17 15:56:23 -0700826 // Give host-side tools a version of OpenJDK's standard libraries
827 // close to what they're targeting. As of Dec 2017, AOSP is only
828 // bundling OpenJDK 8 and 9, so nothing < 8 is available.
829 //
830 // When building with OpenJDK 8, the following should have no
831 // effect since those jars would be available by default.
832 //
833 // When building with OpenJDK 9 but targeting a version < 1.8,
834 // putting them on the bootclasspath means that:
835 // a) code can't (accidentally) refer to OpenJDK 9 specific APIs
836 // b) references to existing APIs are not reinterpreted in an
837 // OpenJDK 9-specific way, eg. calls to subclasses of
838 // java.nio.Buffer as in http://b/70862583
839 java8Home := ctx.Config().Getenv("ANDROID_JAVA8_HOME")
840 flags.bootClasspath = append(flags.bootClasspath,
841 android.PathForSource(ctx, java8Home, "jre/lib/jce.jar"),
842 android.PathForSource(ctx, java8Home, "jre/lib/rt.jar"))
843 if Bool(j.properties.Use_tools_jar) {
844 flags.bootClasspath = append(flags.bootClasspath,
845 android.PathForSource(ctx, java8Home, "lib/tools.jar"))
846 }
847 }
848
849 // systemModules
850 flags.systemModules = deps.systemModules
851
852 // aidl flags.
853 flags.aidlFlags, flags.aidlDeps = j.aidlFlags(ctx, deps.aidlPreprocess, deps.aidlIncludeDirs)
854
855 return flags
856}
857
858func (j *Module) collectJavacFlags(
859 ctx android.ModuleContext, flags javaBuilderFlags, srcFiles android.Paths) javaBuilderFlags {
860 // javac flags.
861 javacFlags := j.properties.Javacflags
862
863 if ctx.Config().MinimizeJavaDebugInfo() && !ctx.Host() {
864 // For non-host binaries, override the -g flag passed globally to remove
865 // local variable debug info to reduce disk and memory usage.
866 javacFlags = append(javacFlags, "-g:source,lines")
867 }
868 javacFlags = append(javacFlags, "-Xlint:-dep-ann")
869
870 if flags.javaVersion.usesJavaModules() {
871 javacFlags = append(javacFlags, j.properties.Openjdk9.Javacflags...)
872
873 if j.properties.Patch_module != nil {
874 // Manually specify build directory in case it is not under the repo root.
875 // (javac doesn't seem to expand into symbolic links when searching for patch-module targets, so
876 // just adding a symlink under the root doesn't help.)
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200877 patchPaths := []string{".", ctx.Config().SoongOutDir()}
Jaewoong Jung26342642021-03-17 15:56:23 -0700878
879 // b/150878007
880 //
881 // Workaround to support *Bazel-executed* JDK9 javac in Bazel's
882 // execution root for --patch-module. If this javac command line is
883 // invoked within Bazel's execution root working directory, the top
884 // level directories (e.g. libcore/, tools/, frameworks/) are all
885 // symlinks. JDK9 javac does not traverse into symlinks, which causes
886 // --patch-module to fail source file lookups when invoked in the
887 // execution root.
888 //
889 // Short of patching javac or enumerating *all* directories as possible
890 // input dirs, manually add the top level dir of the source files to be
891 // compiled.
892 topLevelDirs := map[string]bool{}
893 for _, srcFilePath := range srcFiles {
894 srcFileParts := strings.Split(srcFilePath.String(), "/")
895 // Ignore source files that are already in the top level directory
896 // as well as generated files in the out directory. The out
897 // directory may be an absolute path, which means srcFileParts[0] is the
898 // empty string, so check that as well. Note that "out" in Bazel's execution
899 // root is *not* a symlink, which doesn't cause problems for --patch-modules
900 // anyway, so it's fine to not apply this workaround for generated
901 // source files.
902 if len(srcFileParts) > 1 &&
903 srcFileParts[0] != "" &&
904 srcFileParts[0] != "out" {
905 topLevelDirs[srcFileParts[0]] = true
906 }
907 }
908 patchPaths = append(patchPaths, android.SortedStringKeys(topLevelDirs)...)
909
910 classPath := flags.classpath.FormJavaClassPath("")
911 if classPath != "" {
912 patchPaths = append(patchPaths, classPath)
913 }
914 javacFlags = append(
915 javacFlags,
916 "--patch-module="+String(j.properties.Patch_module)+"="+strings.Join(patchPaths, ":"))
917 }
918 }
919
920 if len(javacFlags) > 0 {
921 // optimization.
922 ctx.Variable(pctx, "javacFlags", strings.Join(javacFlags, " "))
923 flags.javacFlags = "$javacFlags"
924 }
925
926 return flags
927}
928
929func (j *Module) compile(ctx android.ModuleContext, aaptSrcJar android.Path) {
930 j.exportAidlIncludeDirs = android.PathsForModuleSrc(ctx, j.deviceProperties.Aidl.Export_include_dirs)
931
932 deps := j.collectDeps(ctx)
933 flags := j.collectBuilderFlags(ctx, deps)
934
935 if flags.javaVersion.usesJavaModules() {
936 j.properties.Srcs = append(j.properties.Srcs, j.properties.Openjdk9.Srcs...)
937 }
938 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
939 if hasSrcExt(srcFiles.Strings(), ".proto") {
940 flags = protoFlags(ctx, &j.properties, &j.protoProperties, flags)
941 }
942
943 kotlinCommonSrcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Common_srcs, nil)
944 if len(kotlinCommonSrcFiles.FilterOutByExt(".kt")) > 0 {
945 ctx.PropertyErrorf("common_srcs", "common_srcs must be .kt files")
946 }
947
948 srcFiles = j.genSources(ctx, srcFiles, flags)
949
950 // Collect javac flags only after computing the full set of srcFiles to
951 // ensure that the --patch-module lookup paths are complete.
952 flags = j.collectJavacFlags(ctx, flags, srcFiles)
953
954 srcJars := srcFiles.FilterByExt(".srcjar")
955 srcJars = append(srcJars, deps.srcJars...)
956 if aaptSrcJar != nil {
957 srcJars = append(srcJars, aaptSrcJar)
958 }
Colin Crossb0ef30a2021-06-29 10:42:00 -0700959 srcFiles = srcFiles.FilterOutByExt(".srcjar")
Jaewoong Jung26342642021-03-17 15:56:23 -0700960
961 if j.properties.Jarjar_rules != nil {
962 j.expandJarjarRules = android.PathForModuleSrc(ctx, *j.properties.Jarjar_rules)
963 }
964
965 jarName := ctx.ModuleName() + ".jar"
966
967 javaSrcFiles := srcFiles.FilterByExt(".java")
968 var uniqueSrcFiles android.Paths
969 set := make(map[string]bool)
970 for _, v := range javaSrcFiles {
971 if _, found := set[v.String()]; !found {
972 set[v.String()] = true
973 uniqueSrcFiles = append(uniqueSrcFiles, v)
974 }
975 }
976
977 // Collect .java files for AIDEGen
978 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, uniqueSrcFiles.Strings()...)
979
980 var kotlinJars android.Paths
981
982 if srcFiles.HasExt(".kt") {
983 // user defined kotlin flags.
984 kotlincFlags := j.properties.Kotlincflags
985 CheckKotlincFlags(ctx, kotlincFlags)
986
Aurimas Liutikas24a987f2021-05-17 17:47:10 +0000987 // Workaround for KT-46512
988 kotlincFlags = append(kotlincFlags, "-Xsam-conversions=class")
Jaewoong Jung26342642021-03-17 15:56:23 -0700989
990 // If there are kotlin files, compile them first but pass all the kotlin and java files
991 // kotlinc will use the java files to resolve types referenced by the kotlin files, but
992 // won't emit any classes for them.
993 kotlincFlags = append(kotlincFlags, "-no-stdlib")
994 if ctx.Device() {
995 kotlincFlags = append(kotlincFlags, "-no-jdk")
996 }
Colin Crossa1ff7c62021-09-17 14:11:52 -0700997
998 for _, plugin := range deps.kotlinPlugins {
999 kotlincFlags = append(kotlincFlags, "-Xplugin="+plugin.String())
1000 }
1001 flags.kotlincDeps = append(flags.kotlincDeps, deps.kotlinPlugins...)
1002
Jaewoong Jung26342642021-03-17 15:56:23 -07001003 if len(kotlincFlags) > 0 {
1004 // optimization.
1005 ctx.Variable(pctx, "kotlincFlags", strings.Join(kotlincFlags, " "))
1006 flags.kotlincFlags += "$kotlincFlags"
1007 }
1008
1009 var kotlinSrcFiles android.Paths
1010 kotlinSrcFiles = append(kotlinSrcFiles, uniqueSrcFiles...)
1011 kotlinSrcFiles = append(kotlinSrcFiles, srcFiles.FilterByExt(".kt")...)
1012
1013 // Collect .kt files for AIDEGen
1014 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, srcFiles.FilterByExt(".kt").Strings()...)
1015 j.expandIDEInfoCompiledSrcs = append(j.expandIDEInfoCompiledSrcs, kotlinCommonSrcFiles.Strings()...)
1016
1017 flags.classpath = append(flags.classpath, deps.kotlinStdlib...)
1018 flags.classpath = append(flags.classpath, deps.kotlinAnnotations...)
1019
1020 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.bootClasspath...)
1021 flags.kotlincClasspath = append(flags.kotlincClasspath, flags.classpath...)
1022
1023 if len(flags.processorPath) > 0 {
1024 // Use kapt for annotation processing
1025 kaptSrcJar := android.PathForModuleOut(ctx, "kapt", "kapt-sources.jar")
1026 kaptResJar := android.PathForModuleOut(ctx, "kapt", "kapt-res.jar")
1027 kotlinKapt(ctx, kaptSrcJar, kaptResJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1028 srcJars = append(srcJars, kaptSrcJar)
1029 kotlinJars = append(kotlinJars, kaptResJar)
1030 // Disable annotation processing in javac, it's already been handled by kapt
1031 flags.processorPath = nil
1032 flags.processors = nil
1033 }
1034
1035 kotlinJar := android.PathForModuleOut(ctx, "kotlin", jarName)
1036 kotlinCompile(ctx, kotlinJar, kotlinSrcFiles, kotlinCommonSrcFiles, srcJars, flags)
1037 if ctx.Failed() {
1038 return
1039 }
1040
1041 // Make javac rule depend on the kotlinc rule
1042 flags.classpath = append(flags.classpath, kotlinJar)
1043
1044 kotlinJars = append(kotlinJars, kotlinJar)
1045 // Jar kotlin classes into the final jar after javac
1046 if BoolDefault(j.properties.Static_kotlin_stdlib, true) {
1047 kotlinJars = append(kotlinJars, deps.kotlinStdlib...)
1048 }
1049 }
1050
1051 jars := append(android.Paths(nil), kotlinJars...)
1052
1053 // Store the list of .java files that was passed to javac
1054 j.compiledJavaSrcs = uniqueSrcFiles
1055 j.compiledSrcJars = srcJars
1056
1057 enableSharding := false
1058 var headerJarFileWithoutJarjar android.Path
1059 if ctx.Device() && !ctx.Config().IsEnvFalse("TURBINE_ENABLED") && !deps.disableTurbine {
1060 if j.properties.Javac_shard_size != nil && *(j.properties.Javac_shard_size) > 0 {
1061 enableSharding = true
1062 // Formerly, there was a check here that prevented annotation processors
1063 // from being used when sharding was enabled, as some annotation processors
1064 // do not function correctly in sharded environments. It was removed to
1065 // allow for the use of annotation processors that do function correctly
1066 // with sharding enabled. See: b/77284273.
1067 }
1068 headerJarFileWithoutJarjar, j.headerJarFile =
1069 j.compileJavaHeader(ctx, uniqueSrcFiles, srcJars, deps, flags, jarName, kotlinJars)
1070 if ctx.Failed() {
1071 return
1072 }
1073 }
1074 if len(uniqueSrcFiles) > 0 || len(srcJars) > 0 {
1075 var extraJarDeps android.Paths
Cole Faust75fffb12021-06-13 15:23:16 -07001076 if Bool(j.properties.Errorprone.Enabled) {
1077 // If error-prone is enabled, enable errorprone flags on the regular
1078 // build.
1079 flags = enableErrorproneFlags(flags)
Cole Faust2b1536e2021-06-18 12:25:54 -07001080 } else if ctx.Config().RunErrorProne() && j.properties.Errorprone.Enabled == nil {
Cole Faust75fffb12021-06-13 15:23:16 -07001081 // Otherwise, if the RUN_ERROR_PRONE environment variable is set, create
1082 // a new jar file just for compiling with the errorprone compiler to.
1083 // This is because we don't want to cause the java files to get completely
1084 // rebuilt every time the state of the RUN_ERROR_PRONE variable changes.
1085 // We also don't want to run this if errorprone is enabled by default for
1086 // this module, or else we could have duplicated errorprone messages.
1087 errorproneFlags := enableErrorproneFlags(flags)
Jaewoong Jung26342642021-03-17 15:56:23 -07001088 errorprone := android.PathForModuleOut(ctx, "errorprone", jarName)
Cole Faust75fffb12021-06-13 15:23:16 -07001089
1090 transformJavaToClasses(ctx, errorprone, -1, uniqueSrcFiles, srcJars, errorproneFlags, nil,
1091 "errorprone", "errorprone")
1092
Jaewoong Jung26342642021-03-17 15:56:23 -07001093 extraJarDeps = append(extraJarDeps, errorprone)
1094 }
1095
1096 if enableSharding {
1097 flags.classpath = append(flags.classpath, headerJarFileWithoutJarjar)
1098 shardSize := int(*(j.properties.Javac_shard_size))
1099 var shardSrcs []android.Paths
1100 if len(uniqueSrcFiles) > 0 {
1101 shardSrcs = android.ShardPaths(uniqueSrcFiles, shardSize)
1102 for idx, shardSrc := range shardSrcs {
1103 classes := j.compileJavaClasses(ctx, jarName, idx, shardSrc,
1104 nil, flags, extraJarDeps)
1105 jars = append(jars, classes)
1106 }
1107 }
1108 if len(srcJars) > 0 {
1109 classes := j.compileJavaClasses(ctx, jarName, len(shardSrcs),
1110 nil, srcJars, flags, extraJarDeps)
1111 jars = append(jars, classes)
1112 }
1113 } else {
1114 classes := j.compileJavaClasses(ctx, jarName, -1, uniqueSrcFiles, srcJars, flags, extraJarDeps)
1115 jars = append(jars, classes)
1116 }
1117 if ctx.Failed() {
1118 return
1119 }
1120 }
1121
1122 j.srcJarArgs, j.srcJarDeps = resourcePathsToJarArgs(srcFiles), srcFiles
1123
1124 var includeSrcJar android.WritablePath
1125 if Bool(j.properties.Include_srcs) {
1126 includeSrcJar = android.PathForModuleOut(ctx, ctx.ModuleName()+".srcjar")
1127 TransformResourcesToJar(ctx, includeSrcJar, j.srcJarArgs, j.srcJarDeps)
1128 }
1129
1130 dirArgs, dirDeps := ResourceDirsToJarArgs(ctx, j.properties.Java_resource_dirs,
1131 j.properties.Exclude_java_resource_dirs, j.properties.Exclude_java_resources)
1132 fileArgs, fileDeps := ResourceFilesToJarArgs(ctx, j.properties.Java_resources, j.properties.Exclude_java_resources)
1133 extraArgs, extraDeps := resourcePathsToJarArgs(j.extraResources), j.extraResources
1134
1135 var resArgs []string
1136 var resDeps android.Paths
1137
1138 resArgs = append(resArgs, dirArgs...)
1139 resDeps = append(resDeps, dirDeps...)
1140
1141 resArgs = append(resArgs, fileArgs...)
1142 resDeps = append(resDeps, fileDeps...)
1143
1144 resArgs = append(resArgs, extraArgs...)
1145 resDeps = append(resDeps, extraDeps...)
1146
1147 if len(resArgs) > 0 {
1148 resourceJar := android.PathForModuleOut(ctx, "res", jarName)
1149 TransformResourcesToJar(ctx, resourceJar, resArgs, resDeps)
1150 j.resourceJar = resourceJar
1151 if ctx.Failed() {
1152 return
1153 }
1154 }
1155
1156 var resourceJars android.Paths
1157 if j.resourceJar != nil {
1158 resourceJars = append(resourceJars, j.resourceJar)
1159 }
1160 if Bool(j.properties.Include_srcs) {
1161 resourceJars = append(resourceJars, includeSrcJar)
1162 }
1163 resourceJars = append(resourceJars, deps.staticResourceJars...)
1164
1165 if len(resourceJars) > 1 {
1166 combinedJar := android.PathForModuleOut(ctx, "res-combined", jarName)
1167 TransformJarsToJar(ctx, combinedJar, "for resources", resourceJars, android.OptionalPath{},
1168 false, nil, nil)
1169 j.resourceJar = combinedJar
1170 } else if len(resourceJars) == 1 {
1171 j.resourceJar = resourceJars[0]
1172 }
1173
1174 if len(deps.staticJars) > 0 {
1175 jars = append(jars, deps.staticJars...)
1176 }
1177
1178 manifest := j.overrideManifest
1179 if !manifest.Valid() && j.properties.Manifest != nil {
1180 manifest = android.OptionalPathForPath(android.PathForModuleSrc(ctx, *j.properties.Manifest))
1181 }
1182
1183 services := android.PathsForModuleSrc(ctx, j.properties.Services)
1184 if len(services) > 0 {
1185 servicesJar := android.PathForModuleOut(ctx, "services", jarName)
1186 var zipargs []string
1187 for _, file := range services {
1188 serviceFile := file.String()
1189 zipargs = append(zipargs, "-C", filepath.Dir(serviceFile), "-f", serviceFile)
1190 }
1191 rule := zip
1192 args := map[string]string{
1193 "jarArgs": "-P META-INF/services/ " + strings.Join(proptools.NinjaAndShellEscapeList(zipargs), " "),
1194 }
1195 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_ZIP") {
1196 rule = zipRE
1197 args["implicits"] = strings.Join(services.Strings(), ",")
1198 }
1199 ctx.Build(pctx, android.BuildParams{
1200 Rule: rule,
1201 Output: servicesJar,
1202 Implicits: services,
1203 Args: args,
1204 })
1205 jars = append(jars, servicesJar)
1206 }
1207
1208 // Combine the classes built from sources, any manifests, and any static libraries into
1209 // classes.jar. If there is only one input jar this step will be skipped.
1210 var outputFile android.OutputPath
1211
1212 if len(jars) == 1 && !manifest.Valid() {
1213 // Optimization: skip the combine step as there is nothing to do
1214 // TODO(ccross): this leaves any module-info.class files, but those should only come from
1215 // prebuilt dependencies until we support modules in the platform build, so there shouldn't be
1216 // any if len(jars) == 1.
1217
1218 // Transform the single path to the jar into an OutputPath as that is required by the following
1219 // code.
1220 if moduleOutPath, ok := jars[0].(android.ModuleOutPath); ok {
1221 // The path contains an embedded OutputPath so reuse that.
1222 outputFile = moduleOutPath.OutputPath
1223 } else if outputPath, ok := jars[0].(android.OutputPath); ok {
1224 // The path is an OutputPath so reuse it directly.
1225 outputFile = outputPath
1226 } else {
1227 // The file is not in the out directory so create an OutputPath into which it can be copied
1228 // and which the following code can use to refer to it.
1229 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1230 ctx.Build(pctx, android.BuildParams{
1231 Rule: android.Cp,
1232 Input: jars[0],
1233 Output: combinedJar,
1234 })
1235 outputFile = combinedJar.OutputPath
1236 }
1237 } else {
1238 combinedJar := android.PathForModuleOut(ctx, "combined", jarName)
1239 TransformJarsToJar(ctx, combinedJar, "for javac", jars, manifest,
1240 false, nil, nil)
1241 outputFile = combinedJar.OutputPath
1242 }
1243
1244 // jarjar implementation jar if necessary
1245 if j.expandJarjarRules != nil {
1246 // Transform classes.jar into classes-jarjar.jar
1247 jarjarFile := android.PathForModuleOut(ctx, "jarjar", jarName).OutputPath
1248 TransformJarJar(ctx, jarjarFile, outputFile, j.expandJarjarRules)
1249 outputFile = jarjarFile
1250
1251 // jarjar resource jar if necessary
1252 if j.resourceJar != nil {
1253 resourceJarJarFile := android.PathForModuleOut(ctx, "res-jarjar", jarName)
1254 TransformJarJar(ctx, resourceJarJarFile, j.resourceJar, j.expandJarjarRules)
1255 j.resourceJar = resourceJarJarFile
1256 }
1257
1258 if ctx.Failed() {
1259 return
1260 }
1261 }
1262
1263 // Check package restrictions if necessary.
1264 if len(j.properties.Permitted_packages) > 0 {
Paul Duffin08a18bf2021-10-01 13:19:58 +01001265 // Time stamp file created by the package check rule.
Jaewoong Jung26342642021-03-17 15:56:23 -07001266 pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
Paul Duffin08a18bf2021-10-01 13:19:58 +01001267
1268 // Create a rule to copy the output jar to another path and add a validate dependency that
1269 // will check that the jar only contains the permitted packages. The new location will become
1270 // the output file of this module.
1271 inputFile := outputFile
1272 outputFile = android.PathForModuleOut(ctx, "package-check", jarName).OutputPath
1273 ctx.Build(pctx, android.BuildParams{
1274 Rule: android.Cp,
1275 Input: inputFile,
1276 Output: outputFile,
1277 // Make sure that any dependency on the output file will cause ninja to run the package check
1278 // rule.
1279 Validation: pkgckFile,
1280 })
1281
1282 // Check packages and create a timestamp file when complete.
Jaewoong Jung26342642021-03-17 15:56:23 -07001283 CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
Jaewoong Jung26342642021-03-17 15:56:23 -07001284
1285 if ctx.Failed() {
1286 return
1287 }
1288 }
1289
1290 j.implementationJarFile = outputFile
1291 if j.headerJarFile == nil {
1292 j.headerJarFile = j.implementationJarFile
1293 }
1294
1295 if j.shouldInstrumentInApex(ctx) {
1296 j.properties.Instrument = true
1297 }
1298
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001299 // enforce syntax check to jacoco filters for any build (http://b/183622051)
1300 specs := j.jacocoModuleToZipCommand(ctx)
1301 if ctx.Failed() {
1302 return
1303 }
1304
Jaewoong Jung26342642021-03-17 15:56:23 -07001305 if j.shouldInstrument(ctx) {
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001306 outputFile = j.instrument(ctx, flags, outputFile, jarName, specs)
Jaewoong Jung26342642021-03-17 15:56:23 -07001307 }
1308
1309 // merge implementation jar with resources if necessary
1310 implementationAndResourcesJar := outputFile
1311 if j.resourceJar != nil {
1312 jars := android.Paths{j.resourceJar, implementationAndResourcesJar}
1313 combinedJar := android.PathForModuleOut(ctx, "withres", jarName).OutputPath
1314 TransformJarsToJar(ctx, combinedJar, "for resources", jars, manifest,
1315 false, nil, nil)
1316 implementationAndResourcesJar = combinedJar
1317 }
1318
1319 j.implementationAndResourcesJar = implementationAndResourcesJar
1320
1321 // Enable dex compilation for the APEX variants, unless it is disabled explicitly
1322 apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
1323 if j.DirectlyInAnyApex() && !apexInfo.IsForPlatform() {
1324 if j.dexProperties.Compile_dex == nil {
1325 j.dexProperties.Compile_dex = proptools.BoolPtr(true)
1326 }
1327 if j.deviceProperties.Hostdex == nil {
1328 j.deviceProperties.Hostdex = proptools.BoolPtr(true)
1329 }
1330 }
1331
1332 if ctx.Device() && (Bool(j.properties.Installable) || Bool(j.dexProperties.Compile_dex)) {
1333 if j.hasCode(ctx) {
1334 if j.shouldInstrumentStatic(ctx) {
1335 j.dexer.extraProguardFlagFiles = append(j.dexer.extraProguardFlagFiles,
1336 android.PathForSource(ctx, "build/make/core/proguard.jacoco.flags"))
1337 }
1338 // Dex compilation
1339 var dexOutputFile android.OutputPath
Colin Crossa79a52c2021-08-04 10:52:44 -07001340 dexOutputFile = j.dexer.compileDex(ctx, flags, j.MinSdkVersion(ctx), implementationAndResourcesJar, jarName)
Jaewoong Jung26342642021-03-17 15:56:23 -07001341 if ctx.Failed() {
1342 return
1343 }
1344
Jaewoong Jung26342642021-03-17 15:56:23 -07001345 // merge dex jar with resources if necessary
1346 if j.resourceJar != nil {
1347 jars := android.Paths{dexOutputFile, j.resourceJar}
1348 combinedJar := android.PathForModuleOut(ctx, "dex-withres", jarName).OutputPath
1349 TransformJarsToJar(ctx, combinedJar, "for dex resources", jars, android.OptionalPath{},
1350 false, nil, nil)
1351 if *j.dexProperties.Uncompress_dex {
1352 combinedAlignedJar := android.PathForModuleOut(ctx, "dex-withres-aligned", jarName).OutputPath
1353 TransformZipAlign(ctx, combinedAlignedJar, combinedJar)
1354 dexOutputFile = combinedAlignedJar
1355 } else {
1356 dexOutputFile = combinedJar
1357 }
1358 }
1359
Paul Duffin4de94502021-05-16 05:21:16 +01001360 // Initialize the hiddenapi structure.
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001361
1362 j.initHiddenAPI(ctx, makeDexJarPathFromPath(dexOutputFile), j.implementationJarFile, j.dexProperties.Uncompress_dex)
Paul Duffin4de94502021-05-16 05:21:16 +01001363
1364 // Encode hidden API flags in dex file, if needed.
1365 dexOutputFile = j.hiddenAPIEncodeDex(ctx, dexOutputFile)
1366
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001367 j.dexJarFile = makeDexJarPathFromPath(dexOutputFile)
Jaewoong Jung26342642021-03-17 15:56:23 -07001368
1369 // Dexpreopting
1370 j.dexpreopt(ctx, dexOutputFile)
1371
1372 outputFile = dexOutputFile
1373 } else {
1374 // There is no code to compile into a dex jar, make sure the resources are propagated
1375 // to the APK if this is an app.
1376 outputFile = implementationAndResourcesJar
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001377 j.dexJarFile = makeDexJarPathFromPath(j.resourceJar)
Jaewoong Jung26342642021-03-17 15:56:23 -07001378 }
1379
1380 if ctx.Failed() {
1381 return
1382 }
1383 } else {
1384 outputFile = implementationAndResourcesJar
1385 }
1386
1387 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001388 lintSDKVersionString := func(sdkSpec android.SdkSpec) string {
Jiyong Park54105c42021-03-31 18:17:53 +09001389 if v := sdkSpec.ApiLevel; !v.IsPreview() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001390 return v.String()
1391 } else {
1392 return ctx.Config().DefaultAppTargetSdk(ctx).String()
1393 }
1394 }
1395
1396 j.linter.name = ctx.ModuleName()
1397 j.linter.srcs = srcFiles
1398 j.linter.srcJars = srcJars
1399 j.linter.classpath = append(append(android.Paths(nil), flags.bootClasspath...), flags.classpath...)
1400 j.linter.classes = j.implementationJarFile
Jiyong Park92315372021-04-02 08:45:46 +09001401 j.linter.minSdkVersion = lintSDKVersionString(j.MinSdkVersion(ctx))
1402 j.linter.targetSdkVersion = lintSDKVersionString(j.TargetSdkVersion(ctx))
1403 j.linter.compileSdkVersion = lintSDKVersionString(j.SdkVersion(ctx))
Pedro Loureiro18233a22021-06-08 18:11:21 +00001404 j.linter.compileSdkKind = j.SdkVersion(ctx).Kind
Jaewoong Jung26342642021-03-17 15:56:23 -07001405 j.linter.javaLanguageLevel = flags.javaVersion.String()
1406 j.linter.kotlinLanguageLevel = "1.3"
1407 if !apexInfo.IsForPlatform() && ctx.Config().UnbundledBuildApps() {
1408 j.linter.buildModuleReportZip = true
1409 }
1410 j.linter.lint(ctx)
1411 }
1412
1413 ctx.CheckbuildFile(outputFile)
1414
1415 ctx.SetProvider(JavaInfoProvider, JavaInfo{
1416 HeaderJars: android.PathsIfNonNil(j.headerJarFile),
1417 ImplementationAndResourcesJars: android.PathsIfNonNil(j.implementationAndResourcesJar),
1418 ImplementationJars: android.PathsIfNonNil(j.implementationJarFile),
1419 ResourceJars: android.PathsIfNonNil(j.resourceJar),
1420 AidlIncludeDirs: j.exportAidlIncludeDirs,
1421 SrcJarArgs: j.srcJarArgs,
1422 SrcJarDeps: j.srcJarDeps,
1423 ExportedPlugins: j.exportedPluginJars,
1424 ExportedPluginClasses: j.exportedPluginClasses,
1425 ExportedPluginDisableTurbine: j.exportedDisableTurbine,
1426 JacocoReportClassesFile: j.jacocoReportClassesFile,
1427 })
1428
1429 // Save the output file with no relative path so that it doesn't end up in a subdirectory when used as a resource
1430 j.outputFile = outputFile.WithoutRel()
1431}
1432
Colin Crossa1ff7c62021-09-17 14:11:52 -07001433func (j *Module) useCompose() bool {
1434 return android.InList("androidx.compose.runtime_runtime", j.properties.Static_libs)
1435}
1436
Cole Faust75fffb12021-06-13 15:23:16 -07001437// Returns a copy of the supplied flags, but with all the errorprone-related
1438// fields copied to the regular build's fields.
1439func enableErrorproneFlags(flags javaBuilderFlags) javaBuilderFlags {
1440 flags.processorPath = append(flags.errorProneProcessorPath, flags.processorPath...)
1441
1442 if len(flags.errorProneExtraJavacFlags) > 0 {
1443 if len(flags.javacFlags) > 0 {
1444 flags.javacFlags += " " + flags.errorProneExtraJavacFlags
1445 } else {
1446 flags.javacFlags = flags.errorProneExtraJavacFlags
1447 }
1448 }
1449 return flags
1450}
1451
Jaewoong Jung26342642021-03-17 15:56:23 -07001452func (j *Module) compileJavaClasses(ctx android.ModuleContext, jarName string, idx int,
1453 srcFiles, srcJars android.Paths, flags javaBuilderFlags, extraJarDeps android.Paths) android.WritablePath {
1454
1455 kzipName := pathtools.ReplaceExtension(jarName, "kzip")
1456 if idx >= 0 {
1457 kzipName = strings.TrimSuffix(jarName, filepath.Ext(jarName)) + strconv.Itoa(idx) + ".kzip"
1458 jarName += strconv.Itoa(idx)
1459 }
1460
1461 classes := android.PathForModuleOut(ctx, "javac", jarName).OutputPath
1462 TransformJavaToClasses(ctx, classes, idx, srcFiles, srcJars, flags, extraJarDeps)
1463
1464 if ctx.Config().EmitXrefRules() {
1465 extractionFile := android.PathForModuleOut(ctx, kzipName)
1466 emitXrefRule(ctx, extractionFile, idx, srcFiles, srcJars, flags, extraJarDeps)
1467 j.kytheFiles = append(j.kytheFiles, extractionFile)
1468 }
1469
1470 return classes
1471}
1472
1473// Check for invalid kotlinc flags. Only use this for flags explicitly passed by the user,
1474// since some of these flags may be used internally.
1475func CheckKotlincFlags(ctx android.ModuleContext, flags []string) {
1476 for _, flag := range flags {
1477 flag = strings.TrimSpace(flag)
1478
1479 if !strings.HasPrefix(flag, "-") {
1480 ctx.PropertyErrorf("kotlincflags", "Flag `%s` must start with `-`", flag)
1481 } else if strings.HasPrefix(flag, "-Xintellij-plugin-root") {
1482 ctx.PropertyErrorf("kotlincflags",
1483 "Bad flag: `%s`, only use internal compiler for consistency.", flag)
1484 } else if inList(flag, config.KotlincIllegalFlags) {
1485 ctx.PropertyErrorf("kotlincflags", "Flag `%s` already used by build system", flag)
1486 } else if flag == "-include-runtime" {
1487 ctx.PropertyErrorf("kotlincflags", "Bad flag: `%s`, do not include runtime.", flag)
1488 } else {
1489 args := strings.Split(flag, " ")
1490 if args[0] == "-kotlin-home" {
1491 ctx.PropertyErrorf("kotlincflags",
1492 "Bad flag: `%s`, kotlin home already set to default (path to kotlinc in the repo).", flag)
1493 }
1494 }
1495 }
1496}
1497
1498func (j *Module) compileJavaHeader(ctx android.ModuleContext, srcFiles, srcJars android.Paths,
1499 deps deps, flags javaBuilderFlags, jarName string,
1500 extraJars android.Paths) (headerJar, jarjarHeaderJar android.Path) {
1501
1502 var jars android.Paths
1503 if len(srcFiles) > 0 || len(srcJars) > 0 {
1504 // Compile java sources into turbine.jar.
1505 turbineJar := android.PathForModuleOut(ctx, "turbine", jarName)
1506 TransformJavaToHeaderClasses(ctx, turbineJar, srcFiles, srcJars, flags)
1507 if ctx.Failed() {
1508 return nil, nil
1509 }
1510 jars = append(jars, turbineJar)
1511 }
1512
1513 jars = append(jars, extraJars...)
1514
1515 // Combine any static header libraries into classes-header.jar. If there is only
1516 // one input jar this step will be skipped.
1517 jars = append(jars, deps.staticHeaderJars...)
1518
1519 // we cannot skip the combine step for now if there is only one jar
1520 // since we have to strip META-INF/TRANSITIVE dir from turbine.jar
1521 combinedJar := android.PathForModuleOut(ctx, "turbine-combined", jarName)
1522 TransformJarsToJar(ctx, combinedJar, "for turbine", jars, android.OptionalPath{},
1523 false, nil, []string{"META-INF/TRANSITIVE"})
1524 headerJar = combinedJar
1525 jarjarHeaderJar = combinedJar
1526
1527 if j.expandJarjarRules != nil {
1528 // Transform classes.jar into classes-jarjar.jar
1529 jarjarFile := android.PathForModuleOut(ctx, "turbine-jarjar", jarName)
1530 TransformJarJar(ctx, jarjarFile, headerJar, j.expandJarjarRules)
1531 jarjarHeaderJar = jarjarFile
1532 if ctx.Failed() {
1533 return nil, nil
1534 }
1535 }
1536
1537 return headerJar, jarjarHeaderJar
1538}
1539
1540func (j *Module) instrument(ctx android.ModuleContext, flags javaBuilderFlags,
Yuntao Xu5b009ae2021-05-13 12:42:24 -07001541 classesJar android.Path, jarName string, specs string) android.OutputPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001542
1543 jacocoReportClassesFile := android.PathForModuleOut(ctx, "jacoco-report-classes", jarName)
1544 instrumentedJar := android.PathForModuleOut(ctx, "jacoco", jarName).OutputPath
1545
1546 jacocoInstrumentJar(ctx, instrumentedJar, jacocoReportClassesFile, classesJar, specs)
1547
1548 j.jacocoReportClassesFile = jacocoReportClassesFile
1549
1550 return instrumentedJar
1551}
1552
1553func (j *Module) HeaderJars() android.Paths {
1554 if j.headerJarFile == nil {
1555 return nil
1556 }
1557 return android.Paths{j.headerJarFile}
1558}
1559
1560func (j *Module) ImplementationJars() android.Paths {
1561 if j.implementationJarFile == nil {
1562 return nil
1563 }
1564 return android.Paths{j.implementationJarFile}
1565}
1566
Martin Stjernholm8be1e6d2021-09-15 03:34:04 +01001567func (j *Module) DexJarBuildPath() OptionalDexJarPath {
Jaewoong Jung26342642021-03-17 15:56:23 -07001568 return j.dexJarFile
1569}
1570
1571func (j *Module) DexJarInstallPath() android.Path {
1572 return j.installFile
1573}
1574
1575func (j *Module) ImplementationAndResourcesJars() android.Paths {
1576 if j.implementationAndResourcesJar == nil {
1577 return nil
1578 }
1579 return android.Paths{j.implementationAndResourcesJar}
1580}
1581
1582func (j *Module) AidlIncludeDirs() android.Paths {
1583 // exportAidlIncludeDirs is type android.Paths already
1584 return j.exportAidlIncludeDirs
1585}
1586
1587func (j *Module) ClassLoaderContexts() dexpreopt.ClassLoaderContextMap {
1588 return j.classLoaderContexts
1589}
1590
1591// Collect information for opening IDE project files in java/jdeps.go.
1592func (j *Module) IDEInfo(dpInfo *android.IdeInfo) {
1593 dpInfo.Deps = append(dpInfo.Deps, j.CompilerDeps()...)
1594 dpInfo.Srcs = append(dpInfo.Srcs, j.expandIDEInfoCompiledSrcs...)
1595 dpInfo.SrcJars = append(dpInfo.SrcJars, j.compiledSrcJars.Strings()...)
1596 dpInfo.Aidl_include_dirs = append(dpInfo.Aidl_include_dirs, j.deviceProperties.Aidl.Include_dirs...)
1597 if j.expandJarjarRules != nil {
1598 dpInfo.Jarjar_rules = append(dpInfo.Jarjar_rules, j.expandJarjarRules.String())
1599 }
1600 dpInfo.Paths = append(dpInfo.Paths, j.modulePaths...)
1601}
1602
1603func (j *Module) CompilerDeps() []string {
1604 jdeps := []string{}
1605 jdeps = append(jdeps, j.properties.Libs...)
1606 jdeps = append(jdeps, j.properties.Static_libs...)
1607 return jdeps
1608}
1609
1610func (j *Module) hasCode(ctx android.ModuleContext) bool {
1611 srcFiles := android.PathsForModuleSrcExcludes(ctx, j.properties.Srcs, j.properties.Exclude_srcs)
1612 return len(srcFiles) > 0 || len(ctx.GetDirectDepsWithTag(staticLibTag)) > 0
1613}
1614
1615// Implements android.ApexModule
1616func (j *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
1617 return j.depIsInSameApex(ctx, dep)
1618}
1619
1620// Implements android.ApexModule
1621func (j *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext,
1622 sdkVersion android.ApiLevel) error {
Jiyong Park92315372021-04-02 08:45:46 +09001623 sdkSpec := j.MinSdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001624 if !sdkSpec.Specified() {
Jaewoong Jung26342642021-03-17 15:56:23 -07001625 return fmt.Errorf("min_sdk_version is not specified")
1626 }
Jiyong Parkf1691d22021-03-29 20:11:58 +09001627 if sdkSpec.Kind == android.SdkCore {
Jaewoong Jung26342642021-03-17 15:56:23 -07001628 return nil
1629 }
Jooyung Han4c4da062021-06-23 10:23:16 +09001630 if sdkSpec.ApiLevel.GreaterThan(sdkVersion) {
1631 return fmt.Errorf("newer SDK(%v)", sdkSpec.ApiLevel)
Jaewoong Jung26342642021-03-17 15:56:23 -07001632 }
1633 return nil
1634}
1635
1636func (j *Module) Stem() string {
1637 return proptools.StringDefault(j.deviceProperties.Stem, j.Name())
1638}
1639
Jaewoong Jung26342642021-03-17 15:56:23 -07001640func (j *Module) JacocoReportClassesFile() android.Path {
1641 return j.jacocoReportClassesFile
1642}
1643
1644func (j *Module) IsInstallable() bool {
1645 return Bool(j.properties.Installable)
1646}
1647
1648type sdkLinkType int
1649
1650const (
1651 // TODO(jiyong) rename these for better readability. Make the allowed
1652 // and disallowed link types explicit
1653 // order is important here. See rank()
1654 javaCore sdkLinkType = iota
1655 javaSdk
1656 javaSystem
1657 javaModule
1658 javaSystemServer
1659 javaPlatform
1660)
1661
1662func (lt sdkLinkType) String() string {
1663 switch lt {
1664 case javaCore:
1665 return "core Java API"
1666 case javaSdk:
1667 return "Android API"
1668 case javaSystem:
1669 return "system API"
1670 case javaModule:
1671 return "module API"
1672 case javaSystemServer:
1673 return "system server API"
1674 case javaPlatform:
1675 return "private API"
1676 default:
1677 panic(fmt.Errorf("unrecognized linktype: %d", lt))
1678 }
1679}
1680
1681// rank determines the total order among sdkLinkType. An SDK link type of rank A can link to
1682// another SDK link type of rank B only when B <= A. For example, a module linking to Android SDK
1683// can't statically depend on modules that use Platform API.
1684func (lt sdkLinkType) rank() int {
1685 return int(lt)
1686}
1687
1688type moduleWithSdkDep interface {
1689 android.Module
Jiyong Park92315372021-04-02 08:45:46 +09001690 getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool)
Jaewoong Jung26342642021-03-17 15:56:23 -07001691}
1692
Jiyong Park92315372021-04-02 08:45:46 +09001693func (m *Module) getSdkLinkType(ctx android.BaseModuleContext, name string) (ret sdkLinkType, stubs bool) {
Jaewoong Jung26342642021-03-17 15:56:23 -07001694 switch name {
1695 case "core.current.stubs", "legacy.core.platform.api.stubs", "stable.core.platform.api.stubs",
1696 "stub-annotations", "private-stub-annotations-jar",
1697 "core-lambda-stubs", "core-generated-annotation-stubs":
1698 return javaCore, true
1699 case "android_stubs_current":
1700 return javaSdk, true
1701 case "android_system_stubs_current":
1702 return javaSystem, true
1703 case "android_module_lib_stubs_current":
1704 return javaModule, true
1705 case "android_system_server_stubs_current":
1706 return javaSystemServer, true
1707 case "android_test_stubs_current":
1708 return javaSystem, true
1709 }
1710
1711 if stub, linkType := moduleStubLinkType(name); stub {
1712 return linkType, true
1713 }
1714
Jiyong Park92315372021-04-02 08:45:46 +09001715 ver := m.SdkVersion(ctx)
Jiyong Parkf1691d22021-03-29 20:11:58 +09001716 switch ver.Kind {
1717 case android.SdkCore:
Jaewoong Jung26342642021-03-17 15:56:23 -07001718 return javaCore, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001719 case android.SdkSystem:
Jaewoong Jung26342642021-03-17 15:56:23 -07001720 return javaSystem, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001721 case android.SdkPublic:
Jaewoong Jung26342642021-03-17 15:56:23 -07001722 return javaSdk, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001723 case android.SdkModule:
Jaewoong Jung26342642021-03-17 15:56:23 -07001724 return javaModule, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001725 case android.SdkSystemServer:
Jaewoong Jung26342642021-03-17 15:56:23 -07001726 return javaSystemServer, false
Jiyong Parkf1691d22021-03-29 20:11:58 +09001727 case android.SdkPrivate, android.SdkNone, android.SdkCorePlatform, android.SdkTest:
Jaewoong Jung26342642021-03-17 15:56:23 -07001728 return javaPlatform, false
1729 }
1730
Jiyong Parkf1691d22021-03-29 20:11:58 +09001731 if !ver.Valid() {
1732 panic(fmt.Errorf("sdk_version is invalid. got %q", ver.Raw))
Jaewoong Jung26342642021-03-17 15:56:23 -07001733 }
1734 return javaSdk, false
1735}
1736
1737// checkSdkLinkType make sures the given dependency doesn't have a lower SDK link type rank than
1738// this module's. See the comment on rank() for details and an example.
1739func (j *Module) checkSdkLinkType(
1740 ctx android.ModuleContext, dep moduleWithSdkDep, tag dependencyTag) {
1741 if ctx.Host() {
1742 return
1743 }
1744
Jiyong Park92315372021-04-02 08:45:46 +09001745 myLinkType, stubs := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001746 if stubs {
1747 return
1748 }
Jiyong Park92315372021-04-02 08:45:46 +09001749 depLinkType, _ := dep.getSdkLinkType(ctx, ctx.OtherModuleName(dep))
Jaewoong Jung26342642021-03-17 15:56:23 -07001750
1751 if myLinkType.rank() < depLinkType.rank() {
1752 ctx.ModuleErrorf("compiles against %v, but dependency %q is compiling against %v. "+
1753 "In order to fix this, consider adjusting sdk_version: OR platform_apis: "+
1754 "property of the source or target module so that target module is built "+
1755 "with the same or smaller API set when compared to the source.",
1756 myLinkType, ctx.OtherModuleName(dep), depLinkType)
1757 }
1758}
1759
1760func (j *Module) collectDeps(ctx android.ModuleContext) deps {
1761 var deps deps
1762
1763 if ctx.Device() {
Jiyong Parkf1691d22021-03-29 20:11:58 +09001764 sdkDep := decodeSdkDep(ctx, android.SdkContext(j))
Jaewoong Jung26342642021-03-17 15:56:23 -07001765 if sdkDep.invalidVersion {
1766 ctx.AddMissingDependencies(sdkDep.bootclasspath)
1767 ctx.AddMissingDependencies(sdkDep.java9Classpath)
1768 } else if sdkDep.useFiles {
1769 // sdkDep.jar is actually equivalent to turbine header.jar.
1770 deps.classpath = append(deps.classpath, sdkDep.jars...)
1771 deps.aidlPreprocess = sdkDep.aidl
1772 } else {
1773 deps.aidlPreprocess = sdkDep.aidl
1774 }
1775 }
1776
Jiyong Park92315372021-04-02 08:45:46 +09001777 sdkLinkType, _ := j.getSdkLinkType(ctx, ctx.ModuleName())
Jaewoong Jung26342642021-03-17 15:56:23 -07001778
1779 ctx.VisitDirectDeps(func(module android.Module) {
1780 otherName := ctx.OtherModuleName(module)
1781 tag := ctx.OtherModuleDependencyTag(module)
1782
1783 if IsJniDepTag(tag) {
1784 // Handled by AndroidApp.collectAppDeps
1785 return
1786 }
1787 if tag == certificateTag {
1788 // Handled by AndroidApp.collectAppDeps
1789 return
1790 }
1791
1792 if dep, ok := module.(SdkLibraryDependency); ok {
1793 switch tag {
1794 case libTag:
Jiyong Park92315372021-04-02 08:45:46 +09001795 deps.classpath = append(deps.classpath, dep.SdkHeaderJars(ctx, j.SdkVersion(ctx))...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001796 case staticLibTag:
1797 ctx.ModuleErrorf("dependency on java_sdk_library %q can only be in libs", otherName)
1798 }
1799 } else if ctx.OtherModuleHasProvider(module, JavaInfoProvider) {
1800 dep := ctx.OtherModuleProvider(module, JavaInfoProvider).(JavaInfo)
1801 if sdkLinkType != javaPlatform &&
1802 ctx.OtherModuleHasProvider(module, SyspropPublicStubInfoProvider) {
1803 // dep is a sysprop implementation library, but this module is not linking against
1804 // the platform, so it gets the sysprop public stubs library instead. Replace
1805 // dep with the JavaInfo from the SyspropPublicStubInfoProvider.
1806 syspropDep := ctx.OtherModuleProvider(module, SyspropPublicStubInfoProvider).(SyspropPublicStubInfo)
1807 dep = syspropDep.JavaInfo
1808 }
1809 switch tag {
1810 case bootClasspathTag:
1811 deps.bootClasspath = append(deps.bootClasspath, dep.HeaderJars...)
1812 case libTag, instrumentationForTag:
1813 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1814 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1815 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1816 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1817 case java9LibTag:
1818 deps.java9Classpath = append(deps.java9Classpath, dep.HeaderJars...)
1819 case staticLibTag:
1820 deps.classpath = append(deps.classpath, dep.HeaderJars...)
1821 deps.staticJars = append(deps.staticJars, dep.ImplementationJars...)
1822 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.HeaderJars...)
1823 deps.staticResourceJars = append(deps.staticResourceJars, dep.ResourceJars...)
1824 deps.aidlIncludeDirs = append(deps.aidlIncludeDirs, dep.AidlIncludeDirs...)
1825 addPlugins(&deps, dep.ExportedPlugins, dep.ExportedPluginClasses...)
1826 // Turbine doesn't run annotation processors, so any module that uses an
1827 // annotation processor that generates API is incompatible with the turbine
1828 // optimization.
1829 deps.disableTurbine = deps.disableTurbine || dep.ExportedPluginDisableTurbine
1830 case pluginTag:
1831 if plugin, ok := module.(*Plugin); ok {
1832 if plugin.pluginProperties.Processor_class != nil {
1833 addPlugins(&deps, dep.ImplementationAndResourcesJars, *plugin.pluginProperties.Processor_class)
1834 } else {
1835 addPlugins(&deps, dep.ImplementationAndResourcesJars)
1836 }
1837 // Turbine doesn't run annotation processors, so any module that uses an
1838 // annotation processor that generates API is incompatible with the turbine
1839 // optimization.
1840 deps.disableTurbine = deps.disableTurbine || Bool(plugin.pluginProperties.Generates_api)
1841 } else {
1842 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1843 }
1844 case errorpronePluginTag:
1845 if _, ok := module.(*Plugin); ok {
1846 deps.errorProneProcessorPath = append(deps.errorProneProcessorPath, dep.ImplementationAndResourcesJars...)
1847 } else {
1848 ctx.PropertyErrorf("plugins", "%q is not a java_plugin module", otherName)
1849 }
1850 case exportedPluginTag:
1851 if plugin, ok := module.(*Plugin); ok {
1852 j.exportedPluginJars = append(j.exportedPluginJars, dep.ImplementationAndResourcesJars...)
1853 if plugin.pluginProperties.Processor_class != nil {
1854 j.exportedPluginClasses = append(j.exportedPluginClasses, *plugin.pluginProperties.Processor_class)
1855 }
1856 // Turbine doesn't run annotation processors, so any module that uses an
1857 // annotation processor that generates API is incompatible with the turbine
1858 // optimization.
1859 j.exportedDisableTurbine = Bool(plugin.pluginProperties.Generates_api)
1860 } else {
1861 ctx.PropertyErrorf("exported_plugins", "%q is not a java_plugin module", otherName)
1862 }
1863 case kotlinStdlibTag:
1864 deps.kotlinStdlib = append(deps.kotlinStdlib, dep.HeaderJars...)
1865 case kotlinAnnotationsTag:
1866 deps.kotlinAnnotations = dep.HeaderJars
Colin Crossa1ff7c62021-09-17 14:11:52 -07001867 case kotlinPluginTag:
1868 deps.kotlinPlugins = append(deps.kotlinPlugins, dep.ImplementationAndResourcesJars...)
Jaewoong Jung26342642021-03-17 15:56:23 -07001869 case syspropPublicStubDepTag:
1870 // This is a sysprop implementation library, forward the JavaInfoProvider from
1871 // the corresponding sysprop public stub library as SyspropPublicStubInfoProvider.
1872 ctx.SetProvider(SyspropPublicStubInfoProvider, SyspropPublicStubInfo{
1873 JavaInfo: dep,
1874 })
1875 }
1876 } else if dep, ok := module.(android.SourceFileProducer); ok {
1877 switch tag {
1878 case libTag:
1879 checkProducesJars(ctx, dep)
1880 deps.classpath = append(deps.classpath, dep.Srcs()...)
1881 case staticLibTag:
1882 checkProducesJars(ctx, dep)
1883 deps.classpath = append(deps.classpath, dep.Srcs()...)
1884 deps.staticJars = append(deps.staticJars, dep.Srcs()...)
1885 deps.staticHeaderJars = append(deps.staticHeaderJars, dep.Srcs()...)
1886 }
1887 } else {
1888 switch tag {
1889 case bootClasspathTag:
1890 // If a system modules dependency has been added to the bootclasspath
1891 // then add its libs to the bootclasspath.
1892 sm := module.(SystemModulesProvider)
1893 deps.bootClasspath = append(deps.bootClasspath, sm.HeaderJars()...)
1894
1895 case systemModulesTag:
1896 if deps.systemModules != nil {
1897 panic("Found two system module dependencies")
1898 }
1899 sm := module.(SystemModulesProvider)
1900 outputDir, outputDeps := sm.OutputDirAndDeps()
1901 deps.systemModules = &systemModules{outputDir, outputDeps}
1902 }
1903 }
1904
1905 addCLCFromDep(ctx, module, j.classLoaderContexts)
1906 })
1907
1908 return deps
1909}
1910
1911func addPlugins(deps *deps, pluginJars android.Paths, pluginClasses ...string) {
1912 deps.processorPath = append(deps.processorPath, pluginJars...)
1913 deps.processorClasses = append(deps.processorClasses, pluginClasses...)
1914}
1915
1916// TODO(b/132357300) Generalize SdkLibrarComponentDependency to non-SDK libraries and merge with
1917// this interface.
1918type ProvidesUsesLib interface {
1919 ProvidesUsesLib() *string
1920}
1921
1922func (j *Module) ProvidesUsesLib() *string {
1923 return j.usesLibraryProperties.Provides_uses_lib
1924}
satayev1c564cc2021-05-25 19:50:30 +01001925
1926type ModuleWithStem interface {
1927 Stem() string
1928}
1929
1930var _ ModuleWithStem = (*Module)(nil)